<?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:rssdatehelper="urn:rssdatehelper"><channel><title>Fresh.Thoughts</title><link>http://ivonna.biz</link><pubDate>2013-03-08T15:10:33</pubDate><category>CodeProject</category><generator>umbraco</generator><description>Random revelations on .Net programming and other earthly stuff</description><language>en</language><item><title>Testing async requests, mocking async methods with new Ivonna</title><link>http://ivonna.biz/blog/2013/3/8/testing-async-requests,-mocking-async-methods-with-new-ivonna.aspx</link><pubDate>Fri, 08 Mar 2013 00:00:00 GMT</pubDate><guid>http://ivonna.biz/blog/2013/3/8/testing-async-requests,-mocking-async-methods-with-new-ivonna.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>For those of you who can't wait to start testing async requests, here's the good news (and no, there are <em>no</em> bad news in this post): starting with <a href="/download.aspx" title="Download">the 3.1 version of Ivonna</a>, you can test them with the same syntax as before, i.e. using either session.Get(url) or session.GetPage(url).</p>
<p>However, this is not the end of the story. Most of the time you use the async pattern for a reason. You have a lengthy operation in your Web code...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>For those of you who can't wait to start testing async requests, here's the good news (and no, there are <em>no</em> bad news in this post): starting with <a href="/download.aspx" title="Download">the 3.1 version of Ivonna</a>, you can test them with the same syntax as before, i.e. using either session.Get(url) or session.GetPage(url).</p>
<p>However, this is not the end of the story. Most of the time you use the async pattern for a reason. You have a lengthy operation in your Web code. And that's the other good news: now you can mock async methods called from your controllers/codebehind/whetever, returning custom values. This functionality is a part of the Ivonna.Framework.MVC assembly, but you can use it with any Web framework -- it's not really related to MVC, but I didn't put it into Ivonna itself since I didn't want to introduce the .Net 4.0 dependency (this might change in the future).</p>
<p>Suppose you have the following code that you want to test (taken from MSDN):</p>
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f;"><span style="font-weight: bold; color: #83bf55;">public</span> <span style="color: #dfdfbf;">async</span> <span style="color: #bbbbff;">Task</span><span style="color: #a2cd52;">&lt;</span><span style="color: #bbbbff;">ActionResult</span><span style="color: #a2cd52;">&gt;</span> <span style="color: #aad7d9;">About</span>() {
	<span style="color: #dfdfbf;">var</span> <span style="color: #ebebe2;">client</span> <span style="color: #a2cd52;">=</span> <span style="font-weight: bold; color: #83bf55;">new</span> <span style="color: #bbbbff;">HttpClient</span>();
	<span style="font-weight: bold; color: #83bf55;">string</span> <span style="color: #ebebe2;">urlContents</span> <span style="color: #a2cd52;">=</span> <span style="color: #dfdfbf;">await</span> <span style="color: #ebebe2;">client</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetStringAsync</span>(<span style="color: #c89191;">"http://msdn.microsoft.com"</span>);
	<span style="font-weight: bold; color: #83bf55;">return</span> <span style="color: #aad7d9;">Content</span>(<span style="color: #ebebe2;">urlContents</span>);
}</pre>
You can test the whole method, but the test would have wait for the HttpClient to return the result, which can take a long time, and be unpredictable. In addition, you might want to test your controller's logic, not the code that runs the MSDN site. So, you want a predictable return value, and you want it fast. Here is how the new functionality helps you:
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f;"><span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">session</span> <span style="color: #a2cd52;">=</span> <span style="font-weight: bold; color: #83bf55;">new</span> <span style="color: #bbbbff;">TestSession</span>();
<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">fakeResponseString</span> <span style="color: #a2cd52;">=</span> <span style="color: #c89191;">"We Are Microsoft"</span>;
<span style="color: #ebebe2;">session</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">Stub</span><span style="color: #a2cd52;">&lt;</span><span style="color: #bbbbff;">HttpClient</span><span style="color: #a2cd52;">&gt;</span>(<span style="color: #c89191;">"GetStringAsync"</span>)<span style="color: #a2cd52;">.</span><span style="color: #48ffff;">ReturnFromAsync</span>(<span style="color: #ebebe2;">fakeResponseString</span>);</pre>
<p>There's also a strongly typed lambda-based overload, but personally I find it less convenient and more noisy. Note that a stub like this works on all requests for all instances of HttpClient, so if you want a more fine grained control, you'll have to implement your own CThru aspect.</p>
<p>One more gotcha here. Some useful async methods are implemented as extensions, so you cannot use the syntax above. Use more verbose session.AddAspect(new Stub(..)) instead.</p>
<p>I really hope you'll find these new features useful. Enjoy!</p>
<p>P.S. I strongly suggest that you use <a href="http://www.typemock.com/ivonna-march-sale">this opportunity to save 16% on Ivonna and Isolator</a> (ends March 31st).</p>]]></content:encoded></item><item><title>Writing the first test for a Real System, Part II</title><link>http://ivonna.biz/blog/2012/7/21/writing-the-first-test-for-a-real-system,-part-ii.aspx</link><pubDate>Sat, 21 Jul 2012 00:00:00 GMT</pubDate><guid>http://ivonna.biz/blog/2012/7/21/writing-the-first-test-for-a-real-system,-part-ii.aspx</guid><description><![CDATA[ <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967" rel="tag" style="display:none;">  codeproject  </a><p>Guilt. That's what I've been feeling all these days.</p>
<p>Ok, it's not that I spent the past month in a deep depression. I should confess that I'm not that kind of guy. But naming a post "blah blah part I" is kinda making a commitment. And the longer I kept postponing writing the second part, the worse I was feeling about it. So, I finally decide that I won't leave my workplace until I finish it.</p>
<p>In <a href="/blog/2012/3/11/writing-the-first-test-for-a-real-system.aspx" title="Writing the first test for a Real System">Par...]]></description><content:encoded><![CDATA[  <a  href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=646967"  rel="tag"  style="display:none;">  codeproject  </a><p>Guilt. That's what I've been feeling all these days.</p>
<p>Ok, it's not that I spent the past month in a deep depression. I should confess that I'm not that kind of guy. But naming a post "blah blah part I" is kinda making a commitment. And the longer I kept postponing writing the second part, the worse I was feeling about it. So, I finally decide that I won't leave my workplace until I finish it.</p>
<p>In <a href="/blog/2012/3/11/writing-the-first-test-for-a-real-system.aspx" title="Writing the first test for a Real System">Part I</a>, I have defined some guidelines that would help me in writing my first test. What's missing is the requirements for this particular system (<a href="http://chpokk.apphb.com/" target="_blank">Chpokk, and online C# code editor</a>) I'm building. So, let me remind you these guidelines, this time with practical application.</p>
<h3><strong>I want to produce some business value as soon as possible</strong></h3>
<p>What I want my application to do is something that people will find actually useful. "As soon as possible" means a Minimal Viable Product from your marketing course. Perhaps it means that "at least one person might find it useful for at least a small something". In other words, it might be good for a demo. It is not big enough to be used in the daily life, but at least it's better than having just an AbstractFactoryFactoryAdapter. So, instead of building Version One piece by piece, I want to build Version 0.01, not caring much about clean and maintainable code (I'm postponing it for the Refactoring phase), but this version, although being far from perfect in all aspects, will actually solve someone's problem. And of course, among all problems that my applicationis going to solve, I'm choosing the most important one.</p>
<p>This is also very good in terms of getting user's feedback as soon as possible. Since I'm solving a real world problem, there must be some user out there who has this exact problem, so if I provide a solution (for free), this user is going to be my best friend, providing valuable feedback for the rest of her life.</p>
<h3>Back to the point</h3>
<p>So, since I'm building an online code editor, the "something useful" is, well, being able to edit the code. What means "edit"? It means, load, change, save. In my case, "load" is "clone a git repository", since that's where most of the code is stored today (yes I know there are other source control systems, and some people actually use the one named "file system", but I decided to start with Git), and display a file in the editor. "Edit" is "change a file in an online editor", which involves intellisense, refactoring, autosaving and whatnot, but let's forget about it until later. "Save" involves.. ok, let's not talk about it now.</p>
<p><strong>This is the point where I'm going to contradict myself.</strong></p>
<p>Theoretically, I should cover all three parts with one test. The problem is, that would involve multiple user interactions, meaning I should probably add UI testing (in which I'm not very proficient), meaning I should decide on UI (which I don't want to yet), meaning I'll still have to do a lot of things at once. Instead, I split my task into several smaller ones, but I'm not doing it from the developer perspective (I'm not test-driving specific classes), but rather based on user actions.</p>
<p>The first such action is cloning a remote repository. I agree that there is not much business value in it, so I'd rather not showing it to end users (except maybe for my 5-year old Alice), but still it's something that can be shown to somebody -- "hey, this thing can clone a repository!"</p>
<h3><strong>I don't want my tests to be fragile.</strong></h3>
<p>While I don't want certain parts to be fully implemented yet, I also don't want my tests to be dependent on them. These implementation details should be hidden from my tests, and never be tested themselves.</p>
<p>The main reason for a test to be fragile, meaning it can suddenly stop passing while the application behaves correctly, is that it depends on some implementation details. Whenever such a detail changes without affecting the application (for example, as a result of refactoring), the test breaks. Such a test brings more harm than benefit, since we cannot rely on it when checking our application's health. It becomes a burden -- we have to support it in addition to supporting our main application.</p>
<p><em>A typical example is an UI test that relies on element id's. If we are doing Asp.Net WebForms, we often let the framework generate these id's for us. As a result, each time we change our control structure without affecting its functionality (say, add a new NamingContainer), the id's (which are implementation details) change, and our test fails. Don't think that Asp.Net MVC is free from that -- a simple Action Method renaming would make a test that depends on it fail.</em></p>
<p>In our case, one of the implementation details is the physical location of the local repository. I can <em>guess</em> that I should do something to prevent different users or projects use the same folder, but I don't want to care about it right now. So, what I'm doing is <em>encapsulating</em> it, making sure it doesn't <em>leak</em>. For now, I hardcode it to a particular value, but I don't use this value in my tests. So, my tests, just as my production code, use this value without actually knowing it. Later, when the implementation changes, the tests won't break, since they rely on the same implementation.</p>
<p>It also allows me, as agile gurus advice, <strong>delay</strong> the implementation until it's really necessary.</p>
<h3><strong>The tests should not use any knowledge from outside.</strong></h3>
<p>This one has been covered a bit in the previous post, but I'd like to elaborate on it. Sometimes you look at the assert, and you don't understand it at all. I mean, it doesn't have to be crystal clear (that's what the name of the test is for), but at least I should be (eventually) able to understand it, because if it's broken, I have to fix it somehow. Whenever a test depends on some external resources, it becomes totally unclear. In addition, it encourages reusing this external resource, making it complex to satisfy the needs of all tests (I'm looking at you, a test repository for LibGit2Sharp).</p>
<p>Of course, this doesn't apply to the infrastructure. Even unit tests sometimes  are better run with a real database, and we're talking integration tests here.</p>
<p>This is why, rather than taking a database that has some rows pre-inserted, I prefer taking a clean database and inserting the rows I need during the Arrange phase. Another example is when I need to parse a .sln file, rather than using an existing one, I'm creating it in the test. This way I'm free to create as many versions as I need for testing various cases, and I have a unique resource for each test, that contains only the stuff I need for this particular test. But the main benefit is that everything my test needs is just around the corner.</p>
<h3>The requirements</h3>
<p>Before we start writing our test, we should write down the requirements. As I keep insisting, our requirements shouldn't be developer-centric, i.e. they shouldn't be, like, "method xxx should return an instance of yyy with such and such property values". They should be formulated in terms of user expectations.</p>
<p>So, my task for today is to start implementing the "clone" story. I'm coming up with the following requirements:</p>
<ol>
<li>When a user clicks the "open project" button, a popup appears that invites her to enter the repository Url (we assume that the repository is publicly readable). After entering an Url and clicking "Ok", the users sees a progress indicator.</li>
<li>After the process is finished, a user is redirected to the "Project" page.</li>
<li>This page should display the list of the files.</li>
</ol>
<p>Now, as I mentioned previously, I'd like to split this into several tests. For a particular test that I'll be writing now, which is going to be entirely server-side, I've got the following story:</p>
<span style="text-decoration: underline;">If a user submits the Url of a remote publicly readable repository to our system, it should clone a repository to a folder where this user can access it later.</span><br />
<p>Note that I don't specify the exact location of the target folder here (see Rule #2). Instead, there's a rather vague "where.. can access it later", which is not clear how to program. Let's say this means the result of some property or method which will be introduced by our code.</p>
<h3>Finally, the code</h3>
<p>I was delaying it as long as I could, but finally here it is:</p>
<pre style="font-family: Consolas; font-size: 13; color: #dcdccc; background: #3f3f3f; padding: 3px;"><span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">System</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">System</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">IO</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">Chpokk</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Tests</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">GitHub</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Infrastructure</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">ChpokkWeb</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Features</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Exploring</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">ChpokkWeb</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Features</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Remotes</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">LibGit2Sharp</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Tests</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">TestHelpers</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">MbUnit</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Framework</span>;
<span style="font-weight: bold; color: #83bf55;">using</span> <span style="color: #9b9bff;">StructureMap</span>;
 
