<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>www.fooberry.com &#187; .Net</title>
	<atom:link href="http://fooberry.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://fooberry.com</link>
	<description>Sweetness Without Context</description>
	<lastBuildDate>Fri, 30 Jul 2010 14:17:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Routing Newbie Mistake</title>
		<link>http://fooberry.com/2010/04/01/routing-newbie-mistake/</link>
		<comments>http://fooberry.com/2010/04/01/routing-newbie-mistake/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 18:35:54 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://fooberry.com/2010/04/01/routing-newbie-mistake/</guid>
		<description><![CDATA[<br/>So I’m a n00b in some areas and it is painful finding this out sometimes. I spent most of the morning trying to figure out why my ASP.Net Web Site application wasn’t routing to my MVC controller that is inside of my ASP.Net MVC Area. Granted, that is a weird setup so there are a [...]]]></description>
			<content:encoded><![CDATA[<br/><p><a href="http://www.flickr.com/photos/candiedwomanire/3397197237/"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="008" border="0" alt="008" align="right" src="http://farm4.static.flickr.com/3605/3397197237_543c57dea8_m.jpg" width="240" height="240" /></a>So I’m a n00b in some areas and it is painful finding this out sometimes. I spent most of the morning trying to figure out why my ASP.Net Web Site application wasn’t routing to my MVC controller that is inside of my ASP.Net MVC Area. </p>
<p>Granted, that is a weird setup so there are a lot of things I thought could possibly go wrong. The real reason was embarrassingly obvious, but not embarrassing enough that I wouldn’t post it for the world to see. </p>
<p>What do you see wrong with this route:</p>
<pre class="c#" name="code">context.MapRoute(
    &quot;Default Route&quot;,
    &quot;ServerManagement/{controller}/{action}/{id}&quot;,
    new {   controller = &quot;farms&quot;,
            action = &quot;index&quot;
        });</pre>
<p>Give up? You <em>have</em> to give a default value if you have a placeholder in the route. In this case we have “/{id}” in the route, but we never a default value for the id. The following route worked fine. </p>
<pre class="c#" name="code">context.MapRoute(
    &quot;Default Route&quot;,
    &quot;ServerManagement/{controller}/{action}/{id}&quot;,
     new {   controller = &quot;Farms&quot;,
             action = &quot;index&quot;,
             id=&quot;&quot;
         });</pre>
<p>Lesson learned!</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2010/04/01/routing-newbie-mistake/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fixing 500.22 Error Code 0&#215;80070032</title>
		<link>http://fooberry.com/2010/04/01/fixing-500-22-error-code-0x80070032/</link>
		<comments>http://fooberry.com/2010/04/01/fixing-500-22-error-code-0x80070032/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 15:18:39 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://fooberry.com/2010/04/01/fixing-500-22-error-code-0x80070032/</guid>
		<description><![CDATA[<br/>It’s nice when fixing a problem is easy.&#160; It’s nice when you scratch your head for a bit and then smack your forehead because someone in front of you laid out exactly what to do, and exactly what needs to be done.&#160; I just had such a moment. While working MVC into out existing ASP.Net [...]]]></description>
			<content:encoded><![CDATA[<br/><p><a href="http://www.flickr.com/photos/civisi/3158222539/"><img style="border-right-width: 0px; margin: 0px 10px 0px 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="012" border="0" alt="012" align="left" src="http://farm4.static.flickr.com/3093/3158222539_e4603f2446_m.jpg" width="240" height="161" /></a> It’s nice when fixing a problem is easy.&#160; It’s nice when you scratch your head for a bit and then smack your forehead because someone in front of you laid out exactly what to do, and exactly what needs to be done.&#160; I just had such a moment. </p>
<p>While working MVC into out existing ASP.Net Web Site project we hit, what we thought was a brick wall. </p>
<pre>HTTP Error 500.22 - Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.</pre>
<p>&#160;</p>
<p>Well the Visual Studio engineers deserve a hand for helping me get this going.&#160; After spending a minute looking into the web.config to find out what was wrong, I ran into this little bit of commented out configuration.</p>
<pre class="xml" name="code">&lt;!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.

	&lt;system.webServer&gt;

        ...then some more config</pre>
<p>&#160;</p>
<p>That is exactly what was needed to take us into integrated mode in IIS, which is needed for MVC. </p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2010/04/01/fixing-500-22-error-code-0x80070032/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sharing master pages between WebForms and MVC</title>
		<link>http://fooberry.com/2010/03/29/sharing-master-pages-between-webforms-and-mvc/</link>
		<comments>http://fooberry.com/2010/03/29/sharing-master-pages-between-webforms-and-mvc/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 21:55:15 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[master page]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[WebForms]]></category>

		<guid isPermaLink="false">http://fooberry.com/2010/03/29/sharing-master-pages-between-webforms-and-mvc/</guid>
		<description><![CDATA[<br/>Let’s face it. Everyone loves MVC. At least all the web purists love it. It’s clean, straight forward, and very testable. But let’s also face it. We have a huge investment in WebForms. I mean up until now, 100% of the stuff we built was WebForms, include 100% of the master pages. These pages govern [...]]]></description>
			<content:encoded><![CDATA[<br/><p>Let’s face it. Everyone loves MVC. At least all the web purists love it. It’s clean, straight forward, and very testable. But let’s also face it. We have a huge investment in WebForms. I mean up until now, 100% of the stuff we built was WebForms, include 100% of the master pages. </p>
<p>These pages govern how&#160; the entire site looks and a wee bit of its functionality. </p>
<p><a href="http://fooberry.com/wp-content/uploads/2010/03/a.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="a" border="0" alt="a" src="http://fooberry.com/wp-content/uploads/2010/03/a_thumb.png" width="293" height="250" /></a> </p>
<p>It would be a real shame if we had to start being less DRY and copy all that markup, in potentially many files, to new, MVC master pages. Luckily, you don’t.</p>
<p><strong>Let me stop right there</strong>. Technically, no, you don’t. Mvc’s <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.viewmasterpage.aspx">ViewMasterPage</a> (VMP) inherits from <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.masterpage.aspx">MasterPage</a> (MP), so you can just tell your VMP to use the MP you want and it will work, <strong>unless you have the single line I hate more than any other lines in your MP.</strong></p>
<pre class="html" name="code">&lt;form id=”Form1” runat=”server”&gt;</pre>
<p>&#160;</p>
<p>So this single line blows the possibility of using the master page as a VMP out of the water. No problem right, include that in a nested MP and put that runat=”server” around the content place holder, right?</p>
<p><a href="http://fooberry.com/wp-content/uploads/2010/03/a_3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="a_3" border="0" alt="a_3" src="http://fooberry.com/wp-content/uploads/2010/03/a_3_thumb.png" width="489" height="474" /></a> </p>
<p>That’s nice and all, but all those other bit out side of the WebForms specific master page needs to be inside that stupid form.</p>
<p><a href="http://fooberry.com/wp-content/uploads/2010/03/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://fooberry.com/wp-content/uploads/2010/03/image_thumb.png" width="605" height="271" /></a> </p>
</p>
<p>Uh oh! No way around that one! Either move the run at server form outside or convert those controls. I’d vote for convert the controls. </p>
<p>OK, so how about just use partial views and HtmlHelpers. That sounds like a good idea. Here’s another problem.</p>
<pre class="html" name="code">&lt;%= Html.MyMenu() %&gt;</pre>
<p>&#160;</p>
<p>System.Web.UI.MasterPage does not have a HtmlHelper attribute where we get all those nice HtmlHelper Extensions. What about just creating one and using it?</p>
<pre class="html" name="code">&lt;%= new HtmlHelper(null,null).MyMenu() %&gt;</pre>
<p>&#160;</p>
<p>Great! That compiles, but don’t get too excited. It doesn’t run. We can’t just pass null into HtmlHelper. We can new up the first parameter and create our own custom implementation of the second and it does work. </p>
<pre class="html" name="code">&lt;%= new HtmlHelper(new ViewContext(), new FakeViewDataContainer).MyMenu() %&gt;</pre>
<p>&#160;</p>
<p>That looks nasty too, but since that is my own customer helper extension, when not just call into that directly.</p>
<pre class="html" name="code">&lt;%= MyMenuHelper.MyMenu(null) %&gt;</pre>
<p>&#160;</p>
<p>That’s better, and since we aren’t using the HtmlHelper at all, we can clean up the syntax just a bit.</p>
<pre class="html" name="code">&lt;%= MyMenuHelper.CreateMenu() %&gt;</pre>
<p>&#160;</p>
<p>I can live with that, but if we ever need to do anything complicated that requires view data or other information to be passed along, we’re in a nasty situation. This works for us for now, so we’re going to ride this idea for a little longer and see how it goes. </p>
<p>Eventually all those WebForms pages will be moved over to MVC and this won’t be an issue. We’ll have <em>only</em> the MVC master page and everything will be simple. </p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2010/03/29/sharing-master-pages-between-webforms-and-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DataAnnotation Message Parameters</title>
		<link>http://fooberry.com/2010/01/12/dataannotation-message-parameters/</link>
		<comments>http://fooberry.com/2010/01/12/dataannotation-message-parameters/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 18:34:14 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>

		<guid isPermaLink="false">http://fooberry.com/2010/01/12/dataannotation-message-parameters/</guid>
		<description><![CDATA[<br/>I’m adding custom validation messages to all my data annotation validation attributes. Simple stuff right. I started off with this. Then added a customer message. Then moved that message to a resource file The problem is the resource file says something like “Less than 50”. If I change that 50 on the attribute, someone has [...]]]></description>
			<content:encoded><![CDATA[<br/><p>I’m adding custom validation messages to all my data annotation validation attributes. Simple stuff right. I started off with this.</p>
<p><script src="http://gist.github.com/275449.js?file=NoMessage.cs"></script></p>
<p>Then added a customer message.</p>
<p><script src="http://gist.github.com/275449.js?file=CustomMessage.cs"></script></p>
<p>Then moved that message to a resource file</p>
<p><script src="http://gist.github.com/275449.js?file=ResourceMessage.cs"></script></p>
<p>The problem is the resource file says something like “Less than 50”. If I change that 50 on the attribute, someone has to remember to go to the resource file and change it there too. Not very DRY. </p>
<p>Luckily the default message formatting will allow us to embed some tokens in the error message.&#160; All we need to do is change our message to <strong>“Less than {1}”</strong> and the message is formatted to “Less than 50”….or whatever the argument value might be.</p>
<p>I haven&#8217;t found a good list of the parameters you pass, but {0} is the property name, and then I assume 1, 2, 3, etc are the parameters of the constructor in order.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2010/01/12/dataannotation-message-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>You sneaky deferred execution!</title>
		<link>http://fooberry.com/2009/12/01/you-sneaky-deferred-execution/</link>
		<comments>http://fooberry.com/2009/12/01/you-sneaky-deferred-execution/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 16:25:46 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/12/01/you-sneaky-deferred-execution/</guid>
		<description><![CDATA[<br/>As I’ve mentioned we have a series of Extension methods that help with some trivial, but isolated tasks. Here is an example. public static IEnumerable&#60;SelectListItem&#62; CreatePaymentTypeDropDownListItems( this IQueryable&#60;PaymentType&#62; @this) { return @this .OrderBy(x =&#62; x.Description) .Select(x =&#62; new SelectListItem { Value = x.Code, Text = x.Description, }) .MarkAsSelected(x=&#62;x.Text == CreditCard); } Simple enough right? The [...]]]></description>
			<content:encoded><![CDATA[<br/><p>As I’ve mentioned we have a series of Extension methods that help with some trivial, but isolated tasks. Here is an example.</p>
<pre class="c#" name="code">public static IEnumerable&lt;SelectListItem&gt; CreatePaymentTypeDropDownListItems(
                                          this IQueryable&lt;PaymentType&gt; @this)
{
    return  @this
            .OrderBy(x =&gt; x.Description)
            .Select(x =&gt; new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                             })
            .MarkAsSelected(x=&gt;x.Text == CreditCard);
}</pre>
<p>Simple enough right? The <code>MarkAsSelected</code> is another extension method we have to help out. It’s not all that exciting, but here it is.</p>
<pre class="c#" name="code">public static IEnumerable
<selectlistitem> MarkAsSelected(this IEnumerable
<selectlistitem> @this, Func
<selectlistitem  ,BOOL> where)
{
    var items = @this.Where(where);
    foreach (var item in items)
    {
        item.Selected = true;
    }
    return @this;

}</pre>
<p>Simple enough right? But the credit card payment type was never getting defaulted with the select value. We have unit tests around <code>MarkAsSelected</code> and it works! What’s the problem? Let’s try something really quick.</p>
<pre class="c#" name="code">public static IEnumerable&lt;SelectListItem&gt; CreatePaymentTypeDropDownListItems(
                                          this IQueryable&lt;PaymentType&gt; @this)
{
    return  @this
            .OrderBy(x =&gt; x.Description)
            .Select(x =&gt; new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                             })
            .ToArray()
            .MarkAsSelected(x=&gt;x.Text == CreditCard);
}</pre>
<p>That works! What’s up? Oh you sneaky deferred execution. I bet it’s you! I’m not an expert, but here is my best guess. When the <code>MarkAsSelected</code> does its foreach, it asks the <code>@this</code> to create an enumerator. It does, but since it is from an <code>IQueryable&lt;T&gt;</code>, it now executes all that deferred execution in the <code>Select</code> and <code>OrderBy</code>. Fair enough. The enumerator spits out all the <code>SelectListItems</code> we want/need. </p>
<p>We pass on the enumerable incase we want to do something after it, and actually we do. Down the road we want to enumerate again. The <code>Select</code> and <code>OrderBy</code> kick in again and we get all brand new <code>SelectListItems</code>. </p>
<p>Throwing that <code>ToArray</code> in there gets us out of operating on the <code>IQueryable&lt;T&gt;</code>, does the <code>Select</code> and <code>OrderBy</code> and lets us operate on a straight list. Makes sense, but not obviously apparent…at least to me.</p>
<p>But you know what? After all that, I think I just prefer this. </p>
<pre class="c#" name="code">public static IEnumerable&lt;SelectListItem&gt; CreatePaymentTypeDropDownListItems(
                                          this IQueryable&lt;PaymentType&gt; @this)
{
    return  @this
            .OrderBy(x =&gt; x.Description)
            .Select(x =&gt; new SelectListItem
                             {
                                 Value = x.Code,
                                 Text = x.Description,
                                 Selected = (x.Description == CreditCard)
                             });
}</pre>
<p>No need to overcomplicate the problem right?</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/12/01/you-sneaky-deferred-execution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Are extensive extension method an anti-pattern</title>
		<link>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/</link>
		<comments>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 15:55:09 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[anti-pattern]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/</guid>
		<description><![CDATA[<br/>I was explaining my dilemma to a Java friend and the e-mail ended up being fairly interesting, so I thought I would share it. I&#8217;m sure Java has extension methods, but I&#8217;ll give it a once over just in case.&#160; You can extend existing classes without sub-classing by extension methods. public static IEnumerable&#60;SelectListItem&#62; AsSelectListItems( this [...]]]></description>
			<content:encoded><![CDATA[<br/><p>I was explaining my dilemma to a Java friend and the e-mail ended up being fairly interesting, so I thought I would share it. </p>
<blockquote><p>I&#8217;m sure Java has extension methods, but I&#8217;ll give it a once over just in case.&#160; You can extend existing classes without sub-classing by extension methods.</p>
<pre>public static IEnumerable&lt;SelectListItem&gt;
                            AsSelectListItems( this IEnumerable&lt;Person&gt; listOfPeople){
   IList&lt;SelectListItem&gt; selectListItems = new List
<selectlistitems>();
   foreach(var person in listOfPeople){
      selecListItems.Add(new SelectListItem(person.ID,
					    string.Format(&quot;{0} {1} {2}&quot;,
                                                          person.First,
                                                          person.Middle,
                                                          person.Last));
   }
   return selectListItems;
}</pre>
<p>Right. So the <code>this</code> operator tells the compiler to basically create this function:</p>
<pre>public static IEnumerable&lt;SelectListItem&gt;
                           AsSelectListItems(IEnumerable&lt;Person&gt; listOfPeople);</pre>
<p>And invoke it every time you see this:</p>
<pre>IEnunerable&lt;Person&gt; p = myService.GetAllPeople();
IEnumerable&lt;SelectListItem&gt; s = p.AsSelectListItems();</pre>
<p>You probably knew all this, but it explains how we are using them. We end up calling a lot of extension methods off other extension methods. </p>
<pre>myViewData.PersonSelectListItems = myService.GetAllPeople()
                                                   .AsSelectListItems()
                                                   .OrderedByText()
                                                   .StartingWithAnEmptyItem();</pre>
<p>In this example we have three extension method calls and I think it really makes the code much more readable, but it makes testing this code a little more difficult. Obviously, the myService is a mocked dependency which will return a fake list of people, but the other extension method calls cannot be mocked, and the scope of the test bleeds a bit. </p>
<p>I like the syntax it gives, but now I&#8217;m going to test potentially four classes when I should be testing only one. </p>
</blockquote>
<p>This gets pretty pandemic in our code. Especially trying to make Selenium’s API and the assertion API of Nunit and xUnit more fluent.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type Safe Unit Testing of Data Annotations Validations</title>
		<link>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/</link>
		<comments>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 19:52:59 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/</guid>
		<description><![CDATA[<br/>We’re using the Data Annotations Validators in ASP.Net MVC 2.0, but there wasn’t a really great way to unit test them. I’ve read Brad Wilson’s blog post about how to set them up and unit test them, but I didn’t like how you relied on the name of the property as a string. // Arrange [...]]]></description>
			<content:encoded><![CDATA[<br/><p>We’re using the Data Annotations Validators in ASP.Net MVC 2.0, but there wasn’t a really great way to unit test them. I’ve read <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">Brad Wilson’s blog post</a> about how to set them up and unit test them, but I didn’t like how you relied on the name of the property as a string.</p>
<pre class="c#" name="code">// Arrange
var propertyInfo = typeof(Contact).GetProperty(&quot;FirstName&quot;);</pre>
<p>It would be nicer if that used lambda expressions to get the name of the property, so I set out to do just that. Before we begin, I need to remind you, as always, <strong>I don’t know what I’m doing</strong>. This is my first tiny venture into expression trees so it is possible isn’t the best way to do things, but so far, it’s working for me.</p>
<p>I created a base Specification to wrap up a lot of the messy bits of getting property names by lambdas. I took a look at <a href="http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet#266392">how the ASP.Net MVC helpers did it</a> and roughly followed their pattern.</p>
<pre class="c#" name="code">public class DataAnnotationSpecification&lt;T&gt; : Specification
{

    public PropertyInfo Property(Expression&lt;Func&lt;T,object&gt;&gt; op)
    {
        return Property(GetInputName(op));
    }

    public PropertyInfo Property(string propertyName)
    {
        return typeof (T).GetProperty(propertyName);
    }

    public static string GetInputName&lt;TProperty&gt;(Expression&lt;Func&lt;T, TProperty&gt;&gt; expression)
    {
        // not sure I totally understand this
        if (expression.Body.NodeType == ExpressionType.Convert)
        {
            var ue = (UnaryExpression)expression.Body;
            return GetInputName((MemberExpression) ue.Operand );
        }

        if (expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            return GetInputName((MemberExpression)expression.Body);
        }
        throw new NotImplementedException();
    }

    private static string GetInputName(MemberExpression memberExpression)
    {
        return memberExpression.Member.Name;
    }

}</pre>
<p>I know this probably doesn’t cover an exhaustive list of expressions, but we’re only talking about Property access tests here so we’re probably in the clear.</p>
<p>To make things a bit nicer, I also created some extensions off PropertyInfo to help setup their assertions.</p>
<pre class="c#" name="code">public static class AttributeAssertions
{

    public static void ShouldNotBeRequired(this PropertyInfo @this)
    {
        @this.ShouldNotHaveAttribute&lt;RequiredAttribute&gt;();
    }

    public static void ShouldBeRequired(this PropertyInfo @this)
    {
        @this.ShouldHaveAttribute&lt;RequiredAttribute&gt;();
    }

    private static T PropertyAttributeOn&lt;T&gt;(ICustomAttributeProvider propertyInfo)
    {
        return propertyInfo.GetCustomAttributes(typeof (T), false)
            .Cast&lt;T&gt;()
            .FirstOrDefault();
    }

    public static void ShouldHaveAttribute&lt;T&gt;(this PropertyInfo @this)
    {
        PropertyAttributeOn&lt;T&gt;(@this).ShouldNotBeNull();
    }
    public static void ShouldNotHaveAttribute&lt;T&gt;(this PropertyInfo @this)
    {
        PropertyAttributeOn&lt;T&gt;(@this).ShouldBeNull();
    }
}</pre>
<p>We only have the <code>ShouldBeRequired</code> and <code>ShouldNotBeRequired</code> right now, but you could see it will be easy to extend upon them.&#160; The finished spec looks something like this.</p>
<pre class="c#" name="code">public class When_testing_the_state_of_the_CustomerViewData
    : DataAnnotationSpecification&lt;CustomerViewData&gt;
{
    [Then] public void the_customer_first_name_is_required()
    {
        Property(x =&gt; x.CustomerFirstName).ShouldBeRequired();
    }

    [Then] public void the_customer_middle_name_is_not_required()
    {
        Property(x =&gt; x.CustomerMiddleName).ShouldNotBeRequired();
    }

    [Then] public void the_customer_last_name_is_required()
    {
        Property(x=&gt;x.CustomerLastName).ShouldBeRequired();
    }

    [Then] public void the_email_address_is_required()
    {
        Property(x=&gt;x.CustomerEmailAddress).ShouldBeRequired();
    }

}</pre>
<p>That’s not so bad, and it stands up to any refactoring we might do.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing when ModelState is invalid.</title>
		<link>http://fooberry.com/2009/11/06/testing-when-modelstate-is-invalid/</link>
		<comments>http://fooberry.com/2009/11/06/testing-when-modelstate-is-invalid/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 16:15:37 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/06/testing-when-modelstate-is-invalid/</guid>
		<description><![CDATA[<br/>As a follow up to my previous post, testing when ModelState is relatively simple, but leaves me feelings a little uneasy about my tests. Here is an example tests, stripped down to remove some of the unnecessary bits public class When_submitting_lead_data_that_is_in_an_invalid_state : Specification { // class fields...etc protected override void Given() { base.Given(); _mockOrdersRepository = [...]]]></description>
			<content:encoded><![CDATA[<br/><p> As a follow up to my previous post, testing when <code>ModelState</code> is relatively simple, but leaves me feelings a little uneasy about my tests.  </p>
<p>Here is an example tests, stripped down to remove some of the unnecessary bits</p>
<pre name="code" class="c#">
public class When_submitting_lead_data_that_is_in_an_invalid_state : Specification
{
    // class fields...etc

    protected override void Given()
    {
        base.Given();
        _mockOrdersRepository = MockRepository.GenerateStub&lt;IOrdersRepository>();
        _checkoutController = new CheckoutController(_mockOrdersRepository);

        _leadDataWithEmptyPlanName = new PreCheckoutViewData();

        // add an error to the model state
        _checkoutController.ModelState.AddModelError("", "");

        _exceptionWasThrown = false;
    }

    protected override void When()
    {
        base.When();
        try
        {
            _checkoutController.Checkout(_leadDataWithEmptyPlanName);
        } catch(ArgumentNullException)
        {
            _exceptionWasThrown = true;
        }
    }

    [Then] public void an_exception_is_thrown()
    {
        _exceptionWasThrown.ShouldBe(true);
    }
}
</pre>
<p>
  This feels pretty loose to me, but there can be another tests that tests which states the model will appear invalid.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/06/testing-when-modelstate-is-invalid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ModelState.IsValid is always true</title>
		<link>http://fooberry.com/2009/11/06/modelstate-isvalid-is-always-true/</link>
		<comments>http://fooberry.com/2009/11/06/modelstate-isvalid-is-always-true/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 15:09:29 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ASP.Net]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/06/modelstate-isvalid-is-always-true/</guid>
		<description><![CDATA[<br/>We ran into a snag with using the new default Data Annotations Validation in ASP.Net MVC 2.0 Preview 2. Maybe it isn’t a snag, but it is not the behavior I would have expected. Take the following model: public class Person { public string ID { get; set; } public string FirstName { get; set; [...]]]></description>
			<content:encoded><![CDATA[<br/><p>We ran into a snag with using the new default Data Annotations Validation in ASP.Net MVC 2.0 Preview 2. Maybe it isn’t a snag, but it is not the behavior I would have expected. </p>
<p>Take the following model:</p>
<pre class="c#" name="code">public class Person
{
  public string ID { get; set; }

  public string FirstName { get; set; }
  public string LastName { get; set; }

  [Required (ErrorMessage = &quot;Required&quot;)]
  public string EmailAddress { get; set; }
}</pre>
<p>Pretty straight forward, but if you post this form: </p>
<pre class="html" name="code">    &lt;form action=&quot;/person/edit&quot; method=&quot;post&quot;&gt;
        &lt;input type=hidden name=&quot;id&quot; id=&quot;id&quot; value=&quot;&quot; /&gt;
        &lt;input type=&quot;text&quot; id=&quot;firstname&quot; name=&quot;firstname&quot; /&gt; 
        &lt;input type=&quot;text&quot; id=&quot;lastname&quot; name=&quot;lastname&quot; /&gt; 
        &lt;input type=&quot;submit&quot; /&gt;
    &lt;/form&gt; </pre>
<p>To this controller action: </p>
<pre class="C#" name="code">[HttpPost] public virtual ActionResult Edit(Person data)
{
   if (!ModelState.IsValid) throw new ItBrokeException();
   return View();
}</pre>
<p>Personally, I would expect every post of that form to show up as invalid, but infact, it is always true. Add the following input to the form and it works. </p>
<pre class="html" name="code">   &lt;input type=&quot;text&quot; id=&quot;emailaddress&quot; name=&quot;emailaddress&quot; /&gt; &lt;br/&gt;
</pre>
<p>After that, the <code>ModelState.IsValid</code> returns false, like it should.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/06/modelstate-isvalid-is-always-true/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>IIS 7, .Net 4.0 Beta 2 and 503 Service Unavailable&#8230;after Beta 1</title>
		<link>http://fooberry.com/2009/10/30/iis-7-net-4-0-beta-2-and-503-service-unavailableafter-beta-1/</link>
		<comments>http://fooberry.com/2009/10/30/iis-7-net-4-0-beta-2-and-503-service-unavailableafter-beta-1/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 22:23:01 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Beta]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/10/30/iis-7-net-4-0-beta-2-and-503-service-unavailableafter-beta-1/</guid>
		<description><![CDATA[<br/>After recently installing Visual Studio 2010 Beta 2 and creating a .Net 4.0 site, I tried to step out of Cassini and into IIS only to get “503 Service Unavailable” and a killed worker process. Checking the event viewer I found the following errors. The worker process failed to initialize correctly and therefore could not [...]]]></description>
			<content:encoded><![CDATA[<br/><p><a href="http://www.flickr.com/photos/calitomshots/2789088006/sizes/m/"><img style="border-right-width: 0px; margin: 0px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="" border="0" alt="" align="right" src="http://farm4.static.flickr.com/3182/2789088006_3b26f9477f.jpg" width="335" height="500" /></a> After recently installing Visual Studio 2010 Beta 2 and creating a .Net 4.0 site, I tried to step out of Cassini and into IIS only to get “503 Service Unavailable” and a killed worker process. Checking the event viewer I found the following errors.</p>
<blockquote><p>The worker process failed to initialize correctly and therefore could not be started.&#160; The data is the error.</p>
</blockquote>
<p>Followed by…</p>
<blockquote><p>The worker process failed to pre-load .Net Runtime version v4.0.20506.</p>
</blockquote>
<p>The Google was no help. It returned a handful of result that weren’t all that helpful, but one post was interesting. Someone had a similar problem with the&#160; 2.0 runtime when upgrading to the beta and found there were tiny bits of the other runtime sticking around. </p>
<p>I had .Net 4.0 Beta 1 installed before, so I did some digging and found I had the Beta framework:</p>
<blockquote><p>C:\Windows\Microsoft.NET\Framework\v4.0.21006      <br />C:\Windows\Microsoft.NET\Framework64\v4.0.21006</p>
</blockquote>
<p>I also had folders from the Beta 1</p>
<blockquote><p>C:\Windows\Microsoft.NET\Framework\v4.0.20506      <br />C:\Windows\Microsoft.NET\Framework64\v4.0.20506</p>
</blockquote>
<p>I deleted those folders, restarted the .Net 4.0 app pool’s and and hard restart just to be safe. Everything worked. Two hours on a Friday wasted, but we weekend free of worry. </p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/10/30/iis-7-net-4-0-beta-2-and-503-service-unavailableafter-beta-1/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
