<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:rssdatehelper="urn:rssdatehelper" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Fresh.Thoughts</title><link>http://ivonna.biz</link><pubDate>2012-05-12T12:52:52</pubDate><category>CodeProject</category><generator>umbraco</generator><description>Random revelations on .Net programming and other earthly stuff</description><language>en</language><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ivonna/oigv" /><feedburner:info uri="ivonna/oigv" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Fixing the jQueryUI dialog height in IE, the Quirks way</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/2qN9scWVpHM/fixing-the-jqueryui-dialog-height-in-ie,-the-quirks-way.aspx</link><pubDate>Sat, 12 May 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/5/11/fixing-the-jqueryui-dialog-height-in-ie,-the-quirks-way.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>Today I had some fun trying to figure out how to fix the height of the jQueryUI dialog. The client wanted it to be exactly 500px. Or something that resembled 500px. Anyway, it definitely shouldn't have been from the top to the bottom of the screen. Although I sure set it to 500.</p>
<p>The fun part is that it had to work in IE7-9, but in *quirks* mode. The client won't switch to the standards mode, since the site (made in early 2000's, tables inside tables all the way down) would break ap...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>Today I had some fun trying to figure out how to fix the height of the jQueryUI dialog. The client wanted it to be exactly 500px. Or something that resembled 500px. Anyway, it definitely shouldn't have been from the top to the bottom of the screen. Although I sure set it to 500.</p>
<p>The fun part is that it had to work in IE7-9, but in *quirks* mode. The client won't switch to the standards mode, since the site (made in early 2000's, tables inside tables all the way down) would break apart.</p>
<p>After some debugging, I figured that one line in a certain method would save me. Namely, a fix would require adding a line at the beginning of the "_size" method. So, I could just leave it like that..</p>
<h3>Except that I couldn't.</h3>
<p>Doing so wouldn't just violate the Open/Closed principle, it would offended the shadows of the Fathers of SOLIDity and the Alt.Net deities.</p>
<p>After all, JavaScript is a dynamic language, right? So, we can do whatever dirty trick we can think of, including messing with "private" methods.</p>
<h3>Extending a jQueryUI Widget by rewriting a widget's private method? Nothing could be easier!</h3>
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f; padding: 3px;">		<span style="color: #c8e1fd;">var</span> proto = $.ui.dialog.prototype;
		<span style="color: #c8e1fd;">var</span> _size = proto._size;
		proto._size = <span style="color: #c8e1fd;">function</span>(){ 
			<span style="color: #c8e1fd;">this</span>.element.hide(); 
			_size.apply(<span style="color: #c8e1fd;">this</span>); 
		};
