<?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>LP on .NET</title>
	<atom:link href="http://larryparkerdotnet.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://larryparkerdotnet.wordpress.com</link>
	<description>Adventures in C#, WPF, LINQ, etc.</description>
	<lastBuildDate>Wed, 18 Jan 2012 17:08:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='larryparkerdotnet.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>LP on .NET</title>
		<link>http://larryparkerdotnet.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://larryparkerdotnet.wordpress.com/osd.xml" title="LP on .NET" />
	<atom:link rel='hub' href='http://larryparkerdotnet.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Why I Blog &#8212; 2012</title>
		<link>http://larryparkerdotnet.wordpress.com/2012/01/02/why-i-blog-2012/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2012/01/02/why-i-blog-2012/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 22:57:27 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[blogging]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/?p=260</guid>
		<description><![CDATA[I’d like to wish the readers of my blog a very happy New Year and much success in 2012. I thought I’d take a few minutes to reflect on why I blog.  After all, I don’t get paid for it.  I haven’t written any books, I don’t speak at conferences, and blogging is not part [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=260&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’d like to wish the readers of my blog a very happy New Year and much success in 2012.</p>
<p>I thought I’d take a few minutes to reflect on why I blog.  After all, I don’t get paid for it.  I haven’t written any books, I don’t speak at conferences, and blogging is not part of my job.  Actually, I’m pretty much a no-name in the industry.  Just another C# coder swimming in the vast sea of technological talent. </p>
<p>So why do it?</p>
<p>Well… it’s because I like it.</p>
<p>Actually, I like programming more, but when I come across something really challenging at work and solve it, or when I learn about a new technique that I find really useful, I find that writing about it enhances my understanding of the subject.</p>
<p>So maybe blogging is a selfish thing.  <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>But actually, I truly appreciate when someone teaches me something new that helps me in my job (whether it be a colleague, an author of a book, or another blogger) and I find it rewarding when I publish a blog post and someone learns something from it, solves a problem, etc.  And it’s even more rewarding when someone leaves me a note to thank me.</p>
<p>So maybe that’s another selfish aspect of blogging.  I like being thanked for helping someone out. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Anyway, enough reflections on blogging and my place in the blogosphere.  If you’ve read this far, I hope you like my blog and you’ve found my posts to be useful.  I can’t promise to post every week (it’s tough with a day job), but I hope to continue enough to keep this blog useful and enjoyable for both you and me.</p>
<p>Have a great 2012!!!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/260/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=260&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2012/01/02/why-i-blog-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Internal Interfaces with Moq</title>
		<link>http://larryparkerdotnet.wordpress.com/2012/01/02/using-internal-interfaces-with-moq/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2012/01/02/using-internal-interfaces-with-moq/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 20:10:05 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/?p=253</guid>
		<description><![CDATA[Lately I’ve been using the C# internal modifier more and more for code that I intend to keep, well, internal to my assembly.  This has especially been the case for framework code that I have been writing that will not be accessed by framework consumers.  The internal modifier lets others know that it’s internal implementation, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=253&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately I’ve been using the C# <a href="http://msdn.microsoft.com/en-us/library/7c5ka91b(v=VS.100).aspx">internal</a> modifier more and more for code that I intend to keep, well, internal to my assembly.  This has especially been the case for framework code that I have been writing that will not be accessed by framework consumers.  The <em>internal</em> modifier lets others know that it’s <em>internal</em> implementation, subject to change, hands off, etc.</p>
<p>But one area of my code that I’ve had to begrudgingly keep public has been internally used interfaces because they could not be tested with Moq.  They compile just fine.  It’s just that Moq gives me a runtime error:  <em>Castle.DynamicProxy.Generators.GeneratorException: Type &lt;whatever&gt; is not public. Can not create proxy for types that are not accessible.</em></p>
<p>But before I get into the details, why would you want to use an internal interface anyway?  Aren’t interfaces by definition supposed to be public?  Well I guess if that were the case then Microsoft wouldn’t allow you to apply the <em>internal</em> modifier to them.  <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>But seriously, consider the case where you’re doing dependency injection where you hand a class a bunch of interface references in its constructor, but these interfaces are just internal to the assembly.  In other words, you’re writing testable code with injected interfaces to facilitate unit testing.  Just because they’re interfaces doesn’t mean you intend to publish them externally.  Hence the use of internal interfaces.</p>
<p>As an example, say you have a customer manager with an AddCustomer method that calls a persistence layer to add the customer to the database.  The code might look like this:</p>
<pre class="code"><span style="color:blue;">internal class </span><span style="color:#2b91af;">CustomerManager </span>{
    <span style="color:blue;">public </span>CustomerManager(<span style="color:#8014c7;">ICustomerPersistence </span>customerPersistence)
    {
        _customerPersistence = customerPersistence;
    }

    <span style="color:blue;">private </span><span style="color:#8014c7;">ICustomerPersistence </span>_customerPersistence;

    <span style="color:blue;">public void </span>AddCustomer(<span style="color:#2b91af;">String </span>customerName)
    {
        _customerPersistence.Add(customerName);
    }
}

<span style="color:blue;">internal interface </span><span style="color:#8014c7;">ICustomerPersistence </span>{
    <span style="color:blue;">void </span>Add(<span style="color:#2b91af;">String </span>customerName);
}</pre>
<p>Both the CustomerManager class and the ICustomerPersistence interface are marked as internal because they won’t be used outside the current assembly.  When we create our unit test for the AddCustomer method via Visual Studio’s <em>Create Unit Tests…</em> context menu option, it makes our unit test assembly a “friend” of the assembly containing the CustomerManager class:</p>
<pre class="code">[<span style="color:blue;">assembly</span>: <span style="color:#2b91af;">InternalsVisibleTo</span>(<span style="color:#a31515;">"CustomerTest, PublicKey=..."</span>)]</pre>
<p>&nbsp;</p>
<p>Now let’s write a unit test for the AddCustomer method that mocks the ICustomerPersistence interface:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>AddCustomerTest()
{
    <span style="color:blue;">var </span>customerPersistenceMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">ICustomerPersistence</span>&gt;();

    <span style="color:#2b91af;">CustomerManager </span>target = <span style="color:blue;">new </span><span style="color:#2b91af;">CustomerManager</span>(customerPersistenceMock.Object);

    <span style="color:#2b91af;">String </span>name = <span style="color:#a31515;">"Sue Jones"</span>;
    target.AddCustomer(name);
    customerPersistenceMock.Verify(o =&gt; o.Add(name));
}</pre>
<p>This compiles ok, but when we run the test we get the error mentioned above; i.e. that the ICustomerPersistence interface is not public and that Moq cannot create a proxy for it.</p>
<p>My workaround for this has been to grit my teeth and make the interface public:</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#8014c7;">ICustomerPersistence </span>{
    <span style="color:blue;">void </span>Add(<span style="color:#2b91af;">String </span>customerName);
}</pre>
<p>But once you do that, developers start asking you what the ICustomerPersistence interface is for (it’s public after all), how they should be using it, where is the documentation, etc.  All these problems because you just wanted to write a unit test that mocks the interface.  <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Fortunately, there’s a solution.  You just need to use the InternalsVisibleTo assembly attribute to make Moq a friend of the assembly containing the internal ICustomerPersistence interface.</p>
<p>Unfortunately, the Moq assembly name wasn’t so obvious and I couldn’t find it in the Moq documentation.  But after some searching, I found a couple of blog posts on it.  Since Moq is a signed assembly, you need to provide the public key to the InternalsVisibleTo attribute.  The tricky part is copying the public key correctly, and some of the blogs posts either had it wrong or had it formatted such that copying and pasting didn’t work properly.</p>
<p>But this blog post got it right: </p>
<p><a href="http://blog.ashmind.com/category/agile/mocking/">http://blog.ashmind.com/category/agile/mocking/</a></p>
<p>I’ll post the code here too, and I hope you’ll be able to copy and paste it into your own AssemblyInfo.cs file (you’ll need to scroll to the right to get the entire public key):</p>
<pre class="code"><span style="color:green;">// Make internal interfaces visible to Moq [</span><span style="color:blue;">assembly:</span><span style="color:#2b91af;">InternalsVisibleTo(</span><span style="color:#a31515;">"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] </span></pre>
<p>&nbsp;</p>
<p>Now I was able to change all of those public interfaces back to internal, which made my code just a little bit cleaner.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/253/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=253&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2012/01/02/using-internal-interfaces-with-moq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction to Unit Testing with Moq</title>
		<link>http://larryparkerdotnet.wordpress.com/2012/01/02/introduction-to-unit-testing-with-moq/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2012/01/02/introduction-to-unit-testing-with-moq/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 17:31:59 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/?p=249</guid>
		<description><![CDATA[If you’ve kept up with my blog over the last year or so, you may have noticed that I discussed certain aspects of unit testing (like writing testable code and unit testing using stubs) but haven’t mentioned much about mocking frameworks. Mocking frameworks, simply put, allow you to easily simulate behavior of objects and interfaces [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=249&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you’ve kept up with my blog over the last year or so, you may have noticed that I discussed certain aspects of unit testing (like <a href="http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/">writing testable code</a> and <a href="http://larryparkerdotnet.wordpress.com/2010/10/20/unit-testing-using-stubs/">unit testing using stubs</a>) but haven’t mentioned much about mocking frameworks.</p>
<p>Mocking frameworks, simply put, allow you to easily simulate behavior of objects and interfaces and are therefore very useful for unit testing.  But before I show an example of mocking, let’s see how we can do something similar by writing our own stubs.</p>
<p>The following example is from the <a href="http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/">Writing Testable Code</a> post:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserManager </span>{
    <span style="color:blue;">public </span>UserManager(<span style="color:#8014c7;">IUserPersistence </span>userPersistence, <span style="color:#8014c7;">IEmailManager </span>emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    <span style="color:blue;">private </span><span style="color:#8014c7;">IUserPersistence </span>_userPersistence;
    <span style="color:blue;">private </span><span style="color:#8014c7;">IEmailManager </span>_emailManager;

    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>RegisterUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">try </span>{
            <span style="color:#666600;">Boolean </span>result = <span style="color:blue;">false</span>;

            <span style="color:blue;">if </span>(_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            <span style="color:blue;">return </span>result;
        }
        <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
        {
            <span style="color:green;">// Log the exception... return false; </span>}
    }
}

<span style="color:blue;">public interface </span><span style="color:#8014c7;">IUserPersistence </span>{
    <span style="color:#666600;">Boolean </span>AddUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress);
    <span style="color:green;">// Other interface members... </span>}

<span style="color:blue;">public interface </span><span style="color:#8014c7;">IEmailManager </span>{
    <span style="color:#666600;">Boolean </span>SendUserRegistrationEmail(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress);
    <span style="color:green;">// Other interface members... </span>}</pre>
<p>&nbsp;</p>
<p>Note that the UserManager constructor takes parameters for the interface references used by RegisterUser.</p>
<p>Now we can write stubs to simulate these interfaces:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserPersistenceStub </span>: <span style="color:#8014c7;">IUserPersistence </span>{
    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>AddUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName,
        <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">return true</span>;
    }
}

<span style="color:blue;">public class </span><span style="color:#2b91af;">EmailManagerStub </span>: <span style="color:#8014c7;">IEmailManager </span>{
    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>SendUserRegistrationEmail(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName,
        <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">return true</span>;
    }
}</pre>
<p>&nbsp;</p>
<p>These stubs don’t do very much, but they allow us to use them in a unit test like this:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>RegisterUserTest()
{
    <span style="color:blue;">var </span>userPersistenceStub = <span style="color:blue;">new </span><span style="color:#2b91af;">UserPersistenceStub</span>();
    <span style="color:blue;">var </span>emailManagerStub = <span style="color:blue;">new </span><span style="color:#2b91af;">EmailManagerStub</span>();

    <span style="color:#2b91af;">UserManager </span>target = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(userPersistenceStub, emailManagerStub);
    <span style="color:#666600;">Boolean </span>actual = target.RegisterUser(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>);
    <span style="color:#2b91af;">Assert</span>.IsTrue(actual);
}</pre>
<p>&nbsp;</p>
<p>This test calls the RegisterUser method and simply asserts that it returns true.  If you look at the RegisterUser code, the only way that this will happen is if the SendUserRegistrationEmail method that it calls (via the IEmailManager reference) also returns true.</p>
<p>Since we wrote our IEmailManager stub to do this (i.e. the EmailManagerStub class) and also wrote our test to inject it into the UserManager constructor, our test passes.</p>
<p>So we didn’t even need a mocking framework to write a unit test in this example.  We simply wrote some stubs to simulate the interfaces needed by the method being tested.</p>
<p>However, the problem with stubs is that they are tedious to write.  That’s where a mocking framework comes in.  There are many excellent mocking frameworks out there, but I chose <a href="http://code.google.com/p/moq/">Moq</a> after a colleague gave me a quick demo.</p>
<p>Let’s rewrite our unit test to use Moq instead of stubs.  Assuming we’ve installed Moq and added a reference to our unit test project, we first need to do a “using” statement:</p>
<pre class="code"><span style="color:blue;">using </span>Moq;</pre>
<p>&nbsp;</p>
<p>Now we can rewrite our test like this:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>RegisterUserTest()
{
<strong> <span style="color:blue;">var </span>userPersistenceMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IUserPersistence</span>&gt;(); <span style="color:blue;">var </span>emailManagerMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IEmailManager</span>&gt;(); </strong>
    <span style="color:#2b91af;">UserManager </span>target = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(<strong>userPersistenceMock.Object, emailManagerMock.Object</strong>);
    <span style="color:#666600;">Boolean </span>actual = target.RegisterUser(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>);
    <span style="color:#2b91af;">Assert</span>.IsTrue(actual);
}</pre>
<p>&nbsp;</p>
<p>Instead of creating our own stub classes that implement the injected IUserPersistence and IEmailManager interfaces, we simply use the Mock&lt;T&gt; class and specify the interface we wish to mock.  Then we pass the mocked interfaces into our UserManager constructor with the mocked object’s Object property.</p>
<p>And we’re done.  No stub classes to write.  Wow, that was easy!  <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>So let’s run our test!</p>
<p><a href="http://larryparkerdotnet.files.wordpress.com/2012/01/image.png"><img style="display:inline;border-width:0;" title="image" src="http://larryparkerdotnet.files.wordpress.com/2012/01/image_thumb.png?w=538&#038;h=72" alt="image" width="538" height="72" border="0" /></a></p>
<p>Oops.  What happened?</p>
<p>Our test is expecting the RegisterUser method to return true but it didn’t.  As we saw when writing our stubs, the SendUserRegistrationEmail method needs to return true, so that’s what we did for the stub.</p>
<p>But how do we tell Moq to return true for this method?</p>
<p>To do this, we need to set up our mock object like this:</p>
<pre class="code"><span style="color:blue;">var </span>emailManagerMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IEmailManager</span>&gt;();
<strong>emailManagerMock.Setup(o =&gt; o.SendUserRegistrationEmail(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>)) .Returns(<span style="color:blue;">true</span>);</strong></pre>
<p>&nbsp;</p>
<p>This tells the Moq framework that when IEmailManager.SendUserRegistrationEmail is called with the above parameters that it will return true.  The lambda expression variable (“o” in this case) is typed to the interface being mocked (i.e. IEmailManager).</p>
<p>We also need to do something similar for IUserPersistence so our test can pass.  Here’s the full test:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>RegisterUserTest()
{
    <span style="color:blue;">var </span>userPersistenceMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IUserPersistence</span>&gt;();
    userPersistenceMock.Setup(o =&gt; o.AddUser(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>))
        .Returns(<span style="color:blue;">true</span>);

    <span style="color:blue;">var </span>emailManagerMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IEmailManager</span>&gt;();
    emailManagerMock.Setup(o =&gt; o.SendUserRegistrationEmail(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>))
        .Returns(<span style="color:blue;">true</span>);

    <span style="color:#2b91af;">UserManager </span>target = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(userPersistenceMock.Object, emailManagerMock.Object);
    <span style="color:#666600;">Boolean </span>actual = target.RegisterUser(<span style="color:#a31515;">"Smith"</span>, <span style="color:#a31515;">"Bert"</span>, <span style="color:#a31515;">"bsmith@wherever.com"</span>);
    <span style="color:#2b91af;">Assert</span>.IsTrue(actual);
}</pre>
<p>&nbsp;</p>
<p>Now when we run our test it passes! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href="http://larryparkerdotnet.files.wordpress.com/2012/01/image1.png"><img style="display:inline;border-width:0;" title="image" src="http://larryparkerdotnet.files.wordpress.com/2012/01/image_thumb1.png?w=400&#038;h=70" alt="image" width="400" height="70" border="0" /></a></p>
<p>Much easier with Moq than writing our own stubs.  You can consider stubs a thing of the past.</p>
<p>But our test can be simplified a bit.  We don’t really care about specific parameters passed to our interface methods, so we can use Moq’s “It” class to make our test setups a bit more general:</p>
<pre class="code"><span style="color:blue;">var </span>userPersistenceMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IUserPersistence</span>&gt;();
userPersistenceMock.Setup(o =&gt; o.AddUser(<span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;(), <span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;(), <span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;()))
    .Returns(<span style="color:blue;">true</span>);

<span style="color:blue;">var </span>emailManagerMock = <span style="color:blue;">new </span><span style="color:#2b91af;">Mock</span>&lt;<span style="color:#8014c7;">IEmailManager</span>&gt;();
emailManagerMock.Setup(o =&gt; o.SendUserRegistrationEmail(<span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;(), <span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;(), <span style="color:#2b91af;">It</span>.IsAny&lt;<span style="color:#2b91af;">String</span>&gt;()))
    .Returns(<span style="color:blue;">true</span>);</pre>
<p>&nbsp;</p>
<p>This tells Moq that we’re setting up a return value of true for these two methods when <em>any</em> parameters are passed to it.  For our test, this is acceptable.</p>
<p>Well, that was a quick introduction to Moq.  Hopefully I’ve demonstrated that mocking frameworks (like Moq) can be very useful for writing unit tests since they make it easy to simulate the behavior of the objects and interfaces used by the code being tested.</p>
<p>Once I grasped the power of Moq, I never looked back.</p>
<p>Happy mocking!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/249/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=249&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2012/01/02/introduction-to-unit-testing-with-moq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>

		<media:content url="http://larryparkerdotnet.files.wordpress.com/2012/01/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://larryparkerdotnet.files.wordpress.com/2012/01/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Case-Invariant Dictionaries</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/12/27/case-invariant-dictionaries/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/12/27/case-invariant-dictionaries/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 20:26:27 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/?p=242</guid>
		<description><![CDATA[A few months back I posted about case-invariant string comparisons using the Equals method and the StringComparison enum.&#160; This approach made it a bit more efficient to compare strings without regards to their case since it wasn’t necessary to convert the strings to lower or upper case. But what if you have a dictionary that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=242&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A few months back I <a href="http://larryparkerdotnet.wordpress.com/2011/08/03/case-invariant-string-comparisons/">posted</a> about case-invariant string comparisons using the Equals method and the StringComparison enum.&#160; This approach made it a bit more efficient to compare strings without regards to their case since it wasn’t necessary to convert the strings to lower or upper case.</p>
<p>But what if you have a dictionary that is keyed by a string and you wish the lookup to be case insensitive?&#160; The following unit test demonstrates the problem, using a dictionary of city names and temperatures:</p>
<pre class="code"><span style="color:blue;">private </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt; GetDictionary()
{
    <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt; dict = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt;()
    {
        {<span style="color:#a31515;">&quot;New York&quot;</span>, 42},
        {<span style="color:#a31515;">&quot;Boston&quot;</span>, 35},
        {<span style="color:#a31515;">&quot;Atlanta&quot;</span>, 58}
    };
    <span style="color:blue;">return </span>dict;
}

[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>CaseInsensitive_KeyNotFound_Test()
{
    <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt; dict = GetDictionary();

    <span style="color:#2b91af;">Assert</span>.IsFalse(dict.ContainsKey(<span style="color:#a31515;">&quot;new york&quot;</span>));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As the test shows, searching the dictionary for the lower-case city of “new york” fails.&#160; If you ask the user to input a city name and they don’t enter it as mixed case, you’re out of luck.</p>
<p>A workaround is to store the cities in the dictionary as upper (or lower) case and always ensure you search by the same case.&#160; But that gets a bit messy.</p>
<p>Fortunately there’s a better way.&#160; One of the Dictionary&lt;TKey, TValue&gt; <a href="http://msdn.microsoft.com/en-us/library/ms132072.aspx">constructors</a> takes an IEqualityComparer&lt;TKey&gt; that lets you specify how you would like to compare the key of the dictionary.</p>
<p>The following unit test demonstrates this:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>CaseInsensitive_KeyFound_Test()
{
    <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt; dict = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">String</span>, <span style="color:#666600;">Int32</span>&gt;(<strong><span style="color:#2b91af;">StringComparer</span>.OrdinalIgnoreCase</strong>)
    {
        {<span style="color:#a31515;">&quot;New York&quot;</span>, 42},
        {<span style="color:#a31515;">&quot;Boston&quot;</span>, 35},
        {<span style="color:#a31515;">&quot;Atlanta&quot;</span>, 58}
    };

    <span style="color:#2b91af;">Assert</span>.IsTrue(dict.ContainsKey(<span style="color:#a31515;">&quot;new york&quot;</span>));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In this example, we pass in a StringComparer.OrdinalIgnoreCase parameter that tells the dictionary to perform a case-insensitive string comparison.&#160; This lets us find our New York entry regardless of case.&#160; Now we have a better chance of finding the city when the user searches for it.</p>
<p>This is a very handy technique that also works with <a href="http://msdn.microsoft.com/en-us/library/bb359100.aspx">HashSet&lt;T&gt;</a>.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/242/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/242/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/242/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=242&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/12/27/case-invariant-dictionaries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Ignoring Unit Tests</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/12/14/ignoring-unit-tests/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/12/14/ignoring-unit-tests/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 03:19:28 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/?p=239</guid>
		<description><![CDATA[Have you ever had a unit test that you didn’t want executed as part of your team’s test runs?&#160; For example, if it requires external data but you haven’t yet set up the test database.&#160; Or you’ve been using a unit test as a workbench for developing some code that you’re interacting with in the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=239&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Have you ever had a unit test that you didn’t want executed as part of your team’s test runs?&#160; For example, if it requires external data but you haven’t yet set up the test database.&#160; Or you’ve been using a unit test as a workbench for developing some code that you’re interacting with in the debugger and don’t really want it to be run by others.</p>
<p>Up until recently, I would either comment out the [TestMethod] attribute or comment out the entire test method’s code.</p>
<p>But there’s a better way, as a colleague of mine recently advised – the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.ignoreattribute.aspx">[Ignore]</a> attribute.</p>
<p>Decorating your test method with this attribute will prevent it from being run.</p>
<p>The nice thing about this is your test code will still be compiled and refactored with the rest of your codebase.</p>
<p>When you do want the test to run while you’re working with it, just uncomment the [Ignore] attribute.&#160; Then when you’re ready to check in your test, comment it back and you’re all set to go.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/239/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=239&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/12/14/ignoring-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Using a Collection Initializer with a Dictionary</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/09/06/using-a-collection-initializer-with-a-dictionary/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/09/06/using-a-collection-initializer-with-a-dictionary/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 02:39:33 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/2011/09/06/using-a-collection-initializer-with-a-dictionary/</guid>
		<description><![CDATA[Collection initializers (introduced in C# 3.0) provide an easy way to initialize a collection of items.&#160; For example, instead of doing this… List&#60;Color&#62; colors = new List&#60;Color&#62;(); colors.Add(new Color { Value = 0xFFF0F8FF, Name = &#34;Alice Blue&#34; }); colors.Add(new Color { Value = 0xFF9400D3, Name = &#34;Dark Violet&#34; }); colors.Add(new Color { Value = 0xFF708090, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=237&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">Collection initializers</a> (introduced in C# 3.0) provide an easy way to initialize a collection of items.&#160; For example, instead of doing this…</p>
<pre class="code"><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Color</span>&gt; colors = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Color</span>&gt;();
colors.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFFF0F8FF, Name = <span style="color:#a31515;">&quot;Alice Blue&quot; </span>});
colors.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFF9400D3, Name = <span style="color:#a31515;">&quot;Dark Violet&quot; </span>});
colors.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFF708090, Name = <span style="color:#a31515;">&quot;Slate Gray&quot; </span>});</pre>
<p>…we can do this:</p>
<pre class="code"><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Color</span>&gt; colors = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Color</span>&gt;
{
    <span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFFF0F8FF, Name = <span style="color:#a31515;">&quot;Alice Blue&quot; </span>},
    <span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFF9400D3, Name = <span style="color:#a31515;">&quot;Dark Violet&quot; </span>},
    <span style="color:blue;">new </span><span style="color:#2b91af;">Color </span>{ Value = 0xFF708090, Name = <span style="color:#a31515;">&quot;Slate Gray&quot; </span>}
};</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>But what if we want to initialize a dictionary?&#160; The traditional way would be like this:</p>
<pre class="code"><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt; colors = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;();
colors.Add(0xFFF0F8FF, <span style="color:#a31515;">&quot;Alice Blue&quot;</span>);
colors.Add(0xFF9400D3, <span style="color:#a31515;">&quot;Dark Violet&quot;</span>);
colors.Add(0xFF708090, <span style="color:#a31515;">&quot;Slate Gray&quot;</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a>But how would we use a collection initializer?&#160; When you iterate through a dictionary, each item is a KeyValuePair&lt;TKey, TValue&gt;.&#160; But we can’t do this:</p>
<pre class="code"><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt; colors = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;
{
    <span style="color:blue;">new </span><span style="color:#2b91af;">KeyValuePair</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;(0xFFF0F8FF, <span style="color:#a31515;">&quot;Alice Blue&quot;</span>),
    <span style="color:blue;">new </span><span style="color:#2b91af;">KeyValuePair</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;(0xFF9400D3, <span style="color:#a31515;">&quot;Dark Violet&quot;</span>),
    <span style="color:blue;">new </span><span style="color:#2b91af;">KeyValuePair</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;(0xFF708090, <span style="color:#a31515;">&quot;Slate Gray&quot;</span>)
};</pre>
<p><a href="http://11011.net/software/vspaste"></a>The solution is not entirely obvious, but it is succinct:</p>
<pre class="code"><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt; colors = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:#2b91af;">UInt32</span>, <span style="color:#2b91af;">String</span>&gt;
{
    { 0xFFF0F8FF, <span style="color:#a31515;">&quot;Alice Blue&quot; </span>},
    { 0xFF9400D3, <span style="color:#a31515;">&quot;Dark Violet&quot; </span>},
    { 0xFF708090, <span style="color:#a31515;">&quot;Slate Gray&quot; </span>}
};</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is not mentioned in the MSDN <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">link</a> shown above, but MSDN does discuss it <a href="http://msdn.microsoft.com/en-us/library/bb531208.aspx">here</a>.</p>
<p>Hope this helps!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/237/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/237/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=237&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/09/06/using-a-collection-initializer-with-a-dictionary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Dependency Injection and Delegates</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/08/29/dependency-injection-and-delegates/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/08/29/dependency-injection-and-delegates/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 02:46:55 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/2011/08/29/dependency-injection-and-delegates/</guid>
		<description><![CDATA[A couple of weeks ago I blogged about writing testable code using dependency injection.&#160; This was done by injecting interface references into a class’s constructor: public UserManager(IUserPersistence userPersistence, IEmailManager emailManager) { _userPersistence = userPersistence; _emailManager = emailManager; } Assuming we have concrete classes called UserPersistence and EmailManager that implement these interfaces, we could simply inject [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=233&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I <a href="http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/">blogged about</a> writing testable code using dependency injection.&#160; This was done by injecting interface references into a class’s constructor:</p>
<pre class="code"><span style="color:blue;">public </span>UserManager(<span style="color:#8014c7;">IUserPersistence </span>userPersistence, <span style="color:#8014c7;">IEmailManager </span>emailManager)
{
    _userPersistence = userPersistence;
    _emailManager = emailManager;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Assuming we have concrete classes called UserPersistence and EmailManager that implement these interfaces, we could simply inject the dependencies like this:</p>
<pre class="code"><span style="color:blue;">public void </span>DoIt()
{
    <span style="color:#2b91af;">UserManager </span>userManager = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(
        <strong><span style="color:blue;">new </span><span style="color:#2b91af;">UserPersistence</span>()</strong>, <strong><span style="color:blue;">new </span><span style="color:#2b91af;">EmailManager</span>()</strong>);
}</pre>
<p>But what happens if the dependencies cannot actually be injected during construction because it’s too early to create them?&#160; A good example of this is when the concrete classes themselves are constructed with a parameter that is not yet available.</p>
<p>Let’s say that when we register a user we get a guid back from our persistence layer that identifies the user.&#160; Now let’s also say that our IEmailManager interface is written to apply to a single user at a time, and there’s a concrete class called EmailManager with a constructor that looks like this:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">EmailManager </span>: <span style="color:#8014c7;">IEmailManager
</span>{
    <span style="color:blue;">public </span>EmailManager(<strong><span style="color:#666600;">Guid </span>userId</strong>)
    {
        _userId = userId;
    }
...
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Since we don’t know the guid until we register the user (via the UserManager class), we can’t inject an IEmailManager into the UserManager class’s constructor.</p>
<pre class="code"><span style="color:blue;">public void </span>DoIt()
{
    <span style="color:#2b91af;">UserManager </span>userManager = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(
        <span style="color:blue;">new </span><span style="color:#2b91af;">UserPersistence</span>(), <span style="color:blue;">new </span><span style="color:#2b91af;">EmailManager</span>(<strong><em>&lt;oops!  What’s the guid?&gt;</em></strong>));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The solution is to change UserManager’s constructor to take a delegate instead of an interface:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserManager
</span>{
    <span style="color:blue;">public </span>UserManager(<span style="color:#8014c7;">IUserPersistence </span>userPersistence,
<strong>        <span style="color:magenta;">Func</span>&lt;<span style="color:#666600;">Guid</span>, <span style="color:#8014c7;">IEmailManager</span>&gt; emailManagerFactory)
</strong>    {
        _userPersistence = userPersistence;
        _emailManagerFactory = emailManagerFactory;
    }

    <span style="color:blue;">private </span><span style="color:#8014c7;">IUserPersistence </span>_userPersistence;
<strong>    <span style="color:blue;">private </span><span style="color:magenta;">Func</span>&lt;<span style="color:#666600;">Guid</span>, <span style="color:#8014c7;">IEmailManager</span>&gt; _emailManagerFactory;
</strong></pre>
<p>Instead of the UserManager constructor directly taking an IEmailManager, it now takes a <em>delegate</em> that expects a guid and <em>returns</em> an IEmailManager.</p>
<p>Since the delegate is only <em>supplied</em> during UserManager’s construction and <em>not executed</em>, we don’t need to know the guid at this time:</p>
<pre class="code"><span style="color:blue;">public void </span>DoIt()
{
    <span style="color:#2b91af;">UserManager </span>userManager = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(
        <span style="color:blue;">new </span><span style="color:#2b91af;">UserPersistence</span>(), <strong>o =&gt; <span style="color:blue;">new </span><span style="color:#2b91af;">EmailManager</span>(o)</strong>);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Our delegate can be passed in several ways, but a lambda expression is a nice easy way to do it (“o” is a local variable of type Guid).</p>
<p>With this new approach, our RegisterUser method from our <a href="http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/">previous post</a> now looks like this:</p>
<pre class="code"><span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>RegisterUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress)
{
    <span style="color:blue;">try
    </span>{
        <span style="color:#666600;">Boolean </span>result = <span style="color:blue;">false</span>;

        <strong><span style="color:#666600;">Guid </span>userId</strong> = _userPersistence.AddUser(lastName, firstName, emailAddress);

<strong>        <span style="color:#8014c7;">IEmailManager </span>emailManager = _emailManagerFactory(userId);
        result = emailManager.SendLoginInfo();
</strong>
        <span style="color:blue;">return </span>result;
    }
    <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
    {
        <span style="color:green;">// Log the exception...

        </span><span style="color:blue;">return false</span>;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Note that when we execute our delegate (i.e. the _emailManagerFactory field) we pass in the user ID guid as a parameter (i.e. the value we just obtained from calling the AddUser method) and get back our IEmailManager interface reference.&#160; Now we can call its methods and they will all act on the newly registered user.</p>
<p>Delegates are a great way to defer execution until needed, and this is a very useful technique to let you follow the dependency injection pattern even when you don’t have everything you need during object construction.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/233/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=233&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/08/29/dependency-injection-and-delegates/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Serializing and Deserializing JSON Data</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/08/19/serializing-and-deserializing-json-data/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/08/19/serializing-and-deserializing-json-data/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 23:31:17 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/2011/08/19/serializing-and-deserializing-json-data/</guid>
		<description><![CDATA[My team is working on a web site that consumes JSON (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data. I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.&#160; A colleague pointed me to MSDN (always a good [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=223&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My team is working on a web site that consumes <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data.</p>
<p>I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.&#160; A colleague pointed me to MSDN (always a good start) with <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx">this link</a>, and a quick search pointed me to <a href="http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx">this site</a> which had some nice JSON helpers.</p>
<p>After looking at the examples on both sites, I wrote some extension methods to make things easier.&#160; Here’s what I came up with (after some suggestions on the method names by my team):</p>
<pre class="code"><span style="color:blue;">public static class </span><span style="color:#2b91af;">JsonExtensionMethods
</span>{
    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Serializes an object to a JSON string.
    </span><span style="color:gray;">/// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;</span><span style="color:green;">The serializable class.</span><span style="color:gray;">&lt;/typeparam&gt;
    /// &lt;param name=&quot;entity&quot;&gt;</span><span style="color:green;">The object that will be serialized to JSON.</span><span style="color:gray;">&lt;/param&gt;
    /// &lt;returns&gt;</span><span style="color:green;">Returns a serialized representation of the object as a JSON string.</span><span style="color:gray;">&lt;/returns&gt;
    </span><span style="color:blue;">public static </span><span style="color:#2b91af;">String </span>ToJson&lt;T&gt;(<span style="color:blue;">this </span>T entity)
        <span style="color:blue;">where </span>T : <span style="color:blue;">class
    </span>{
        <span style="color:#2b91af;">String </span>result = <span style="color:blue;">null</span>;

        <span style="color:#2b91af;">DataContractJsonSerializer </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractJsonSerializer</span>(<span style="color:blue;">typeof</span>(T));

        <span style="color:blue;">using </span>(<span style="color:#2b91af;">MemoryStream </span>ms = <span style="color:blue;">new </span><span style="color:#2b91af;">MemoryStream</span>())
        {
            serializer.WriteObject(ms, entity);
            result = <span style="color:#2b91af;">Encoding</span>.Default.GetString(ms.ToArray());
        }

        <span style="color:blue;">return </span>result;
    }

    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Deserializes a JSON string into an object.
    </span><span style="color:gray;">/// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;</span><span style="color:green;">The class to deserialize the JSON string into.</span><span style="color:gray;">&lt;/typeparam&gt;
    /// &lt;param name=&quot;jsonObject&quot;&gt;</span><span style="color:green;">The serialized object as a JSON string.</span><span style="color:gray;">&lt;/param&gt;
    /// &lt;returns&gt;</span><span style="color:green;">Returns an instance of the concrete class representing the JSON string.</span><span style="color:gray;">&lt;/returns&gt;
    </span><span style="color:blue;">public static </span>T FromJson&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">String </span>jsonObject)
        <span style="color:blue;">where </span>T : <span style="color:blue;">class
    </span>{
        T entity = <span style="color:#2b91af;">Activator</span>.CreateInstance&lt;T&gt;();

        <span style="color:blue;">using </span>(<span style="color:#2b91af;">MemoryStream </span>ms = <span style="color:blue;">new </span><span style="color:#2b91af;">MemoryStream</span>(<span style="color:#2b91af;">Encoding</span>.Unicode.GetBytes(jsonObject)))
        {
            <span style="color:#2b91af;">DataContractJsonSerializer </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractJsonSerializer</span>(<span style="color:blue;">typeof</span>(T));
            entity = (T)serializer.ReadObject(ms);
        }

        <span style="color:blue;">return </span>entity;
    }
}</pre>
<p>Here are some unit tests that show how they are used:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>SerializeTest()
{
    <span style="color:#2b91af;">Customer </span>customer = <span style="color:blue;">new </span><span style="color:#2b91af;">Customer </span>{ FirstName = <span style="color:#a31515;">&quot;Joe&quot;</span>, LastName = <span style="color:#a31515;">&quot;Smith&quot; </span>};

    <span style="color:#2b91af;">String </span>actual = <strong>customer.ToJson()</strong>;

    <span style="color:#2b91af;">Assert</span>.AreEqual(<span style="color:#a31515;">&quot;{\&quot;FirstName\&quot;:\&quot;Joe\&quot;,\&quot;LastName\&quot;:\&quot;Smith\&quot;}&quot;</span>, actual);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>DeserializeTest()
{
    <span style="color:#2b91af;">String </span>jsonObject = <span style="color:#a31515;">&quot;{\&quot;FirstName\&quot;:\&quot;Joe\&quot;,\&quot;LastName\&quot;:\&quot;Smith\&quot;}&quot;</span>;

    <span style="color:#2b91af;">Customer </span>actual = <strong>jsonObject.FromJson&lt;<span style="color:#2b91af;">Customer</span>&gt;()</strong>;

    <span style="color:#2b91af;">Assert</span>.AreEqual(<span style="color:#a31515;">&quot;Joe&quot;</span>, actual.FirstName);
    <span style="color:#2b91af;">Assert</span>.AreEqual(<span style="color:#a31515;">&quot;Smith&quot;</span>, actual.LastName);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Both of the tests use a class called Customer that looks like this:</p>
<pre class="code">[<span style="color:#2b91af;">DataContract</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">Customer
</span>{
    [<span style="color:#2b91af;">DataMember</span>]
    <span style="color:blue;">public </span><span style="color:#2b91af;">String </span>LastName { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    [<span style="color:#2b91af;">DataMember</span>]
    <span style="color:blue;">public </span><span style="color:#2b91af;">String </span>FirstName { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</pre>
<p>Notice that the ToJson extension method is applied to a class, while the FromJson extension method is applied to a string.&#160; The extension methods are a nice touch because you don’t have to go through a static helper class in your code, but instead just use the applicable extension methods directly on your variable (depending if you’re serializing to JSON or deserializing from JSON).</p>
<p>Hope you like it!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/223/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/223/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/223/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=223&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/08/19/serializing-and-deserializing-json-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing Testable Code</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/#comments</comments>
		<pubDate>Sun, 14 Aug 2011 21:59:23 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/</guid>
		<description><![CDATA[About a year ago, my idea of unit testing included anything that could be tested no matter how heavy the setup.&#160; This included having an available test database, available web services, and other external resources (like the file system) that were needed to test my code. While this kind of test environment is useful, it’s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=210&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>About a year ago, my idea of unit testing included anything that could be tested no matter how heavy the setup.&#160; This included having an available test database, available web services, and other external resources (like the file system) that were needed to test my code.</p>
<p>While this kind of test environment is useful, it’s more along the lines of an integrated test environment that QA would have set up.&#160; Test likes these can really be categorized as <em>integration tests</em> and not <em>unit tests</em>.</p>
<p>If you want to really unit test your code, you don’t want any of the aforementioned dependencies to be part of your tests.&#160; Unit tests should be fast and should just test a single piece of code – not your entire application’s runtime environment.</p>
<p>Let’s take a look at both of these approaches.&#160; Consider the following code that registers a user with your application:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserManager </span>
{
    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>RegisterUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">try </span>
        {
            <span style="color:#2b91af;">String </span>connString = <span style="color:#a31515;">&quot;...&quot;</span>;

            <span style="color:blue;">using </span>(<span style="color:blue;">var </span>connection = <span style="color:blue;">new </span><span style="color:#2b91af;">SqlConnection</span>(connString))
            <span style="color:blue;">using </span>(<span style="color:blue;">var </span>cmd = <span style="color:blue;">new </span><span style="color:#2b91af;">SqlCommand</span>())
            {
                cmd.CommandText = <span style="color:#a31515;">@&quot;
INSERT INTO User (LastName, FirstName, EmailAddress)
VALUES (@LastName, @FirstName, @EmailAddress)
&quot;</span>;

                cmd.Parameters.Add(<span style="color:#a31515;">&quot;LastName&quot;</span>, <span style="color:olive;">SqlDbType</span>.NVarChar).Value = lastName;
                cmd.Parameters.Add(<span style="color:#a31515;">&quot;FirstName&quot;</span>, <span style="color:olive;">SqlDbType</span>.NVarChar).Value = firstName;
                cmd.Parameters.Add(<span style="color:#a31515;">&quot;EmailAddress&quot;</span>, <span style="color:olive;">SqlDbType</span>.NVarChar).Value = emailAddress;

                connection.Open();
                cmd.Connection = connection;
                cmd.ExecuteNonQuery();
            }

            <span style="color:blue;">return true</span>;
        }
        <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
        {
            <span style="color:green;">// Log the exception... </span><span style="color:blue;">return false</span>;
        }
    }
}</pre>
<p>Now let’s write a test for the RegisterUser method.</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>RegisterUserTest()
{
    <span style="color:#2b91af;">UserManager </span>target = <span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>();
    <span style="color:#666600;">Boolean </span>actual = target.RegisterUser(<span style="color:#a31515;">&quot;Smith&quot;</span>, <span style="color:#a31515;">&quot;Bert&quot;</span>, <span style="color:#a31515;">&quot;bsmith@wherever.com&quot;</span>);
    <span style="color:#2b91af;">Assert</span>.IsTrue(actual);
}</pre>
<p>This test attempts to register a user named Bert Smith and verifies that the registration succeeded (i.e. we assert that the RegisterUser method returned true).</p>
<p>The test is simple enough, but in order to run it <em>we need a database and also a User table in it</em>.&#160; It’s possible to set up a test database like this and ensure that the connection string is supplied for the test.&#160; But now we have a heavy dependency that probably needs to be in a certain state every time we run the test (e.g. we probably don’t already want the user Bert Smith in the database before we run the test).</p>
<p>Let’s step back a second and ask ourselves exactly what we want to test in our RegisterUser test.&#160; Do we want to test that ADO.NET works?&#160; Hopefully Microsoft has already tested that well enough.&#160; Do we want to test that we can write SQL that inserts a row into our User table?&#160; At some point, but not right now.</p>
<p>The job of the RegisterUser method is to <em>register a user with our system</em>.&#160; This probably involves some data validation (like ensuring the email address was supplied and is in a valid format), adding the user to persistent storage (like in a User table in a SQL database), and possibly sending an email to the user to let him know the registration succeeded.</p>
<p>All of these things are possible tasks that the RegisterUser method might need to execute, but we don’t necessarily want to test the tasks themselves – <em>we only want to test that the tasks were called in the expected way</em>.</p>
<p>Consider the email step.&#160; How would we test that anyway?&#160; We could use .NET’s SmtpClient class and have RegisterUser send the registration email to ourselves via our company’s email server (if we had rights to do so) and verify that we did indeed receive the email in our inbox.</p>
<p>The problem with this is that <em>you</em> need to verify that the email arrived in your inbox by <em>looking</em> at your inbox.&#160; But when you run this test along with hundreds of other tests, you are not going to do this.&#160; And neither is an automated test system.</p>
<p>So how do we write our RegisterUser test so we can test what we need without having all of these external dependencies?</p>
<p>The answer is:&#160; <em><strong>dependency injection</strong></em>.</p>
<p>Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system.&#160; There are plenty of discussions about this (<a href="http://martinfowler.com/articles/injection.html">Martin Fowler</a>, <a href="http://en.wikipedia.org/wiki/Dependency_injection">Wikipedia</a>, etc.), but in a nutshell you simply hand the dependencies (typically as interfaces) to your class or method which then works with them in an abstract way.&#160; In other words, instead of working directly with ADO.NET, your method works with an interface responsible for adding the user to persistent storage.</p>
<p>Let’s revisit the RegisterUser method with a couple of dependencies injected into the UserManager class’s constructor.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserManager </span>
{
    <span style="color:blue;">public </span>UserManager(<span style="color:#8014c7;">IUserPersistence </span>userPersistence, <span style="color:#8014c7;">IEmailManager </span>emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    <span style="color:blue;">private </span><span style="color:#8014c7;">IUserPersistence </span>_userPersistence;
    <span style="color:blue;">private </span><span style="color:#8014c7;">IEmailManager </span>_emailManager;

    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>RegisterUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">try </span>
        {
            <span style="color:#666600;">Boolean </span>result = <span style="color:blue;">false</span>;

            <span style="color:blue;">if </span>(_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            <span style="color:blue;">return </span>result;
        }
        <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
        {
            <span style="color:green;">// Log the exception... </span><span style="color:blue;">return false</span>;
        }
    }
}</pre>
<p>Notice that our constructor takes two parameters that are interfaces that define our tasks.</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#8014c7;">IUserPersistence </span>
{
    <span style="color:#666600;">Boolean </span>AddUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress);
    <span style="color:green;">// Other interface members... </span>
}

<span style="color:blue;">public interface </span><span style="color:#8014c7;">IEmailManager </span>
{
    <span style="color:#666600;">Boolean </span>SendUserRegistrationEmail(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName, <span style="color:#2b91af;">String </span>emailAddress);
    <span style="color:green;">// Other interface members... </span>
}</pre>
<p>As for the RegisterUser method, what happened to the SQL that will add the user to the User table in our database?&#160; The short answer is, “Who cares?”</p>
<p>Persisting the user to the database is now farmed out to an interface called IUserPersistence that has a method called AddUser.&#160; The SQL will probably be in there, but as far as the RegisterUser method is concerned, it doesn’t care.&#160; Our RegisterUser method just works with the interfaces:</p>
<pre class="code">        <span style="color:blue;">if </span>(<strong>_userPersistence.AddUser</strong>(lastName, firstName, emailAddress))
            result = <strong>_emailManager.SendUserRegistrationEmail</strong>(lastName, firstName,
                emailAddress);</pre>
<p>This is dependency injection at work.&#160; Our code is now testable and our test can now <em>inject dependencies</em> into the UserManager class without having to have a database and email server set up to run the test!</p>
<p>Let’s rewrite our test and inject some home-grown dependencies.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">UserPersistenceStub </span>: <span style="color:#8014c7;">IUserPersistence </span>
{
    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>AddUser(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName,
        <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">return true</span>;
    }
}

<span style="color:blue;">public class </span><span style="color:#2b91af;">EmailManagerStub </span>: <span style="color:#8014c7;">IEmailManager </span>
{
    <span style="color:blue;">public </span><span style="color:#666600;">Boolean </span>SendUserRegistrationEmail(<span style="color:#2b91af;">String </span>lastName, <span style="color:#2b91af;">String </span>firstName,
        <span style="color:#2b91af;">String </span>emailAddress)
    {
        <span style="color:blue;">return true</span>;
    }
}

[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>RegisterUserTest()
{
<strong>    <span style="color:blue;">var </span>userPersistenceStub = <span style="color:blue;">new </span><span style="color:#2b91af;">UserPersistenceStub</span>();
    <span style="color:blue;">var </span>emailManagerStub = <span style="color:blue;">new </span><span style="color:#2b91af;">EmailManagerStub</span>();
</strong>
    <span style="color:#2b91af;">UserManager </span>target = <strong><span style="color:blue;">new </span><span style="color:#2b91af;">UserManager</span>(userPersistenceStub, emailManagerStub);
</strong>    <span style="color:#666600;">Boolean </span>actual = target.RegisterUser(<span style="color:#a31515;">&quot;Smith&quot;</span>, <span style="color:#a31515;">&quot;Bert&quot;</span>, <span style="color:#a31515;">&quot;bsmith@wherever.com&quot;</span>);
    <span style="color:#2b91af;">Assert</span>.IsTrue(actual);
}</pre>
<p>We simply created two stub classes that implement our interfaces and then injected instances of those classes into our UserManager instance.</p>
<p>Now our test runs without the need for a database or an email server.&#160; We were able to achieve this because we rewrote our UserManager class and RegisterUser method as <em>testable code</em> using <em>dependency injection</em>.</p>
<p>Our unit test can be improved (e.g. by using tools like <a href="http://code.google.com/p/moq/">Moq</a>), but I will save that for another post.&#160; For now, the main takeaway of this post is that code can be written to be testable using dependency injection.</p>
<p>It took me a while to realize the importance of writing testable code.&#160; The fact that testable code can be unit tested without needing external resources like databases opens up the door to writing a slew of tests to thoroughly test your code, and this gets you into the area of <em><a href="http://en.wikipedia.org/wiki/Code_coverage">code coverage</a></em> and even <em><a href="http://en.wikipedia.org/wiki/Test-driven_development">test-driven development</a></em>.</p>
<p>More to come on this…</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/210/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/210/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=210&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
		<item>
		<title>Case-invariant String Comparisons</title>
		<link>http://larryparkerdotnet.wordpress.com/2011/08/03/case-invariant-string-comparisons/</link>
		<comments>http://larryparkerdotnet.wordpress.com/2011/08/03/case-invariant-string-comparisons/#comments</comments>
		<pubDate>Wed, 03 Aug 2011 12:23:49 +0000</pubDate>
		<dc:creator>Larry Parker</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://larryparkerdotnet.wordpress.com/2011/08/03/case-invariant-string-comparisons/</guid>
		<description><![CDATA[String comparisons are one of those things done fairly frequently in a programmer’s day job.  The fact that our alphabet has upper-case and lower-case versions of each letter makes our job a little harder since we sometimes need to perform case-invariant comparisons.  For example, we may not care about the case of the user’s last [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=206&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>String comparisons are one of those things done fairly frequently in a programmer’s day job.  The fact that our alphabet has upper-case and lower-case versions of each letter makes our job a little harder since we sometimes need to perform <em>case-invariant comparisons</em>.  For example, we may not care about the case of the user’s last name when performing a customer lookup (although that sometimes gets resolved at the SQL level, but that’s another topic).</p>
<p>A simple way to compare strings without regard to case is to simply convert them to the same case.  For example:</p>
<pre class="code"><span style="color:#2b91af;">String </span>a = <span style="color:#a31515;">"Antwerp"</span>;
<span style="color:#2b91af;">String </span>b = <span style="color:#a31515;">"ANTWERP"</span>;

<span style="color:#666600;">Boolean </span>areEqual = (a.ToLower() == b.ToLower());</pre>
<p>There’s nothing wrong with this approach (we could have used ToUpper as well), but let’s take a deeper look at what’s going on here.</p>
<p>The String.ToLower method has the following signature:</p>
<pre class="code"><span style="color:blue;">public string </span>ToLower();</pre>
<p>This means that it returns a string.  So we start off with our original string, apply the ToLower method to it, and return a new string with all characters lower case.</p>
<p>In our original example, we’re actually doing two ToLower operations, so two strings are returned and finally compared for equality.</p>
<p>Again, there’s nothing really wrong with this approach except that under the covers it seems to be doing a bit more than we need.  What we really want is to simply compare two strings for equality without regard to case.</p>
<p>Fortunately, there is a more efficient way.  The .NET String class provides an overload of the Equals method that lets us specify <em>how</em> we want to compare our string with another string.</p>
<pre class="code"><span style="color:blue;">public bool </span>Equals(<span style="color:blue;">string </span>value, <span style="color:olive;">StringComparison </span>comparisonType);</pre>
<p>One of the members of the StringComparison enum gives us just what we want, and we can rewrite our code as such:</p>
<pre class="code"><span style="color:#2b91af;">String </span>a = <span style="color:#a31515;">"Antwerp"</span>;
<span style="color:#2b91af;">String </span>b = <span style="color:#a31515;">"ANTWERP"</span>;

<span style="color:#666600;">Boolean </span>areEqual = a.Equals(b, <span style="color:olive;">StringComparison</span>.OrdinalIgnoreCase);</pre>
<p>This performs a string comparison between the two strings by using ordinal sort rules and ignoring case, and the Equals method simply returns a boolean value indicating if the comparison succeeded.  We didn’t have to convert our strings to lower-case, return the new string, and compare with the other converted string.</p>
<p>As a disclaimer, I have not performed benchmark tests on the two approaches to see which one is faster, nor have I inspected the .NET IL code under the covers.</p>
<p>But it just seems more intuitive that comparing existing strings using a designated set of rules would be a more optimal approach.</p>
<p>I find as I continue to work with .NET I start to think about these things a bit more.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/larryparkerdotnet.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/larryparkerdotnet.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/larryparkerdotnet.wordpress.com/206/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=larryparkerdotnet.wordpress.com&amp;blog=1413408&amp;post=206&amp;subd=larryparkerdotnet&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://larryparkerdotnet.wordpress.com/2011/08/03/case-invariant-string-comparisons/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eccdc472914bb3d3acddbb80bb1c58c0?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Larry</media:title>
		</media:content>
	</item>
	</channel>
</rss>