<span style="color: #7f9f7f;">// Namespace should correspond to the feature we're developing </span>
<span style="color: #7f9f7f;">// Later it's going to help me to find this particular test</span>
<span style="font-weight: bold; color: #83bf55;">namespace</span> <span style="color: #9b9bff;">Chpokk</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Tests</span><span style="color: #a2cd52;">.</span><span style="color: #9b9bff;">Cloning</span> {
	<span style="font-weight: bold; color: #83bf55;">public</span> <span style="font-weight: bold; color: #83bf55;">class</span> <span style="color: #bbbbff;">WhenYouSendACloneCommandToAServer</span> {
		<span style="font-weight: bold; color: #83bf55;">private</span> <span style="font-weight: bold; color: #83bf55;">string</span> <span style="color: #bfcb2e;">_fileName</span>;
		<span style="font-weight: bold; color: #83bf55;">private</span> <span style="font-weight: bold; color: #83bf55;">string</span> <span style="color: #bfcb2e;">_targetFolder</span>;
 
		<span style="color: #7f9f7f;">// First, prepare the context</span>
		[<span style="color: #bbbbff;">FixtureSetUp</span>]
		<span style="font-weight: bold; color: #83bf55;">public</span> <span style="font-weight: bold; color: #83bf55;">void</span> <span style="color: #aad7d9;">Setup</span>() {
			<span style="font-weight: bold; color: #83bf55;">const</span> <span style="font-weight: bold; color: #83bf55;">string</span> <span style="font-weight: bold; color: #b6ce2b;">repoUrl</span> <span style="color: #a2cd52;">=</span> <span style="color: #c89191;">"git://github.com/uluhonolulu/Chpokk-Scratchpad.git"</span>;
			<span style="color: #7f9f7f;">// ARRANGE</span>
 
			<span style="color: #7f9f7f;">// Create a random filename</span>
			<span style="color: #bfcb2e;">_fileName</span> <span style="color: #a2cd52;">=</span> <span style="color: darkblue;">Guid</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">NewGuid</span>()<span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">ToString</span>();
			<span style="color: #7f9f7f;">// Commit a new file to the remote repository</span>
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">content</span> <span style="color: #a2cd52;">=</span> <span style="color: #c89191;">"stuff"</span>;
			<span style="color: #bbbbff;">Api</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">CommitFile</span>(<span style="color: #bfcb2e;">_fileName</span>, <span style="color: #ebebe2;">content</span>);
 
			<span style="color: #7f9f7f;">// Prepare the target folder</span>
			<span style="color: #7f9f7f;">// This is where we get the relative repository path </span>
 			<span style="color: #7f9f7f;">// See discussion about Rule #2</span>
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">repositoryInfo</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">ObjectFactory</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetInstance</span><span style="color: #a2cd52;">&lt;</span><span style="color: #bbbbff;">RepositoryInfo</span><span style="color: #a2cd52;">&gt;</span>();
			<span style="color: #bfcb2e;">_targetFolder</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">Path</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">Combine</span>(<span style="color: #ba96fe;">Path</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetFullPath</span>(<span style="color: #db726c;">@".."</span>), <span style="color: #ebebe2;">repositoryInfo</span><span style="color: #a2cd52;">.</span><span style="color: #bfcb2e;">Path</span>);
			<span style="color: #7f9f7f;">// We cannot clone into a nonempty directory, so delete it</span>
			<span style="font-weight: bold; color: #83bf55;">if</span> (<span style="color: #ba96fe;">Directory</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">Exists</span>(<span style="color: #bfcb2e;">_targetFolder</span>))
				<span style="color: #ba96fe;">DirectoryHelper</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">DeleteDirectory</span>(<span style="color: #bfcb2e;">_targetFolder</span>);
 
			<span style="color: #7f9f7f;">// ACT</span>
 
			<span style="color: #7f9f7f;">// Get an instance of our controller.</span>
			<span style="color: #7f9f7f;">// I'm using a container so that I don't have to rewrite it</span>
			<span style="color: #7f9f7f;">// each time I change the signature of the constructor.</span>
			<span style="color: #7f9f7f;">// For unit tests, use automocking container.</span>
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">controller</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">ObjectFactory</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetInstance</span><span style="color: #a2cd52;">&lt;</span><span style="color: #bbbbff;">CloneController</span><span style="color: #a2cd52;">&gt;</span>();
			<span style="color: #7f9f7f;">// Create a model for using with our Action Method.</span>
			<span style="color: #7f9f7f;">// PhysicalApplicationPath is databound automatically,</span>
			<span style="color: #7f9f7f;">// but in out test we need to submit it.</span>
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">model</span> <span style="color: #a2cd52;">=</span> <span style="font-weight: bold; color: #83bf55;">new</span> <span style="color: #bbbbff;">CloneInputModel</span> 
				{<span style="color: #bfcb2e;">PhysicalApplicationPath</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">Path</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetFullPath</span>(<span style="color: #c89191;">".."</span>), 
					<span style="color: #bfcb2e;">RepoUrl</span> <span style="color: #a2cd52;">=</span> <span style="font-weight: bold; color: #b6ce2b;">repoUrl</span>};
			<span style="color: #7f9f7f;">// Finally, execute the Action method.</span>
			<span style="color: #ebebe2;">controller</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">CloneRepository</span>(<span style="color: #ebebe2;">model</span>);
 
		}
 
		[<span style="color: #bbbbff;">Test</span>]
		<span style="font-weight: bold; color: #83bf55;">public</span> <span style="font-weight: bold; color: #83bf55;">void</span> <span style="color: #aad7d9;">RepositoryFilesShouldAppearInTheDestinationFolder</span>() {
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">expectedFile</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">Path</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">Combine</span>(<span style="color: #bfcb2e;">_targetFolder</span>, <span style="color: #bfcb2e;">_fileName</span>);
			<span style="font-weight: bold; color: #83bf55;">var</span> <span style="color: #ebebe2;">existingFiles</span> <span style="color: #a2cd52;">=</span> <span style="color: #ba96fe;">Directory</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">GetFiles</span>(<span style="color: #bfcb2e;">_targetFolder</span>);
			<span style="color: #bbbbff;">Assert</span><span style="color: #a2cd52;">.</span><span style="color: #aad7d9;">AreElementsEqual</span>(<span style="font-weight: bold; color: #83bf55;">new</span>[] { <span style="color: #ebebe2;">expectedFile</span> }, <span style="color: #ebebe2;">existingFiles</span>);
			
		}
	}
 
}
</pre>
<br />
<h3>Your posts are too long, and I don't understand the main idea</h3>
<p>Ok, here's the summary:</p>
<p><strong>1. Produce the business value as soon as possible. </strong>It means, identify the main benefit that your product does, and write a test for it, end to end. You are allowed, however, to split it into several tests, but each one should represent a significant feature.</p>
<p><strong>Benefits</strong>: When you make this test green, you actually have a working product. You can receive an early feedback on it, you can show it to your Mom, but what's most important, it feels great!</p>
<p><strong>2. Don't let the implementation details leak into your tests.</strong> It means, whenever you have to use some knowledge in your test that's irrelevant to the end user, hide it behind a piece of production code that's implemented as simple as possible.</p>
<p><strong>Benefits</strong>: You don't have to think about these details right now and go straight to goal #1, plus, and this is actually the most important thing, you get solid tests. Because one of the main reasons that tests break over time is that the implementation details change, and these tests depend on them.</p>
<p><strong>3. Always prepare your context in the test code.</strong> It means, other than infrastructure, everything that your test uses should be created as part of it.</p>
<p><strong>Benefits:</strong> Such tests are much easier to support. If your test breaks, at least you can be sure it's not because some external resource has been changed. In addition, it is much easier to figure out what's going on in this test.</p>
<h3>Wrapping up</h3>
<p>This post (both parts) take too long to write. Probably much longer than it deserves. I think I should have written an ebook instead, sell it for $37, and become rich. Anyway, I hope it made somebody's life less boring.</p>]]></content:encoded></item><item><title>Fixing the jQueryUI dialog height in IE, the Quirks way</title><link>http://ivonna.biz/blog/2012/5/11/fixing-the-jqueryui-dialog-height-in-ie,-the-quirks-way.aspx</link><pubDate>Sat, 12 May 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>A binder that breaks the rules</title><link>http://ivonna.biz/blog/2012/5/11/a-binder-that-breaks-the-rules.aspx</link><pubDate>Fri, 11 May 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>Configuring your assets for FubuMVC</title><link>http://ivonna.biz/blog/2012/4/14/configuring-your-assets-for-fubumvc.aspx</link><pubDate>Sat, 14 Apr 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>Writing the first test for a Real System</title><link>http://ivonna.biz/blog/2012/3/11/writing-the-first-test-for-a-real-system.aspx</link><pubDate>Sun, 11 Mar 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>Ripple, the utility that saves you from your personal NuGet hell</title><link>http://ivonna.biz/blog/2012/3/2/ripple,-the-utility-that-saves-you-from-your-personal-nuget-hell.aspx</link><pubDate>Fri, 02 Mar 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>Getting started with Jasmine tests in FubuMVC applications</title><link>http://ivonna.biz/blog/2012/2/19/getting-started-with-jasmine-tests-in-fubumvc-applications.aspx</link><pubDate>Sun, 19 Feb 2012 00:00:00 GMT</pubDate><guid>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>]]></content:encoded></item><item><title>Custom Asp.Net Model Binders series, part 3: Subclassing your models</title><link>http://ivonna.biz/blog/2012/2/2/custom-aspnet-model-binders-series,-part-3-subclassing-your-models.aspx</link><pubDate>Thu, 02 Feb 2012 00:00:00 GMT</pubDate><guid>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 />]]></content:encoded></item><item><title>A useless custom Asp.Net value provider (or maybe not that useless after all)</title><link>http://ivonna.biz/blog/2011/12/7/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>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>]]></content:encoded></item></channel></rss>