</pre>
<p>While I could easily put there something like <em>alert('OHMYGOSH!!!')</em> (and have fun imagining my coworkers trying to figure out what's going on), what I'm actually doing here is just add something to the beginning. So, first I'm saving a reference to the existing function, then I redefine it, adding the line I need and then invoking the function itself.</p>
<p>So, why do I feel like I've just committed a sin?</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/2qN9scWVpHM" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/5/11/fixing-the-jqueryui-dialog-height-in-ie,-the-quirks-way.aspx</feedburner:origLink></item><item><title>A binder that breaks the rules</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/z0HdhDnNgII/a-binder-that-breaks-the-rules.aspx</link><pubDate>Fri, 11 May 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/5/11/a-binder-that-breaks-the-rules.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>There are many binders in my big rusty toolchest. Some are good boys (and girls), others just like to misbehave. I mean, they do what they're destined for, and they do it really good, but in the process of doing it they break one or several Holy Laws that our Holy President wants us to abide by.</p>
<p>Nobody complains though.</p>
<h3>This particular one saves me a lot of repetitive coding</h3>
<p>Web requests tend to contain simple values. We developers like to work with objects. We li...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>There are many binders in my big rusty toolchest. Some are good boys (and girls), others just like to misbehave. I mean, they do what they're destined for, and they do it really good, but in the process of doing it they break one or several Holy Laws that our Holy President wants us to abide by.</p>
<p>Nobody complains though.</p>
<h3>This particular one saves me a lot of repetitive coding</h3>
<p>Web requests tend to contain simple values. We developers like to work with objects. We like it so much that we are even willing to create objects from simple values. In particular, we often have to retrieve an object from the database (or from the cache), using its ID. Believe it or not, I was doing it at the beginning of almost every action method, sometimes two or three times. I felt so exausted that I would postpone writing the rest of the method until after a lunch break.</p>
<h3>And then I saw the light</h3>
<p>A few years ago Scott Hanselman wrote an <a href="http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx" target="_blank">article about an IPrincipal model binder</a> (I use it a lot as well). And I thought, hey, these binders are not just for slapping your form values together, they can do more than that!</p>
<p>And I wrote the EntityBinder.</p>
<p>This particular binder may be frowned upon by respectable developers. Binders should know their place, you know. They are meant to stay somewhere between your M, V, and C. Your database and the business layer should be a forbidden territory for them.</p>
<p>Ok guys, you may have your controller full of boring repetitive code. I'm done with this.</p>
<p>Another Bad Thing that this boy (or is it a girl?) does, is that it does two things instead of one (<em>what?? you forgot about the Single Responsibility principle???</em>). It serves both as a custom binder attribute and a Binder. I did it this way because I wanted to save several keystrokes writing [EntityBinder("projectId")] instead of [EntityModelBinder(typeof(EntityBinder), "projectId")]. While one can argue that the code for the binder became less maintainable, the code that <em>used</em> it became twice as maintainable, and that was a huge gain.</p>
<p>The downside is that I couldn't use Dependency Injection in that binder (at the time of the writing, I couldn't use it anyway, because it was the first version of Asp.Net MVC), so I had to resort to Service Location (and had never had any problem with that).</p>
<h3>What exactly this shiny binder does, anyway?</h3>
<p>The binder that I'm going to show you looks at the parameter name and type and tries to guess the name of the field that holds the ID, and the type of the entity. So, given a declaration like this:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> ActionResult AnketaDefinition([EntityBinder] <span style="color: #678cb1;">Project</span> project)
</pre>
<p>it looks first for a request value named "projectId", and if it cannot find it, for a value named "Id". Then it asks the ORM for an entity of the type Project with that Id.</p>
<p>In case we don't want the defaults, we can provide our own, but it happens very rarely.</p>
<p>There is one question though. What do we do if we don't find the id in the request? It turns out that there are cases when we want to return null, and cases when we want to throw an exception. There is an additional boolean parameter called "relaxed" which you can use for that. What is default behavior, you decide. I'd recommend throwing an exception, just in case.</p>
<h3>And finally the code that you can <span style="text-decoration: line-through;">steal</span> use</h3>
<p>The code together with a sample aplication can be found at <a href="https://github.com/uluhonolulu/BlogSamples/tree/master/EntityBinderSample">GitHub</a>. The main part, however, is below:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">object</span> BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
	<span style="color: #93c763;">var</span> fieldName <span style="color: #e8e2b7;">=</span> bindingContext<span style="color: #e8e2b7;">.</span>ModelName <span style="color: #e8e2b7;">+</span> <span style="color: #ec7600;">"Id"</span>;
	<span style="color: #93c763;">var</span> result <span style="color: #e8e2b7;">=</span> bindingContext<span style="color: #e8e2b7;">.</span>ValueProvider<span style="color: #e8e2b7;">.</span>GetValue(fieldName);
	<span style="color: #93c763;">if</span> (FieldNotFoundOrValueIsEmpty(result))
		fieldName <span style="color: #e8e2b7;">=</span> _idName;
		result <span style="color: #e8e2b7;">=</span> bindingContext<span style="color: #e8e2b7;">.</span>ValueProvider<span style="color: #e8e2b7;">.</span>GetValue(fieldName);
	<span style="color: #93c763;">if</span> (FieldNotFoundOrValueIsEmpty(result)) {
		<span style="color: #93c763;">if</span> (_relaxed) <span style="color: #93c763;">return</span> <span style="color: #93c763;">null</span>;
		<span style="color: #93c763;">throw</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">MissingFieldException</span>(<span style="color: #ec7600;">"Could not find the request parameter: "</span> <span style="color: #e8e2b7;">+</span> fieldName);
	}
	<span style="color: #93c763;">var</span> entityType <span style="color: #e8e2b7;">=</span> _entityType <span style="color: #e8e2b7;">??</span> bindingContext<span style="color: #e8e2b7;">.</span>ModelType;
	<span style="color: #93c763;">var</span> session <span style="color: #e8e2b7;">=</span> <span style="color: #678cb1;">ObjectFactory</span><span style="color: #e8e2b7;">.</span>GetInstance<span style="color: #e8e2b7;">&lt;</span><span style="color: #8c8cb4;">ISession</span><span style="color: #e8e2b7;">&gt;</span>();
	<span style="color: #93c763;">var</span> id <span style="color: #e8e2b7;">=</span> GetId(result, fieldName);
	<span style="color: #93c763;">object</span> instance <span style="color: #e8e2b7;">=</span> session<span style="color: #e8e2b7;">.</span>Get(entityType, id);
	<span style="color: #93c763;">if</span> (instance <span style="color: #e8e2b7;">==</span> <span style="color: #93c763;">null</span>)
		bindingContext<span style="color: #e8e2b7;">.</span>ModelState<span style="color: #e8e2b7;">.</span>AddModelError(<span style="color: #ec7600;">"null"</span>, 
			<span style="color: #93c763;">new</span> <span style="color: #678cb1;">HttpException</span>(<span style="color: #ffcd22;">404</span>, 
				<span style="color: #93c763;">string</span><span style="color: #e8e2b7;">.</span>Format(<span style="color: #ec7600;">"Could not find {0} ({1}: {2}"</span>, entityType, fieldName, id)));
	<span style="color: #93c763;">return</span> instance;

}</pre>
<p>First I look for the field value using the rules I mentioned above. Next, I figure the entity type. If not specifically set in the attribute, the type should be that of the parameter we're binding to. Next, I use StructureMap.ObjectFactory to get an instance of NHibernate.ISession. You can use any container and ORM you like. The rest is simple. I have omitted the part where you handle array valued parameters, you can see it in the original source.</p>
<h3>Writing a test for our great binder</h3>
<p>As always, I prefer writing an integration test, the one that actully executes an Asp.Net request, because it lets me demonstrate how powerful <a href="/learn.aspx" title="Learn">Ivonna, my Asp.Net testing tool</a>, is. This time, however, I'm adding a little bit of mocking (so it's not a 100% integration test). Because I don't want to setup NHibernate with all that mapping, bootstrapping, and stuff, I'm just stubbing the DB access using the new Ivonna/CThru Stub syntax:</p>
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f; padding: 3px;"><span style="color: #dfdfbf;">session</span>.<span style="color: #aad7d9;">Stub</span>&lt;<span style="color: #6ac2df;">ISession</span>&gt;(<span style="color: #c89191;">"Get"</span>).<span style="color: #aad7d9;">Return</span>(<span style="color: #dfdfbf;">entity</span>);
</pre>
Here you have some kinda brute force stubbing, where you don't need much flexibility, and you don't want anything "force" you into a supposedly good design (which is close to impossible when writing integration tests anyway). Just make the Get method on any ISession instance return this object, regardless of the arguments (strictly speaking, we should verify that the argument is as intended, but let's not overcomplicate our test). Here is the full test:
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f; padding: 3px;"><span style="font-weight: bold; color: #eaeaac;">var</span> <span style="color: #dfdfbf;">entity</span> = <span style="font-weight: bold; color: #eaeaac;">new</span> <span style="color: #bbbbff;">Entity</span>();
<span style="color: #7f9f7f;">// We don't want to set up an ORM, </span>
<span style="color: #7f9f7f;">// so we'll just fake ISession</span>
<span style="font-weight: bold; color: #eaeaac;">var</span> <span style="color: #dfdfbf;">session</span> = <span style="font-weight: bold; color: #eaeaac;">new</span> <span style="color: #bbbbff;">TestSession</span>();
<span style="color: #dfdfbf;">session</span>.<span style="color: #aad7d9;">Stub</span>&lt;<span style="color: #6ac2df;">ISession</span>&gt;(<span style="color: #c89191;">"Get"</span>).<span style="color: #aad7d9;">Return</span>(<span style="color: #dfdfbf;">entity</span>);
 
<span style="color: #7f9f7f;">// Now let's execute a Web request</span>
<span style="font-weight: bold; color: #eaeaac;">var</span> <span style="color: #dfdfbf;">response</span> = <span style="color: #dfdfbf;">session</span>.<span style="color: #48ffff;">Get</span>(<span style="color: #c89191;">"/Sample/Get?entityId=1"</span>);
 
<span style="color: #7f9f7f;">// Check the result</span>
<span style="color: #bbbbff;">Assert</span>.<span style="color: #aad7d9;">AreEqual</span>(<span style="color: #dfdfbf;">entity</span>, <span style="color: #dfdfbf;">response</span>.<span style="color: #bfcb2e;">ActionMethodParameters</span>[<span style="color: #c89191;">"entity"</span>]);</pre>
<p><br />As you see, we prepare an Entity instance, have it returned from the stubbed ORM call, then execute our request, and verify the parameter of the action call. Our Web should have the SampleController class with the Get method having the following signature:</p>
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f; padding: 3px;"><span style="font-weight: bold; color: #83bf55;">public</span> <span style="color: #bbbbff;">ActionResult</span> <span style="color: #aad7d9;">Get</span>([<span style="color: #bbbbff;">EntityBinder</span>()] <span style="color: #bbbbff;">Entity</span> <span style="color: #dfdfbf;">entity</span>)
</pre>
<p>That's it for today, I do hope you'll find it useful, and please tell me that you like to break the rules as much as I do, whenever it makes your (and the others') life happier. I do believe that releasing this binder to the general public I'm doing a Good Thing, and the world became a better place because of this, and maybe even a couple of whales will be saved from brutal killing, but maybe not.</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/z0HdhDnNgII" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/5/11/a-binder-that-breaks-the-rules.aspx</feedburner:origLink></item><item><title>Configuring your assets for FubuMVC</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/9_-Svtu7SbU/configuring-your-assets-for-fubumvc.aspx</link><pubDate>Sat, 14 Apr 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/4/14/configuring-your-assets-for-fubumvc.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>When you have a complicated View, things can easily get messy. A View may have several Partials, each Partial being reused in several Views. Each Partial might require certain library scripts, which in turn might depend on other scripts.</p>
<p>(At this point, I stopped and thought, maybe I should really add images to my posts. Ayende does it, although he has clearly no time for finding an appropriate image. All the cool guys do it. Perhaps I should do it, too.)</p>
<p style="font-style:...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>When you have a complicated View, things can easily get messy. A View may have several Partials, each Partial being reused in several Views. Each Partial might require certain library scripts, which in turn might depend on other scripts.</p>
<p>(At this point, I stopped and thought, maybe I should really add images to my posts. Ayende does it, although he has clearly no time for finding an appropriate image. All the cool guys do it. Perhaps I should do it, too.)</p>
<p style="font-style: italic;">&lt;insert a messy picture here&gt;</p>
<p>(By the way, if you know a place where I could quickly steal images for my posts, please tell me in the comments. I heard that it makes them more entertaining and gives a personal touch.)</p>
<p>Turned out FubuMVC provides a nice solution to this problem. You can have an arbitrary number of "config" files (the extension is misleading, they're plain text files) in arbitrary places, named either *.script.config, or *.asset.config. Each file describes relationships between assets, or just groups them for reference. After that, your View just references a file it needs, and your Master issues a directive to render all required files.</p>
<h3>How do you write a config file</h3>
<p>If you have scripts dependent on each other, you need an ordered set:</p>
<p style="padding-left: 30px;">ordered set {set name}<br />{name1}<br />{name2}</p>
<p>For example,</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: white;">ordered set jslib is</span>
<span style="color: white;">lib/jquery-1.7.1.js</span>
<span style="color: white;">lib/jquery-ui.js</span>
<span style="color: white;">lib/bootstrap.js</span>
<span style="color: white;">lib/tree.jquery.js</span>
<span style="color: white;">lib/amplify.js</span>
</pre>
<p>Unordered set:</p>
<p style="padding-left: 30px;">{set name} includes {name1}, {name2},..</p>
<p>Individual dependencies:</p>
<p style="padding-left: 30px;">{asset name} requires {name1}, {name2}</p>
<p>For example,</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: white;">demo.js requires jslib</span>
</pre>
<p>Ordering individual files:</p>
<p style="padding-left: 30px;">{asset name} preceeds {another name}</p>
<p>Applying a custom policy (should be a type implementing either IAssetPolicy or ICombinationPolicy):</p>
<p style="padding-left: 30px;">apply policy {policy type}</p>
<p>Combining assets:</p>
<p style="padding-left: 30px;">combine {name1}, {name2},.. as {set name}</p>
<p>Alias:</p>
<p style="padding-left: 30px;">{alias} is {asset name}<br />e.g., jquery is lib/jquery.min.js</p>
<p>Extending (not sure what it means -- please enlighten me!):</p>
<p style="padding-left: 30px;">{asset name} extends {another name}</p>
<p>In addition, you can have empty lines for readability, and lines starting with '#' for comments.</p>
<h3>How works them config files?</h3>
<p>Suppose you have the pieces provided above in one of your config files. Whenever you need the demo.js script on your page, you just put</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">&lt;<span style="color: #93c763;">Script</span> <span style="color: #e0e2e4; background: #293134;">src</span><span style="color: #e0e2e4; background: #293134;">=</span><span style="color: #ec7600;">"demo.js"</span> /&gt;
</pre>
somewhere close to the top of your View (assuming you use a Spark ViewEngine with the default bindings; it would work for other Views, of course, but with a slightly different syntax). This directive doesn't output anything, but it tells the Asset Pipeline that you'll need that script at some time. Later, presumably in your Master, you have the following:
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;">&lt;<span style="color: #93c763;">Scripts</span> /&gt;
</pre>
<p>This should render all the required scripts for the page. In particular, although we have never mentioned we need jQuery, it's going to be referenced, since demo.js needs it. All scripts will be rendered in the correct order. In addition, there won't be any duplicates.</p>
<p>Another Good Thing is that the config files acan be easily reused across different projects. After all, the library dependencies is what doesn't depend on a particular project.</p>
<h3>This can't be so good. Now tell me the bad news!</h3>
<p>The bad news is that the current implementation enforces rather strict rules for where your assets should be. Namely, everything should be placed in the Content folder, with the hardcoded subfolder names for styles, scripts, and images. this doesn't work good with styles requiring images in a subfolder, and also can cause some friction e.g. when updating jQuery via NuGet. While having such a rigid structure is a bit unusual for this otherwise very flexible framework, the benefits, in my opinion, outweight the (forgot the English word for that thing that is outweighted by the benefits).</p>
<p>For a real-world sample of what I'm talking about, take a look at <a href="https://github.com/DarthFubuMVC/fubumvc/blob/master/src/FubuMVC.Diagnostics/diagnostics.script.config">https://github.com/DarthFubuMVC/fubumvc/blob/master/src/FubuMVC.Diagnostics/diagnostics.script.config</a></p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/9_-Svtu7SbU" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/4/14/configuring-your-assets-for-fubumvc.aspx</feedburner:origLink></item><item><title>Writing the first test for a Real System</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/wl5ELB5AZJ8/writing-the-first-test-for-a-real-system.aspx</link><pubDate>Sun, 11 Mar 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/3/11/writing-the-first-test-for-a-real-system.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>So, you've read a book on TDD, a couple of blog posts from the gurus, and maybe even done the Calculator Kata several times. Now it's time to apply your knowledge to a Real Life Project that you are starting today. You probably stare at the empty solution and try to figure out where to start. "Create an instance of the System Under Test".. which system? "Mock or stub the dependencies".. which dependencies?</p>
<p>Sounds familiar?</p>
<h3>Let me give you a hand</h3>
<p>Right now I'm also...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>So, you've read a book on TDD, a couple of blog posts from the gurus, and maybe even done the Calculator Kata several times. Now it's time to apply your knowledge to a Real Life Project that you are starting today. You probably stare at the empty solution and try to figure out where to start. "Create an instance of the System Under Test".. which system? "Mock or stub the dependencies".. which dependencies?</p>
<p>Sounds familiar?</p>
<h3>Let me give you a hand</h3>
<p>Right now I'm also staring at the (almost) empty solution. I'll try to document what I think and do, and maybe you'll find it useful. However, remember that it's not the only way to do it, it's probably not the best way, and it even might be a bad way. But it works for me, and it might work for you, so, if you don't have a better solution, you might wanna try this one..</p>
<h3>Meet Chpokk, an online .Net code editor.</h3>
<p><a href="http://chpokk.apphb.com/" target="_blank">Chpokk</a> is meant as a lightweight replacement for Visual Studio, integrated with source control, plus some goodies like refactoring support, running your tests etc. I decided that today is a great day to develop the first feature that might be actually useful.</p>
<h3>What do I want from my tests</h3>
<p>There are several important requirements, that will help me a lot in writing my first test.</p>
<p><strong>I want to produce some business value as soon as possible.</strong> I don't have time for all these funny AbstractFactoryFactory toys. If that means creating a one big static method, fine. I'll refactor it later. But when I refactor it, I need it to be covered with a test. So, my first test should be about the first useful thing I want to implement in my system.</p>
<p><strong>I don't want my tests to be fragile.</strong> I don't know what my UI is going to be, and I don't know my API yet. But changing the UI can easily break many tests that depend on it, while the server side code can be easily refactored in sync with the tests. Not just UI, anything "stringy" should be kept out. For example, I don't want to hardcode the folder in which I'm going to keep the user's code files.</p>
<p>This requirement kind of contradicts the previous one, which suggested that my first test should cover everything. But while the first rquirement is more like a nice wish that would make me happy right now, the second one would save me from perpetual pain later, since robust tests are what makes me sleep well at night.</p>
<p><strong>The tests should not use any knowledge from outside.</strong> This is better explained with an example. Say, I'm going to clone an existing repository from GitHub. Then I'm going to check if a certain file exists locally. The knowledge about the name of the file that should be there is not a part of the test. This can be a problem, since later looking at this test I won't know why it expects this particular file. In addition, I might rename this file later in order to use it in a different test.</p>
<p>How can I fix it? <em>By adding this file to the remote repository as a part of the test</em>. That makes my life harder, but at least I can look at the test and understand why the file should be there. In addition, <em>my test is responsible for setting up its environment</em>. Ideally, the test should have created a remote repository, of course, but that's probably too much. In fact, perhaps I could even manage without adding this file, but the repository content is a changing thing, while the repositories themselves tend to stay longer.</p>
<h3>Enough philosophy, show me the code already!</h3>
<p>Not so fassst, mah friend! Just wait for the next part, where I'm figuring the requirements for the first iteration and writing tests for them.</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/wl5ELB5AZJ8" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/3/11/writing-the-first-test-for-a-real-system.aspx</feedburner:origLink></item><item><title>Ripple, the utility that saves you from your personal NuGet hell</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/uWvdTZaVEp8/ripple,-the-utility-that-saves-you-from-your-personal-nuget-hell.aspx</link><pubDate>Fri, 02 Mar 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/3/2/ripple,-the-utility-that-saves-you-from-your-personal-nuget-hell.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><h3>Managing your dependencies with NuGet can be just fine.</h3>
<p>Unless you want some of these be compiled locally.</p>
<p>For example, imagine that you have a complicated dependency graph, and you've just modified a source of one of the assemblies. Or you just want the freshest bits from the source control. Now you want to use the local version in your project, since you don't want to wait till your modification is accepted and released as a NuGet package. At the same time, you want to ...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><h3>Managing your dependencies with NuGet can be just fine.</h3>
<p>Unless you want some of these be compiled locally.</p>
<p>For example, imagine that you have a complicated dependency graph, and you've just modified a source of one of the assemblies. Or you just want the freshest bits from the source control. Now you want to use the local version in your project, since you don't want to wait till your modification is accepted and released as a NuGet package. At the same time, you want to use the other dependencies managed for you by NuGet, plus merge the recent updates to the ones that you build locally. Welcome back to dependency nightmares.</p>
<h3>This could be even worse than the pre-NuGet era. If only Ripple didn't exist.</h3>
<p><a href="https://github.com/darthfubumvc/ripple" target="_blank">Ripple</a> was created for scenarios like this. Well, not exactly, but at least it can save you from Dependency Hell. What's even better, Ripple will do a lot of things for you so that all your solutions will have the freshest bits from NuGet when the local source is missing, and locally built assemblies conveniently put into the NuGet package folders.</p>
<h3>In other words, Ripple is NuGet's best friend.</h3>
<p>For a good introduction to Ripple (and its requirements), check the Ian Battersby's <a href="http://geek.ianbattersby.com/2011/12/01/ripple-tastic" target="_blank">Ripple-tastic!</a> post. Ian gives an example of a "targeted" rippling -- from one to another solution. However, I have discovered it's more fun to just "ripple around" -- shoot "ripple local" without the "from" and "to" pieces. This way Ripple just fixes and updates everything it can.</p>
<p>There are many Ripple commands available. Here is the (incomplete) list of them, as of today.</p>
<ul>
<li>Clean -- just clean a particular solution, or all solutions. Can clean packages, project outputs, or both.</li>
<li>Float -- makes the package "floating" -- marked as to be updated by Ripple.</li>
<li>GitIgnore -- Lists or adds values to the .gitignore file.</li>
<li>History -- write the list of packages to the dependency-history.txt file.</li>
<li>Init -- Creates a basic ripple.config file and opens it in an editor, removes packages from Git and adds their folder to .gitignore</li>
<li>List -- for each solution, outputs the list of projects with their dependencies and published packages.</li>
<li>Local -- you better try it yourself with a verbose flag and watch the output.</li>
<li>LocalNuget -- Creates the nuget files locally</li>
<li>Lock -- opposite to Float, locks a nuget to prevent it from being automatically updated from the Update command.</li>
<li>Publish -- Builds and pushes all the nuspec files for a solution(s) to nuget.org.</li>
<li>Restore -- another important command, interacts with nuget to restore all the nuget dependencies in a solution tree. </li>
<li>Update -- gets the latest NuGets (or just lets you preview them). As I understand, either Restore or Update is used as part of the Local command execution.</li>
<li>UseTheirs -- Does a 'use theirs' merge on all the project and packages file in a solution.</li>
<li>WhereAmI -- Tells you where ripple thinks the root folder is at.</li>
</ul>
<p>You can see that this is a great piece of functionality for those who works actively with OSS dependencies. It is opinionated, in the ForUsByUs way, but you can happily use it in non-Fubu projects. The only annoying limitation for me is that you should keep your projects in the same folder, but it's not annoying enough for a pull request.</p>
<p>Ripple is included in the buildsupport submodule if you get the source of any Fubu project.</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/uWvdTZaVEp8" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/3/2/ripple,-the-utility-that-saves-you-from-your-personal-nuget-hell.aspx</feedburner:origLink></item><item><title>Getting started with Jasmine tests in FubuMVC applications</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/AyHyXeFoNoM/getting-started-with-jasmine-tests-in-fubumvc-applications.aspx</link><pubDate>Sun, 19 Feb 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/2/19/getting-started-with-jasmine-tests-in-fubumvc-applications.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p> </p>
<p><a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a> is one of the most popular BDD-style Javascript testing frameworks. I decided to use it for my new project, <a href="http://chpokk.apphb.com/" target="_blank">Chpokk</a>, built on top of <a href="http://fubumvc.com" target="_blank">FubuMVC</a>. Here are the steps that I made, together with some for-dummies explanations.</p>
<h3>Adding Jasmine to your project</h3>
<p>is as easy as adding the FubuMVC.TestRun...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p> </p>
<p><a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a> is one of the most popular BDD-style Javascript testing frameworks. I decided to use it for my new project, <a href="http://chpokk.apphb.com/" target="_blank">Chpokk</a>, built on top of <a href="http://fubumvc.com" target="_blank">FubuMVC</a>. Here are the steps that I made, together with some for-dummies explanations.</p>
<h3>Adding Jasmine to your project</h3>
<p>is as easy as adding the FubuMVC.TestRunner NuGet package to your project. After that, navigate to /testing/suites/whatever, and see a greenish almost empty page that says "0 specs". Jasmine is installed.</p>
<h3>What's under the hood?</h3>
<p>After you add the package, you discover a zip file named fubumvc-testrunner.zip in your fubu-content folder. This file is a "bottle", a piece of functionality that adds itself to the main application. With the first Web request, the zip is extracted ("exploded") to a subfolder. Let's see what we have there.</p>
<p>The WebContent folder is mapped to the root of your application. The Shared subfolder contains the Application.spark file, which is going to be the master page for all test pages, and the bindings file.</p>
<p>Take a look at the following snippet from the Application.spark file:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">	&lt;<span style="color: #93c763;">Stylesheet</span> <span style="color: #e0e2e4; background: #293134;">href</span><span style="color: #e0e2e4; background: #293134;">=</span><span style="color: #ec7600;">"jasmine.css"</span> /&gt;
	&lt;<span style="color: #93c763;">Script</span> <span style="color: #e0e2e4; background: #293134;">src</span><span style="color: #e0e2e4; background: #293134;">=</span><span style="color: #ec7600;">"fubumvc-testrunner"</span> /&gt;</pre>
These tags look unfamiliar. Their meaning is explained in the bindings file:
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;">  &lt;<span style="color: #93c763;">element</span> <span style="color: #678cb1;">name</span>=<span style="color: black;">"</span><span style="color: #ec7600;">Stylesheet</span><span style="color: black;">"</span>&gt;<span style="color: white;">#this.Asset('@href');</span>&lt;/<span style="color: #93c763;">element</span>&gt;
  &lt;<span style="color: #93c763;">element</span> <span style="color: #678cb1;">name</span>=<span style="color: black;">"</span><span style="color: #ec7600;">Script</span><span style="color: black;">"</span>&gt;<span style="color: white;">#this.Asset('@src');</span>&lt;/<span style="color: #93c763;">element</span>&gt;
</pre>
this.Asset() is a method that adds a script/css to the list of assets of the page. Note that it produces no output; in order to write all scripts (together with their dependencies), you have to call
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: white;">this.WriteScriptTags()</span>
</pre>
or, using our bindings, just
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;">&lt;<span style="color: #93c763;">Scripts</span> /&gt;
</pre>
<p>The actual View is called Run.spark, and located in the suites folder. It's very simple:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">&lt;<span style="color: #93c763;">viewdata</span> <span style="color: #678cb1;">model</span>=<span style="color: black;">"</span><span style="color: #ec7600;">FubuMVC.TestRunner.Suites.RunSuiteViewModel</span><span style="color: black;">"</span> /&gt;
&lt;<span style="color: #93c763;">content:title</span>&gt;<span style="color: white;">${Model.Suite}</span>&lt;/<span style="color: #93c763;">content:title</span>&gt;
&lt;<span style="color: #93c763;">content:scripts</span>&gt;
  &lt;<span style="color: #93c763;">Script</span> <span style="color: #678cb1;">src</span>=<span style="color: black;">"</span><span style="color: #ec7600;">${Model.Suite}</span><span style="color: black;">"</span> /&gt;
&lt;/<span style="color: #93c763;">content:scripts</span>&gt;</pre>
There are two content areas: one is the page title, the other just adds a script (or a set of scripts, see later) to the page. How do we decide which script to add? We take it from the Url. Because of some model binding magic (plus internal Fubu processing), the last part of the Url is mapped to the Suite property of the model.<br />
<h3>Adding the first test</h3>
<p>In order to use the Fubu's Asset Pipeline, I put my test script into the /Content/scripts folder of my Web.</p>
<p>Here is my sampletest.js:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">describe(<span style="color: #ec7600;">"First test"</span>, <span style="color: #93c763;">function</span>() {
	it(<span style="color: #ec7600;">"should fail"</span>, <span style="color: #93c763;">function</span>() {
		expect(<span style="color: #93c763;">true</span>).toBeFalsy();
	});
});</pre>
<p>As a <strong>real</strong> TDD practitioner, I'm creating a failing test first. Mom would be proud of me!</p>
<p>After saving this file, I navigate to /testing/suites/sampletest.js, and I see a failing test. WIN!</p>
<h3>Dealing with a Real World Problem</h3>
<p>Having all your code in the tests is fine, but at some point a manager might want you to move some of it to the production files. So, we'll need to include several files in our tests. Let's see how to do it.</p>
<p>Let's create another file called realstuff.js, and put it into the Content/Scripts folder:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">function</span> arewegood() {
	<span style="color: #93c763;">return</span> <span style="color: #93c763;">false</span>;
}</pre>
Next, let's create a plain text file, named tests.script.config, and place it in the root of our application. This file will hold our script set definitions. Right now, we'll put the following line there:
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: white;">tests includes realstuff.js, sampletest.js</span>
</pre>
<p>Now, we'll use the name of the set in the Url: /testing/suites/tests. If we look at the source, we'll see that both scripts are loaded. We can put another script set in our config file, and we'll be able to run a different suite with a different Url.</p>
<p>The last step is to modify our test so that it depends on the "production" code:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">describe(<span style="color: #ec7600;">"First test"</span>, <span style="color: #93c763;">function</span>() {
	it(<span style="color: #ec7600;">"should fail"</span>, <span style="color: #93c763;">function</span>() {
		expect(arewegood()).toBeTruthy();
	});
});</pre>
<p>That's it for today, I still have to make this test pass.</p>
<h3>Update</h3>
<p>@jmarnold pointed me that Serenity does all that and lots of other great stuff. I guess I'll have to delete all this and start from scratch. In the next post, I'll tell you what happened.</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/AyHyXeFoNoM" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/2/19/getting-started-with-jasmine-tests-in-fubumvc-applications.aspx</feedburner:origLink></item><item><title>Custom Asp.Net Model Binders series, part 3: Subclassing your models</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/S69XQjlJjjA/custom-aspnet-model-binders-series,-part-3-subclassing-your-models.aspx</link><pubDate>Thu, 02 Feb 2012 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2012/2/2/custom-aspnet-model-binders-series,-part-3-subclassing-your-models.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>This is the third part in the series about custom Asp.Net MVC Model Binders and Value Providers. Part 1 is about two ways of <a href="/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx" title="Custom Asp.Net Model Binders series, part 1: Now How">using DateTime.Now as an Action Method parameter</a> for better testability, and Part 2 is about <a href="/blog/2011/12/7/a-useless-custom-aspnet-value-provider-(or-maybe-not-that-useless-after-all).aspx" title="A useless custom Asp.Net value provider (or maybe not that useless after all)">building a Value Provider for the Http Header values</a>. Read on.</p...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>This is the third part in the series about custom Asp.Net MVC Model Binders and Value Providers. Part 1 is about two ways of <a href="/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx" title="Custom Asp.Net Model Binders series, part 1: Now How">using DateTime.Now as an Action Method parameter</a> for better testability, and Part 2 is about <a href="/blog/2011/12/7/a-useless-custom-aspnet-value-provider-(or-maybe-not-that-useless-after-all).aspx" title="A useless custom Asp.Net value provider (or maybe not that useless after all)">building a Value Provider for the Http Header values</a>. Read on.</p>
<h3>What's up with subclassing your models</h3>
<p>Often you need to use inheritance in your domain model. For example, you might have to model a book with a list <span class="short_text"><span class="hps">bibliographic</span> <span class="hps">references. Each reference might be to an article in a magazine, to another book, to a Web page etc. So, you create a Reference abstract class, and a couple of subclasses for different types of references. You might also want to create a parallel inheritance chain for your models.</span></span></p>
<p><span class="short_text"><span class="hps">Now, suppose you have a list of references. Each row has a link to the page where you can edit the corresponding reference object. While different types of references have different fields to edit, you don't want to create a separate page for each type. Displaying a reference is simple: you just call Html.EditorFor() inside your form, and the fairies will generate the necessary fields for that particular kind of reference. The problem is how to get the new values back.</span></span></p>
<p><span class="short_text"><span class="hps">Suppose you have the following action method:</span></span></p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">[<span style="color: #678cb1;">HttpPost</span>]
<span style="color: #93c763;">public</span> <span style="color: #678cb1;">ActionResult</span> Update(<span style="color: #678cb1;">ReferenceModel</span> model) {
	<span style="color: #66747b;">//...</span>
}</pre>
<p>The default binder will try to create an instance of ReferenceModel, and will fail, since this is an abstract class. So, we'll have to use a different binder. The one that is smart enough so that it could create an instance of the concrete type.</p>
<h3>Implementing the SubclassingBinder</h3>
<p>In order to do it, we'll have to provide the name of the model's type. We'll do it via a hidden field called ModelType:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">&lt;<span style="color: #93c763;">input</span> <span style="color: #e0e2e4; background: #293134;">type=</span><span style="color: #ec7600;">"hidden"</span> <span style="color: #e0e2e4; background: #293134;">name=</span><span style="color: #ec7600;">"ModelType"</span> <span style="color: #e0e2e4; background: #293134;">value=</span><span style="color: #ec7600;">"</span><span style="color: #8c8cb4;">&lt;%</span>=this.Model.GetType() <span style="color: #8c8cb4;">%&gt;</span><span style="color: #ec7600;">"</span>/&gt;
</pre>
<p>One would be tempted to override the CreateModel method, but that wouldn't be enough. The model would be created, but it would not be populated with the subclass-specific properties. The binder would still use the metadata of the base abstract class, so the properties specific to the concrete class will not be picked up.</p>
<p>So, we're going to override the BindModel method and "correct" the model type, then let the binder create and bind a model of the requested type for us. Here's the code:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">override</span> <span style="color: #93c763;">object</span> BindModel(<span style="color: #678cb1;">ControllerContext</span> controllerContext, 
	<span style="color: #678cb1;">ModelBindingContext</span> bindingContext) {
	<span style="color: #93c763;">if</span> (bindingContext<span style="color: #e8e2b7;">.</span>ValueProvider<span style="color: #e8e2b7;">.</span>ContainsPrefix(<span style="color: #ec7600;">"ModelType"</span>)) {
		<span style="color: #66747b;">//get the model type</span>
		<span style="color: #93c763;">var</span> typeName <span style="color: #e8e2b7;">=</span> (<span style="color: #93c763;">string</span>) bindingContext
			<span style="color: #e8e2b7;">.</span>ValueProvider
			<span style="color: #e8e2b7;">.</span>GetValue(<span style="color: #ec7600;">"ModelType"</span>)
			<span style="color: #e8e2b7;">.</span>ConvertTo(<span style="color: #93c763;">typeof</span>(<span style="color: #93c763;">string</span>));
		<span style="color: #93c763;">var</span> modelType <span style="color: #e8e2b7;">=</span> <span style="color: #678cb1;">Type</span><span style="color: #e8e2b7;">.</span>GetType(typeName);
 
		<span style="color: #66747b;">//tell the binder to use it</span>
		bindingContext<span style="color: #e8e2b7;">.</span>ModelMetadata <span style="color: #e8e2b7;">=</span> 
			<span style="color: #678cb1;">ModelMetadataProviders</span>
			<span style="color: #e8e2b7;">.</span>Current
			<span style="color: #e8e2b7;">.</span>GetMetadataForType(<span style="color: #93c763;">null</span>, modelType);
	}
	<span style="color: #93c763;">return</span> <span style="color: #93c763;">base</span><span style="color: #e8e2b7;">.</span>BindModel(controllerContext, bindingContext);
}</pre>
<h3>Do you have teh tests?</h3>
<p>Oh yes we have! As always, we're going to test our code with the help of <a href="/" title="Ivonna, Asp.Net unit and integration testing tool">Ivonna, our favorite Asp.Net testing tool</a>. Here's the test. It verifies two things: given the model type and a property value, a model of the correct type is created and the property is filled with that value (disclaimer: I'm usually opposed to several asserts in a test, but I'm doing it here for clarity):</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">[<span style="color: #678cb1;">TestFixture</span>, <span style="color: #678cb1;">RunOnWeb</span>]
<span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">ModelSubclassing</span> {
	<span style="color: #93c763;">private</span> <span style="color: #93c763;">const</span> <span style="color: #93c763;">string</span> NEW_ARTICLE_NAME 
		<span style="color: #e8e2b7;">=</span> <span style="color: #ec7600;">"On the meaning of death"</span>;
 
	[<span style="color: #678cb1;">Test</span>]
	<span style="color: #93c763;">public</span> <span style="color: #93c763;">void</span> BinderCreatesArticleModelWithValues() {
		<span style="color: #93c763;">var</span> response <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">TestSession</span>()
			<span style="color: #e8e2b7;">.</span>Post(<span style="color: #ec7600;">"/Sample/UpdateReference"</span>,
			<span style="color: #93c763;">new</span> {
				ModelType <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">typeof</span>(<span style="color: #678cb1;">ArticleModel</span>)
					<span style="color: #e8e2b7;">.</span>ToString(),
				ArticleName <span style="color: #e8e2b7;">=</span> NEW_ARTICLE_NAME
			});
			
		<span style="color: #66747b;">//verify that we have the corect model type</span>
		<span style="color: #678cb1;">Assert</span><span style="color: #e8e2b7;">.</span>IsInstanceOf<span style="color: #e8e2b7;">&lt;</span><span style="color: #678cb1;">ArticleModel</span><span style="color: #e8e2b7;">&gt;</span>(
			response<span style="color: #e8e2b7;">.</span>ActionMethodParameters[<span style="color: #ec7600;">"model"</span>]);
		<span style="color: #66747b;">//verify that we have filled </span>
		<span style="color: #66747b;">//the concrete type specific properties</span>
		<span style="color: #93c763;">var</span> model <span style="color: #e8e2b7;">=</span> 
			(<span style="color: #678cb1;">ArticleModel</span>)response
				<span style="color: #e8e2b7;">.</span>ActionMethodParameters[<span style="color: #ec7600;">"model"</span>];
		<span style="color: #678cb1;">Assert</span><span style="color: #e8e2b7;">.</span>AreEqual(NEW_ARTICLE_NAME, model<span style="color: #e8e2b7;">.</span>ArticleName);
	}
}</pre>
<br />That's all for today. You can grab the code from <a href="https://github.com/uluhonolulu/BlogSamples" target="_blank">GitHub</a>. Comments are welcome!<br /><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/S69XQjlJjjA" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2012/2/2/custom-aspnet-model-binders-series,-part-3-subclassing-your-models.aspx</feedburner:origLink></item><item><title>A useless custom Asp.Net value provider (or maybe not that useless after all)</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/7nFToK9m-64/a-useless-custom-aspnet-value-provider-(or-maybe-not-that-useless-after-all).aspx</link><pubDate>Wed, 07 Dec 2011 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2011/12/7/a-useless-custom-aspnet-value-provider-(or-maybe-not-that-useless-after-all).aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>So, following my previous post on <a href="/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx" title="Custom Asp.Net Model Binders series, part 1: Now How">implementing a custom Asp.Net Value Provider</a>, here is another one.</p>
<h3>Request Header Value Provider</h3>
<p>Here is a totally useless requirement: add a Value Provider that would let you use your request headers in your actions without calling HttpContext.Current.Request (or something equally unacceptable). This is actually absurdly simple, because we alread...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>So, following my previous post on <a href="/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx" title="Custom Asp.Net Model Binders series, part 1: Now How">implementing a custom Asp.Net Value Provider</a>, here is another one.</p>
<h3>Request Header Value Provider</h3>
<p>Here is a totally useless requirement: add a Value Provider that would let you use your request headers in your actions without calling HttpContext.Current.Request (or something equally unacceptable). This is actually absurdly simple, because we already have a convenient base class, NameValueCollectionValueProvider, that takes a collection and provides its values to the unsuspecting Controller. So, the code it pretty simple:</p>
<pre style="font-family: Consolas; font-size: 12px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">RequestHeaderValueProvider</span> : <span style="color: #678cb1;">NameValueCollectionValueProvider</span> {
	<span style="color: #93c763;">public</span> RequestHeaderValueProvider(<span style="color: #678cb1;">ControllerContext</span> controllerContext)
		: <span style="color: #93c763;">base</span>(controllerContext<span style="color: #e8e2b7;">.</span>HttpContext<span style="color: #e8e2b7;">.</span>Request<span style="color: #e8e2b7;">.</span>Headers, 
			<span style="color: #678cb1;">CultureInfo</span><span style="color: #e8e2b7;">.</span>CurrentCulture) { }
 
}
 
<span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">RequestHeaderValueProviderFactory</span> : <span style="color: #678cb1;">ValueProviderFactory</span> {
	<span style="color: #93c763;">public</span> <span style="color: #93c763;">override</span> <span style="color: #8c8cb4;">IValueProvider</span> GetValueProvider<br />			(<span style="color: #678cb1;">ControllerContext</span> controllerContext) {
		<span style="color: #93c763;">return</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">RequestHeaderValueProvider</span>(controllerContext);
	}
}</pre>
Note that we need a ValueProviderFactory again. And we need to regiser it in Global.asax as well:
<pre style="font-family: Consolas; font-size: 12px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: #678cb1;">ValueProviderFactories</span><span style="color: #e8e2b7;">.</span>Factories<span style="color: #e8e2b7;">.</span>Add(<span style="color: #93c763;">new</span> <span style="color: #678cb1;">RequestHeaderValueProviderFactory</span>());
</pre>
<p>Now it's enough to name the action method parameter as the header you need, and you'll get the value automatically.</p>
<h3>Writing a test for it</h3>
<p>So, I wasn't completely honest with you when I said it was completely useless. Apart from using it in RESTful apps, there is a pretty common need to get the Referer value, mostly for redirecting back to it as part of the Post-Redirect-Get routine. So, we can test two things (using <a href="/" title="Ivonna, Asp.Net unit and integration testing tool">Ivonna</a> of course): that we have our Referer value as an argument, and that we are actually redirecting to it. Both are integration tests, and the second one is testing both our infrastructure and the actual Action method, but who cares:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">[<span style="color: #678cb1;">Test</span>]
<span style="color: #93c763;">public</span> <span style="color: #93c763;">void</span> TestHeaderProvider() {
	<span style="color: #93c763;">var</span> request <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">WebRequest</span>(<span style="color: #ec7600;">"/Sample/ActionUsingReferer"</span>)
		{AutoRedirect <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">false</span>};
	<span style="color: #93c763;">const</span> <span style="color: #93c763;">string</span> previousurl <span style="color: #e8e2b7;">=</span> <span style="color: #ec7600;">"/PreviousUrl"</span>;
	request<span style="color: #e8e2b7;">.</span>Headers[<span style="color: #ec7600;">"Referer"</span>] <span style="color: #e8e2b7;">=</span> previousurl;
	<span style="color: #93c763;">var</span> response <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">TestSession</span>()<span style="color: #e8e2b7;">.</span>ProcessRequest(request);
	<span style="color: #678cb1;">Assert</span><span style="color: #e8e2b7;">.</span>AreEqual(previousurl, 
			response<span style="color: #e8e2b7;">.</span>ActionMethodParameters[<span style="color: #ec7600;">"referer"</span>]);
	<span style="color: #678cb1;">Assert</span><span style="color: #e8e2b7;">.</span>AreEqual(previousurl, 
			response<span style="color: #e8e2b7;">.</span>RedirectLocation);
}</pre>
<p>Notice that we have to disable the Autoredirection feature of Ivonna: without that, we'll be testing the result of the redirection (quick poll: do you want this property to be false by default?), rather than the original request. Notice that we ae using the new MVC feature of Ivonna: the ability to get the action method parameters.</p>
<p>Finally, here's the code that makes this test happy:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #678cb1;">ActionResult</span> ActionUsingReferer(<span style="color: #93c763;">string</span> referer) {
	<span style="color: #93c763;">return</span> Redirect(referer);
}</pre>
Unfortunately, header names like <span class=" ">User-Agent are not very C# friendly, so you might have modify your code in order to be able to consume these headers as parameters named, say, user_agent.<br /></span><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/7nFToK9m-64" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2011/12/7/a-useless-custom-aspnet-value-provider-(or-maybe-not-that-useless-after-all).aspx</feedburner:origLink></item><item><title>Custom Asp.Net Model Binders series, part 1: Now How</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/JKZPkiR8auE/custom-aspnet-model-binders-series,-part-1-now-how.aspx</link><pubDate>Wed, 02 Nov 2011 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>Recently I started a <a href="http://www.linkedin.com/groups/1-week-Custom-Binder-Marathon-1931721.S.77995829">challenge</a> on LinkedIn: let's write blog posts about custom model binders, view results, and other extensible stuff in Asp.Net MVC; let's do it one post a day for a week and see what happens. Presumably, it should benefit everybody, especially Asp.Net MVC newcomers.</p>
<p>Well, I'm two days late already, and I don't feel like doing a big post today, so today's a really simple...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>Recently I started a <a href="http://www.linkedin.com/groups/1-week-Custom-Binder-Marathon-1931721.S.77995829">challenge</a> on LinkedIn: let's write blog posts about custom model binders, view results, and other extensible stuff in Asp.Net MVC; let's do it one post a day for a week and see what happens. Presumably, it should benefit everybody, especially Asp.Net MVC newcomers.</p>
<p>Well, I'm two days late already, and I don't feel like doing a big post today, so today's a really simple custom Model Binder. But first, we should decide which functionality we wan to move to our binders. For me, an eye opening post was <a href="http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx">Scott Hanselmann's one on his IPrincipal binder</a>. The logic here is very simple. The Smart Guys Who Invented Asp.Net MVC wanted it to be testable. Specifically, they wanted the Action Methods to be testable. So, let's make them happy and proud of us, and let's write testable Action Methods, shall we?</p>
<p>There are two simple tricks that can help with it. One trick is widely adopted in general programming: Dependency Injection. You can write a service, use it as a constructor argument in your Controller, and use this service inside your method to retrieve the required value (and also to execute an action, but that's a different story). However, you can end up with 10 methods, each requiring a different service, hence 10 services injected in the constructor, and you'll have to create all 10 for testing each method.</p>
<p>Another option is parameter injection: you don't create a service in order to retrieve a value (and mock it in your tests), you just use your value as a parameter. The testability problem is solved, but how about the runtime behavior? Yes, we'll use custom Model Binders (and Value Providers).</p>
<h3>Let's see your example</h3>
<p>One of the common values that are used in our methods, but cannot be tested using our usual tools, is DateTime.Now. Yes, I know that Typemock Isolator can mock it now, but that's not the point. The point is that, rather than call it inside our method, we can provide it as an argument. It would be our Custom Model Binder's responsibility to look at the watch and tell us the time. (Note that we don't eliminate the untestable part, we just move it from our controller elsewhere)</p>
<p>Here's the code for the custom binder:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">NowBinder</span> : <span style="color: #8c8cb4;">IModelBinder</span> {
	<span style="color: #93c763;">public</span> <span style="color: #93c763;">object</span> BindModel(
			<span style="color: #678cb1;">ControllerContext</span> controllerContext, 
			<span style="color: #678cb1;">ModelBindingContext</span> bindingContext) {
		<span style="color: #93c763;">return</span> <span style="color: #678cb1;">DateTime</span><span style="color: #e8e2b7;">.</span>Now;
	}
}</pre>
<p>And the example usage:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #678cb1;">ActionResult</span> ActionUsingCurrectDateTime(
	[<span style="color: #678cb1;">ModelBinder</span>(<span style="color: #93c763;">typeof</span>(<span style="color: #678cb1;">NowBinder</span>))] <span style="color: #678cb1;">DateTime</span> current) {..</pre>
<p>You are encouraged to subclass the ModelBindingAttribute in order to make it more readable, but that's another story.</p>
<h3>Doing it with a custom Value Provider</h3>
<p>While custom Model Binders are used more or less widely, there's another point of extensibility tht might be of use here: a custom Asp.Net MVC Value Provider. This might be even more appropriate: while Model Binders are created to construct objects from data, Value Providers are the ones who retrieve this data from the outside world. Obviously, the system clock is a part of this "outside world" so, let's use a value provider:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">NowValueProvider</span> : <span style="color: #8c8cb4;">IValueProvider</span> {
	<span style="color: #93c763;">public</span> <span style="color: #93c763;">bool</span> ContainsPrefix(<span style="color: #93c763;">string</span> prefix) {
		<span style="color: #93c763;">return</span> prefix <span style="color: #e8e2b7;">==</span> <span style="color: #ec7600;">"now"</span>;
	}
 
	<span style="color: #93c763;">public</span> <span style="color: #678cb1;">ValueProviderResult</span> GetValue(<span style="color: #93c763;">string</span> key) {
		<span style="color: #93c763;">var</span> now <span style="color: #e8e2b7;">=</span> <span style="color: #678cb1;">DateTime</span><span style="color: #e8e2b7;">.</span>Now;
		<span style="color: #93c763;">if</span> (key <span style="color: #e8e2b7;">==</span> <span style="color: #ec7600;">"now"</span>)
			<span style="color: #93c763;">return</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">ValueProviderResult</span>(
				now, 
				now<span style="color: #e8e2b7;">.</span>ToString(<span style="color: #678cb1;">CultureInfo</span><span style="color: #e8e2b7;">.</span>CurrentCulture), 
				<span style="color: #678cb1;">CultureInfo</span><span style="color: #e8e2b7;">.</span>CurrentCulture);
		<span style="color: #93c763;">return</span> <span style="color: #93c763;">null</span>;
	}
}</pre>
Unfortunately, using it is not that simple: you have to subclass ValueProviderFactory:
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #93c763;">class</span> <span style="color: #678cb1;">NowValueProviderFactory</span> : <span style="color: #678cb1;">ValueProviderFactory</span> {
	<span style="color: #93c763;">public</span> <span style="color: #93c763;">override</span> <span style="color: #8c8cb4;">IValueProvider</span> 
		GetValueProvider(<span style="color: #678cb1;">ControllerContext</span> controllerContext) {
		<span style="color: #93c763;">return</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">NowValueProvider</span>();
	}
}</pre>
And register it in the global.asax:
<pre style="font-family: Consolas; font-size: 13px; color: #f1f2f3; background: none repeat scroll 0% 0% #22282a; padding: 3px;"><span style="color: #678cb1;">ValueProviderFactories</span><span style="color: #e8e2b7;">.</span>Factories<span style="color: #e8e2b7;">.</span>Add(<span style="color: #93c763;">new</span> <span style="color: #678cb1;">NowValueProviderFactory</span>());
</pre>
<p>However, you don't have to use a custom binder now, just name your parameter "now", and it'll be automatically bound to DateTime.Now:</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;"><span style="color: #93c763;">public</span> <span style="color: #678cb1;">ActionResult</span> ActionUsingNowValueProvider(<span style="color: #678cb1;">DateTime</span> now)
</pre>
<p>In addition, whenever your model has a property named "Now", it'll be filled automatically by the default model binder.</p>
<p>Isn't it sweet?</p>
<h3>Can we test that it works?</h3>
<p>Previously I said that we're moving the untestable part to a different place. The point is, we have moved it to our infrastructure, leaving our controller clean of infrastructure concerns. However, with the latest <a href="/download/version-3-download.aspx" title="Version 3 download">Ivonna</a><a href="/download/version-3-download.aspx" title="Version 3 download"> for MVC</a> we can test that the whole thing works together correctly.</p>
<pre style="font-family: Consolas; font-size: 13; color: #f1f2f3; background: #22282a; padding: 3px;">[<span style="color: #678cb1;">Test</span>]
<span style="color: #93c763;">public</span> <span style="color: #93c763;">void</span> TestValueProvider() {
	<span style="color: #93c763;">var</span> result <span style="color: #e8e2b7;">=</span> <span style="color: #93c763;">new</span> <span style="color: #678cb1;">TestSession</span>()
		<span style="color: #e8e2b7;">.</span>Get(<span style="color: #ec7600;">"/Sample/ActionUsingNowValueProvider"</span>);
	<span style="color: #93c763;">var</span> model <span style="color: #e8e2b7;">=</span> (<span style="color: #678cb1;">DateTime</span>) result<span style="color: #e8e2b7;">.</span>Model;
	<span style="color: #678cb1;">Assert</span><span style="color: #e8e2b7;">.</span>AreApproximatelyEqual (
		<span style="color: #678cb1;">DateTime</span><span style="color: #e8e2b7;">.</span>Now, 
		model, 
		<span style="color: #678cb1;">TimeSpan</span><span style="color: #e8e2b7;">.</span>FromSeconds(<span style="color: #ffcd22;">1</span>)) ;
}</pre>
<br /><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/JKZPkiR8auE" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2011/11/2/custom-aspnet-model-binders-series,-part-1-now-how.aspx</feedburner:origLink></item><item><title>Fighting AppDomainUnloadedException and the PrivateBinPath problem</title><link>http://feedproxy.google.com/~r/ivonna/oigv/~3/86S8mYpVBDk/fighting-appdomainunloadedexception-and-the-privatebinpath-problem.aspx</link><pubDate>Mon, 24 Oct 2011 00:00:00 GMT</pubDate><guid isPermaLink="false">http://ivonna.biz/blog/2011/10/24/fighting-appdomainunloadedexception-and-the-privatebinpath-problem.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>Today I'm fighting with two very annoying bugs in Ivonna.</p>
<p>The first one is, when you debug your tests, sometimes you get the AppDomainUnloaded exception ("Attempted to access an unloaded AppDomain"). That one has been annoying me for some time, so I decided to fix it. I have opened the thread list, found the thread that contained a call to AppDomain.Unload, switched to it, and checked the HttpRuntime instance. The _shutDownMessage field told me: "Change Notification for critical di...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>Today I'm fighting with two very annoying bugs in Ivonna.</p>
<p>The first one is, when you debug your tests, sometimes you get the AppDomainUnloaded exception ("Attempted to access an unloaded AppDomain"). That one has been annoying me for some time, so I decided to fix it. I have opened the thread list, found the thread that contained a call to AppDomain.Unload, switched to it, and checked the HttpRuntime instance. The _shutDownMessage field told me: "Change Notification for critical directories.\r\nbin dir change or directory rename\r\nHostingEnvironment initiated shutdown\r\nHostingEnvironment caused shutdown". So I watched the bin folder while running the test and discovered that Gallio copied the test project's config file to it, and then deleted it in the middle of a test. The runtime discovered that the bin folder contents has been changed and it should crash just in case.</p>
<p>Fixing it has been easy. I just stubbed the ReleaseResourcesAndUnloadAppDomain method using the <a href="http://cthru.codeplex.com/">CThru</a> built-in Stub aspect.</p>
<p>The other bug is actually two bugs that manifest themselves only when combined. Ivonna creates an AppDomain for testing, and this AppDomain was having a duplicate PrivateBinPath (two identical paths actually). This was fine until I tried to test a <a href="http://mvc.fubu-project.org/">FubuMVC</a> based project that expected a single path in the PrivateBinPath property (actually it's a Bottles bug, but, since nobody uses multiple bin paths, the bug is probably not worth fixing). I won't bother you with technical details, but the good news is that Ivonna is now fully compatible with FubuMVC.</p><img src="http://feeds.feedburner.com/~r/ivonna/oigv/~4/86S8mYpVBDk" height="1" width="1"/>]]></content:encoded><feedburner:origLink>http://ivonna.biz/blog/2011/10/24/fighting-appdomainunloadedexception-and-the-privatebinpath-problem.aspx</feedburner:origLink></item></channel></rss>

