<?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:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>muonlab</title>
	
	<link>http://blog.muonlab.com</link>
	<description>random .NET and web development musings</description>
	<lastBuildDate>Sun, 07 Mar 2010 19:47:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Muonlab" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="muonlab" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Automatically HTML encoding code expressions in ASP.NET pages and MVC views</title>
		<link>http://blog.muonlab.com/2010/03/05/automatically-html-encoding-code-expressions-in-asp-net-pages-and-mvc-views/</link>
		<comments>http://blog.muonlab.com/2010/03/05/automatically-html-encoding-code-expressions-in-asp-net-pages-and-mvc-views/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 13:10:18 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[OpenRasta]]></category>
		<category><![CDATA[XSS]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=220</guid>
		<description><![CDATA[I&#8217;m fed up of writing:

&#60;%= Html.Encode(bla) %&#62;

throughout my views. Not only is it messy, but ASP.NET&#8217;s default behaviour of &#8220;be as insecure as possible&#8221; means you have to remember to do this everywhere. In addition to this, it simply uses:

System.Web.HttpUtility.HtmlEncode()

underneath, which isn&#8217;t particularly good at preventing XSS.
OpenRasta (a brilliant alternative to MVC which you should [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m fed up of writing:</p>
<pre class="brush: c-sharp;">
&lt;%= Html.Encode(bla) %&gt;
</pre>
<p>throughout my views. Not only is it messy, but ASP.NET&#8217;s default behaviour of &#8220;be as insecure as possible&#8221; means you have to remember to do this everywhere. In addition to this, it simply uses:</p>
<pre class="brush: c-sharp;">
System.Web.HttpUtility.HtmlEncode()
</pre>
<p>underneath, which isn&#8217;t particularly good at preventing XSS.</p>
<p><a href="http://trac.caffeine-it.com/openrasta/wiki">OpenRasta</a> (a brilliant alternative to MVC which you should be using) has an excellent solution to this problem, by using a custom CSharCodeProvider to help with view compilation.</p>
<p>Below is a simplified version of the code OpenRasta uses, demonstrating how you can get automatic HTML encoding of all code expressions in your views. This also works for WebForms.</p>
<p>It uses an IoC service locator to request an arbitrary IHtmlEncoder. This allows you to use whatever encoding library you like, such as <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=051ee83c-5ccf-48ed-8463-02f56a6bfc09&#038;displaylang=en">Microsoft AntiXss</a>.</p>
<pre class="brush: c-sharp;">
public class AutoHtmlEncodingCSharpCodeProvider : CSharpCodeProvider
{
	public AutoHtmlEncodingCSharpCodeProvider()
	{
	}

	public AutoHtmlEncodingCSharpCodeProvider(IDictionary&lt;string, string&gt; providerOptions) : base(providerOptions)
	{
	}

	public override void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options)
	{
		var codeExpressionStatement = statement as CodeExpressionStatement;
		if (codeExpressionStatement != null)
		{
			var methodInvokeExpression = codeExpressionStatement.Expression as CodeMethodInvokeExpression;
			if (methodInvokeExpression != null)
			{
				if (methodInvokeExpression.Method.MethodName == "Write" &#038;&#038; methodInvokeExpression.Parameters.Count == 1)
				{
					var parameter = methodInvokeExpression.Parameters[0] as CodeSnippetExpression;

					if ((parameter != null) &#038;&#038; (!string.IsNullOrEmpty(parameter.Value)))
						parameter.Value = "global::" + GetType().FullName + ".PreProcessObject(this, " + parameter.Value + ")";
				}
			}
		}

		base.GenerateCodeFromStatement(statement, writer, options);
	}

	public static string PreProcessObject(object source, object value)
	{
		if(value is Raw)
			return ((Raw)value).Value;

		var encoder = ServiceLocator.Current.TryGetInstance&lt;IHtmlEncoder&gt;();
		if (encoder != null)
			return encoder.HtmlAttributeEncode(value.ToString());

		return HttpUtility.HtmlAttributeEncode(value.ToString());
	}
}

public class Raw
{
	public string Value { get; set; }

	public static explicit operator Raw(string text)
	{
		return new Raw { Value = text };
	}

	public static implicit operator string(Raw output)
	{
		return output.Value;
	}
}
</pre>
<p>You need to register this in your Web.config like so:</p>
<pre class="brush: xml;">
&lt;system.codedom&gt;
	&lt;compilers&gt;
		&lt;compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="MyAssembly.AutoHtmlEncodingCSharpCodeProvider, MyAssembly"&gt;
			&lt;providerOption name="CompilerVersion" value="v3.5" /&gt;
			&lt;providerOption name="WarnAsError" value="false" /&gt;
		&lt;/compiler&gt;
	&lt;/compilers&gt;
&lt;/system.codedom&gt;
</pre>
<p>Then in your pages, you can do this:</p>
<pre class="brush: xml;">
&lt;p&gt;&lt;%= "&lt;script&gt;alert('i'm encoded, so i wont popup');&lt;/script&gt;" %&gt;&lt;/p&gt;
&lt;p&gt;&lt;%= (Raw)"&lt;strong&gt;i'm bold because im escaped with (Raw)!&lt;/strong&gt;" %&gt;&lt;/p&gt;
</pre>
<p>Which will be rendered as:</p>
<p>&lt;script&gt;alert(&#8216;i&#8217;m encoded, so i wont popup&#8217;);&lt;/script&gt;<br />
<strong>i&#8217;m bold because im escaped with (Raw)!</strong></p>
<p>There you go!</p>
<p>Because this code has been inspired by/copied from/a modification of code from OpenRasta, according to its license I must reproduce the copyright notice. If you also wish to use this code, you must do the same.</p>
<pre>
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/03/05/automatically-html-encoding-code-expressions-in-asp-net-pages-and-mvc-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use MVC’s UrlHelper in your tests with RhinoMocks</title>
		<link>http://blog.muonlab.com/2010/02/22/how-to-use-mvcs-urlhelper-in-your-tests-with-rhinomocks/</link>
		<comments>http://blog.muonlab.com/2010/02/22/how-to-use-mvcs-urlhelper-in-your-tests-with-rhinomocks/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 11:47:22 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=101</guid>
		<description><![CDATA[In order to use the UrlHelper class in your tests, you need to construct it with a ControllerContext, which consists of an HttpRequest and an HttpResponse. Unfortunately these are quite difficult to construct, as you&#8217;ll know if you&#8217;ve ever tried. Luckily, the UrlHelper doesn&#8217;t use much of these two classes, only a few properties, making [...]]]></description>
			<content:encoded><![CDATA[<p>In order to use the UrlHelper class in your tests, you need to construct it with a ControllerContext, which consists of an HttpRequest and an HttpResponse. Unfortunately these are quite difficult to construct, as you&#8217;ll know if you&#8217;ve ever tried. Luckily, the UrlHelper doesn&#8217;t use much of these two classes, only a few properties, making them fairly easy to mock.</p>
<p>The first thing you need to do is get your routes, usually declared in your Global.asax MvcApplication</p>
<pre class="brush: c-sharp;">
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
</pre>
<p>Then you need to mock an HttpRequest</p>
<pre class="brush: c-sharp;">
var request = MockRepository.GenerateStub&lt;HttpRequestBase&gt;();
request.Stub(x =&gt; x.ApplicationPath).Return("/");
request.Stub(x =&gt; x.Url).Return(new Uri("http://localhost/a", UriKind.Absolute));
request.Stub(x =&gt; x.ServerVariables).Return(new System.Collections.Specialized.NameValueCollection());
</pre>
<p>Then you need to mock the HttpResponse</p>
<pre class="brush: c-sharp;">
var response = MockRepository.GenerateStub&lt;HttpResponseBase&gt;();
response.Stub(x =&gt; x.ApplyAppPathModifier(Arg&lt;string&gt;.Is.Anything))
    .Return(null)
    .WhenCalled(x =&gt; x.ReturnValue = x.Arguments[0]);
</pre>
<p>Then you can simply stick these two mocks onto a mock context, and use that to create your UrlHelper instance and set them on the controller you are testing:</p>
<pre class="brush: c-sharp;">
var context = MockRepository.GenerateStub&lt;HttpContextBase&gt;();
context.Stub(x =&gt; x.Request).Return(request);
context.Stub(x =&gt; x.Response).Return(response);

var subjectUnderTest = new MyController(); // this is the controller you are testing

subjectUnderTest.ControllerContext = new ControllerContext(context, new RouteData(), subjectUnderTest);
subjectUnderTest.Url = new UrlHelper(new RequestContext(context, new RouteData()), routes);
</pre>
<p>Job done.</p>
<p>Now go and use OpenRasta and not have any of these problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/02/22/how-to-use-mvcs-urlhelper-in-your-tests-with-rhinomocks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Validation in OpenRasta</title>
		<link>http://blog.muonlab.com/2010/02/22/implementing-validation-in-openrasta/</link>
		<comments>http://blog.muonlab.com/2010/02/22/implementing-validation-in-openrasta/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 10:38:52 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[OpenRasta]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=185</guid>
		<description><![CDATA[In this post I&#8217;m going to discuss one method of implementing validation into your OpenRasta handlers using an OperationInterceptor.
OpenRasta deliberately doesn&#8217;t ship with a validation framework, there are plenty out there for you to use. For the purposes of this post, I&#8217;m not using any particular validation framework, simply demonstrating the point with a generic [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;m going to discuss one method of implementing validation into your OpenRasta handlers using an OperationInterceptor.</p>
<p>OpenRasta deliberately doesn&#8217;t ship with a validation framework, there are plenty out there for you to use. For the purposes of this post, I&#8217;m not using any particular validation framework, simply demonstrating the point with a generic IValidator, something like:</p>
<pre class="brush: c-sharp;">
public interface IValidator&lt;TResource&gt;
{
    ValidationReport Validate(object resource);
}
</pre>
<p>First, lets see a way you <i>could</i> do validation in an MVC sort of way:</p>
<pre class="brush: c-sharp;">
public class EditUserHandler
{
    private readonly IValidator&lt;EditUserResource&gt; validator;

    public EditUserHandler(IValidator&lt;EditUserResource&gt; validator)
    {
        this.validator = validator;
    }

    public OperationResult Post(EditUserResource resource)
    {
        var validationReport = validator.Validate(resource);

        if (!validationReport.IsValid)
            return new OperationResult.BadRequest {ResponseResource = resource};

        // save user details here

        return new OperationResult.SeeOther {RedirectLocation = "~/ "};
    }
</pre>
<p>This is probably a very familiar pattern and something you could expect to see inside all hander operations which require validation. Meh. This duplication is not only wasteful, but its unnecessary noise cluttering up your Operation and we can get rid of it.</p>
<p>OperationInterceptors wrap the execution of an operation, giving you three places to interact, BeforeExecute, RewriteOperation and AfterExecute. In this instance, we are only concerned with BeforeExecution.</p>
<p>This method is called just before the Operation in invoked, this is where we want to examine the input parameters, and check if they are valid.</p>
<p>For the purposes of brevity, the below code assumes there is only one parameter to your operation method; hence the FirstOrDefault();</p>
<pre class="brush: c-sharp;">
public class ValidationOperationInterceptor : OperationInterceptor
{
	private readonly IDependencyResolver resolver;
	private readonly ICommunicationContext context;

	public ValidationOperationInterceptor(IDependencyResolver resolver, ICommunicationContext context)
	{
		this.resolver = resolver;
		this.context = context;
	}

	public override bool BeforeExecute(OpenRasta.OperationModel.IOperation operation)
	{
		var input = operation.Inputs.FirstOrDefault();

		if(input == null)
			return true;

		var parameter = input.Binder.BuildObject();

		var validatorType = typeof(IValidator&lt;&gt;).MakeGenericType(parameter.Instance.GetType());

		if (!resolver.HasDependency(validatorType))
			return true;

		var validator = this.resolver.Resolve(validatorType) as IValidator;

		var validationReport = validator.Validate(parameter.Instance);

		if (validationReport.IsValid)
			return true;

		// add validation errors here

		context.OperationResult = new OperationResult.BadRequest { ResponseResource = parameter.Instance };
		return false;
	}
}
</pre>
<p>We register this OperationInterceptor as follows:</p>
<pre class="brush: c-sharp;">
ResourceSpace.Uses.CustomDependency&lt;IOperationInterceptor, ValidationOperationInterceptor&gt;(DependencyLifetime.Transient);
</pre>
<p>The above code assumes that the parameter binding succeeded, I&#8217;ll demonstrate a way to deal with binding failures in a future post (its very similar to the above code).</p>
<p>So what effect does this code have? Well, it can make your handlers super clean:</p>
<pre class="brush: c-sharp;">
public class EditUserHandler
{
    public OperationResult Post(EditUserResource resource)
    {
        // save user details here

        return new OperationResult.SeeOther {RedirectLocation = "~/ "};
    }
</pre>
<p>Your Operations are now only called when the resource is valid, excellent!</p>
<p>You may be seeing one obvious drawback with this approach, that being what if your resources need extra data setting on them before they get sent to the codec in the case of invalidity? When editing a user, perhaps the resource needs to also contain a list of possible authorization roles, one of which will be selected for the user. Having a single mechanism for handling validation for all types doesn&#8217;t allow you anywhere to set this extra information on the resource. Well, there is a solution I&#8217;ll be proposing in my next post.</p>
<p>So stay tuned <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/02/22/implementing-validation-in-openrasta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handlers and Operation Results in OpenRasta</title>
		<link>http://blog.muonlab.com/2010/02/16/handlers-and-operation-results-in-openrasta/</link>
		<comments>http://blog.muonlab.com/2010/02/16/handlers-and-operation-results-in-openrasta/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 10:09:27 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[OpenRasta]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=174</guid>
		<description><![CDATA[This is the 2nd part to my OpenRasta introduction (see part 1 here) in which I&#8217;m going to cover Handlers and OperationResults.
Handlers are very much like MVC Controllers, except that there is no base class or interface to implement   This makes them incredibly lightweight and a dream to work with.
The OpenRasta equivalent of [...]]]></description>
			<content:encoded><![CDATA[<p>This is the 2nd part to my OpenRasta introduction (<a href="http://blog.muonlab.com/2010/02/12/openrasta-code-camp-at-huddle/">see part 1 here</a>) in which I&#8217;m going to cover Handlers and OperationResults.</p>
<p>Handlers are very much like MVC Controllers, except that there is no base class or interface to implement <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  This makes them incredibly lightweight and a dream to work with.</p>
<p>The OpenRasta equivalent of MVC Actions are Operations. These look very similar to their MVC counterparts except we return an OperationResult instead of an ActionResult.</p>
<p>OperationResults represent HTTP Status codes, and you should strongly consider the choice of OperationResult that you use.</p>
<pre class="brush: c-sharp;">
public class FooHandler
{
    private readonly IFooService fooService;

    public FooHandler(IFooService fooService)
    {
        this.fooSerivce = fooService;
    }

    public OperationResult Get(int id)
    {
        var foo = fooService.Get(id);

        if(foo == null)
            return new OperationResult.NotFound();

        return new OperationResult.OK(foo);
    }
}
</pre>
<p>(similarly to my last post, I&#8217;ll ignore the fact that we shouldn&#8217;t be sending domain objects out of our handlers for brevity of the example)</p>
<p>In the above case, if the IFooService cannot find the request Foo object, we return an OperationResult.NotFound which is a direct representation of HTTP Status 404.</p>
<p>If it is found, we return an OK (HTTP 200) passing the Foo &#8220;resource&#8221; out as the ResourceResponse for encoding later in the pipeline.</p>
<p>OpenRasta code is designed with discoverability in mind, intellisense is your friend. Start typing:</p>
<pre class="brush: c-sharp;">
new OperationResult.
</pre>
<p>and see the complete list of HTTP Statuses you can return. Different results have different arguments, for example:</p>
<pre class="brush: c-sharp;">
new OperationResult.SeeOther {RedirectLocation = "~/somewhere" }
</pre>
<p>In OpenRasta, Operations have the name of the HTTP Verb you want them to respond to (you can override this behaviour with named operations, more on this later).</p>
<p>This means that you have a Handler per Resource, which is an excellent means of helping enforce S.R.P.</p>
<p>The last part we need is the registration.</p>
<pre class="brush: c-sharp;">
ResourceSpace.Has.ResourcesOfType&lt;Foo&gt;()
    .AtUri("/foo/{id}")
    .HandledBy&lt;FooHandler&gt;()
    .RenderedByAspx("~/Views/Foo.aspx");
</pre>
<p>The brilliant fluent configuration API makes the above code very self explanitory, but just to clarify:</p>
<pre class="brush: c-sharp;">
ResourceSpace.Has.ResourcesOfType&lt;Foo&gt;() // Tell OpenRasta about our Foo type
    .AtUri("/foo/{id}") // Providing the URI where Foos reside. The brackets are parameter templating just like MVC
    .HandledBy&lt;FooHandler&gt;() // Here we tell OpenRasta which class handles requests for Foos
    .RenderedByAspx("~/Views/Foo.aspx"); // Here we set a WebForms codec, using the given view
</pre>
<p>How much simpler could this be?</p>
<p>Next post we&#8217;ll look at Pipeline Contributors</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/02/16/handlers-and-operation-results-in-openrasta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenRasta Code Camp at Huddle</title>
		<link>http://blog.muonlab.com/2010/02/12/openrasta-code-camp-at-huddle/</link>
		<comments>http://blog.muonlab.com/2010/02/12/openrasta-code-camp-at-huddle/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 11:34:29 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[OpenRasta]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=159</guid>
		<description><![CDATA[Huddle are hosting an OpenRasta Code Camp on the 18th February at their London offices. You want to go to this.
You can read more about the event here and register for the event here.
You haven&#8217;t heard of OpenRasta? For those living under a rock, to quote from the wiki:
OpenRasta is a resource-oriented framework for .NET [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.huddle.net">Huddle</a> are hosting an <a href="http://trac.caffeine-it.com/openrasta">OpenRasta</a> Code Camp on the 18th February at their London offices. You want to go to this.</p>
<p>You can <a href="http://blog.huddle.net/openrasta-code-camp">read more about the event here</a> and <a href="http://upcoming.yahoo.com/event/5339036/ENG/London/OpenRasta-Code-Camp/Huddle/?ps=5">register for the event here</a>.</p>
<p>You haven&#8217;t heard of OpenRasta? For those living under a rock, to quote from the wiki:</p>
<blockquote><p>OpenRasta is a resource-oriented framework for .NET enabling easy ReST-ful development of web sites and services. OpenRasta is designed to run on .net 2.0 and above, and can co-exist peacefully with your existing ASP.NET and WCF deployments.</p></blockquote>
<p>However, this statement alone does not come close to describing the awesomeness of OpenRasta.</p>
<p>OpenRasta is &#8220;resource-oriented&#8221;, this really cannot be understated. OpenRasta elegantly embraces the way HTTP is designed which immediately removes countless issues you encounter when using the likes of ASP.NET MVC.</p>
<p>For those who need an HTTP referesher, consider URIs. The clue is in the name, Uniform RESOURCE Identifier. A resource can be anything, to take Seb&#8217;s example from his <a href="http://skillsmatter.com/podcast/open-source-dot-net/openrasta-an-mvc-framework-with-strong-opinions">Progressive.NET talk</a>, a teacup.</p>
<p>Now you can&#8217;t send a teacup over the wire, but we can send an encoded projection. In MVC, you might do something like:</p>
<pre class="brush: c-sharp;">
public ActionResult Get()
{
    var cup = teacupService.Get();
    return View("TeaCup", cup);
}
</pre>
<p>which will use the WebForms view engine to combine the TeaCup.aspx template with the cup resource (I&#8217;m going to overlook the fact that you shouldn&#8217;t be sending your domain objects out directly for brevity).</p>
<p>This is ok, but what happens when you want the teacup in JSON format? You can do one of two things. Either you create a whole new Action method:</p>
<pre class="brush: c-sharp;">
public ActionResult GetAsJson()
{
    var cup = teacupService.Get();
    return Json(cup);
}
</pre>
<p>which immediately creates all sort of code smells; duplication, encoding concerns in the method names (and therefore url) and the method itself. Meh.</p>
<p>Or you could remove some of this duplication by having a single action method and checking the accept headers yourself inside the action method, but come on, seriously. Why should you have to do all this boilerplate/plumbing code yourself? I might as well just be using an HTTP Handler. What power is the Controller giving you if you&#8217;re having to do everything yourself?</p>
<p>Do not fear. OpenRasta is here! Lets see how we do the same thing in OpenRasta:</p>
<pre class="brush: c-sharp;">
public class TeaCupHandler
{
    public OperationResult Get()
    {
        var cup = teacupService.Get();
        return new OperationResult.OK(cup);
    }
}
</pre>
<p>(obviously I&#8217;m ignoring error handling here)</p>
<p>But wait, I hear you cry! Where do I specify the encoding? In the configuration of course, somewhere completely separate to the above handler method, as it isn&#8217;t its concern.</p>
<pre class="brush: c-sharp;">
ResourceSpace.Has.ResourcesOfType&lt;TeaCup&gt;()
    .AtUri("/teacup")
    .HandledBy&lt;TeaCupHandler&gt;()
    .AsJsonDataContract()
    .And.AsXmlDataContract()
    .And.RenderedByAspx("~/Views/TeaCup.aspx");
</pre>
<p>Look at that! One line of code for each type of encoding we want! *joys* The lovely fluent `.And.` allows you to chain up as many different types of encoding support as you like. And because OpenRasta is completely pluggable and extendible (no, it REALLY is, not like in the way MVC claims) you can write your own codecs with extreme ease.</p>
<p>So, that was a very brief introduction to encoding in OpenRasta. In future posts I will cover HTTP verbs and handlers in greater detail, and show you the power of the pipeline!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/02/12/openrasta-code-camp-at-huddle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Fluent NHibernate’s AutoMapper default string to varchar(max)</title>
		<link>http://blog.muonlab.com/2010/01/04/making-fluent-nhibernates-automapper-default-string-to-varcharmax/</link>
		<comments>http://blog.muonlab.com/2010/01/04/making-fluent-nhibernates-automapper-default-string-to-varcharmax/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 17:33:38 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=154</guid>
		<description><![CDATA[You use a convention!

public class StringPropertyConvention : IPropertyConvention, IPropertyConventionAcceptance
{
	public void Apply(IPropertyInstance instance)
	{
		instance.Length(4001);
	}

	public void Accept(IAcceptanceCriteria&#60;IPropertyInspector&#62; criteria)
	{
		criteria.Expect(x => x.Property.PropertyType == typeof (string));
	}
}

  
Make sure you register the conventions with the automapper.
Peace
]]></description>
			<content:encoded><![CDATA[<p>You use a convention!</p>
<pre class="@brush: csharp;">
public class StringPropertyConvention : IPropertyConvention, IPropertyConventionAcceptance
{
	public void Apply(IPropertyInstance instance)
	{
		instance.Length(4001);
	}

	public void Accept(IAcceptanceCriteria&lt;IPropertyInspector&gt; criteria)
	{
		criteria.Expect(x => x.Property.PropertyType == typeof (string));
	}
}
</pre>
<p> <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Make sure you <a href="http://wiki.fluentnhibernate.org/Conventions">register the conventions with the automapper</a>.</p>
<p>Peace</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2010/01/04/making-fluent-nhibernates-automapper-default-string-to-varcharmax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get at the date part of a DateTime with HQL in NHibernate</title>
		<link>http://blog.muonlab.com/2009/12/14/how-to-get-at-the-date-part-of-a-datetime-with-hql-in-nhibernate/</link>
		<comments>http://blog.muonlab.com/2009/12/14/how-to-get-at-the-date-part-of-a-datetime-with-hql-in-nhibernate/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 12:07:12 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[HQL]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=147</guid>
		<description><![CDATA[If you need to get access to the date part of a DateTime through HQL, the easiest way is to use a custom dialect:

public class CustomDialect : SQLiteDialect
{
	public CustomDialect()
	{
		RegisterFunction("DateOnly", new StandardSQLFunction("date", NHibernateUtil.String));
	}
}

public class CustomDialect : MsSql2005Dialect
{
	public CustomDialect()
	{
		RegisterFunction("DateOnly", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(dd, 0, DATEDIFF(dd, 0, ?1))"));
	}
}

Because I use SQLite for my integration tests and MSSQL2005 for my [...]]]></description>
			<content:encoded><![CDATA[<p>If you need to get access to the date part of a DateTime through HQL, the easiest way is to use a custom dialect:</p>
<pre class="brush: csharp;">
public class CustomDialect : SQLiteDialect
{
	public CustomDialect()
	{
		RegisterFunction("DateOnly", new StandardSQLFunction("date", NHibernateUtil.String));
	}
}

public class CustomDialect : MsSql2005Dialect
{
	public CustomDialect()
	{
		RegisterFunction("DateOnly", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(dd, 0, DATEDIFF(dd, 0, ?1))"));
	}
}
</pre>
<p>Because I use SQLite for my integration tests and MSSQL2005 for my runtime database, I need two different dialects, one for each provider. Using the custom function name &#8220;DateOnly&#8221; I can have the same HQL work on both databases <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>You can then use this function, like so:</p>
<pre class="brush: sql;">
select DateOnly(x.Date), count(x.Id)
from someEntity x
group by DateOnly(x.Date)
</pre>
<p>Win.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2009/12/14/how-to-get-at-the-date-part-of-a-datetime-with-hql-in-nhibernate/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>An idiots guide to subversion and .NET project organisation</title>
		<link>http://blog.muonlab.com/2009/12/09/an-idiots-guide-to-subversion-and-net-project-organisation/</link>
		<comments>http://blog.muonlab.com/2009/12/09/an-idiots-guide-to-subversion-and-net-project-organisation/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 14:27:52 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=130</guid>
		<description><![CDATA[Time and time again I encounter repositories which are just a free-for-all mess, so here is a definitive guide to SVN and project code organisation for the tidy-inept.
Most people will use their repository for multiple projects. For this reason it is a sensible idea to have top level folders which semantically group your code. How [...]]]></description>
			<content:encoded><![CDATA[<p>Time and time again I encounter repositories which are just a free-for-all mess, so here is a definitive guide to SVN and project code organisation for the tidy-inept.</p>
<p>Most people will use their repository for multiple projects. For this reason it is a sensible idea to have top level folders which semantically group your code. How you do this depends largely on what code/projects you have in SVN. Here&#8217;s an example:<br />
<code><br />
root<br />
- Customer A<br />
-- Project X<br />
-- Project Y<br />
- Customer B<br />
-- Project Q<br />
-- Project X<br />
</code></p>
<p>Next, under each Project you should have:<br />
<code><br />
Project X<br />
- trunk<br />
- branches<br />
- releases<br />
- tags<br />
</code></p>
<p>Sometimes its more appropriate to have the releases folder under branches (as they technically are branches), it doesn&#8217;t really matter. What is important is that you are <a href="http://www.codinghorror.com/blog/archives/000968.html">branching your releases!</a></p>
<p><strong>.NET Project Organisation</strong></p>
<p>Here is how I organise my projects:<br />
<code><br />
/<br />
/lib<br />
/src<br />
/src/&lt;projectname&gt;.sln<br />
/src/&lt;projectname&gt;&lt;assembly-specific-names&gt;<br />
/tools<br />
/rakefile.rb<br />
</code></p>
<p>Nice and clean <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>The lib folder holds all your 3rd party assemblies which your project utilises.<br />
The src folder contains&#8230;you guessed it, your source code!<br />
The tools folder contains mainly build tools and test runners. Mine also has the <a href="http://www.nhprof.com/">NHibernate Profiler</a> in there, too.<br />
The rakefile is my build script, if you enjoy angled-bracketed-unneccessaryness this could be your NAnt or MSBuild file.</p>
<p>Next, externals. If your project shares code with another, this shared code should be under a separate project, and included via an <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html">svn:external</a> under the lib folder. For example:<br />
<code><br />
/lib/&lt;folder-for-external&gt;<br />
</code></p>
<p><strong>Useful Resources</strong></p>
<p>Here are some <a href="http://stackoverflow.com/questions/222827/how-do-you-organize-your-version-control-repository/304036#304036">great examples of best practices for code and svn organisation.</a></p>
<p>And here is an <a href="http://www.pragprog.com/titles/svn/pragmatic-version-control-using-subversion">excellent book</a> on the subject!</p>
<p>One tidy life&#8230;.Done!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2009/12/09/an-idiots-guide-to-subversion-and-net-project-organisation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to test an MVC FileResult points to an existing file</title>
		<link>http://blog.muonlab.com/2009/10/08/how-to-test-an-mvc-fileresult-points-to-an-existing-file/</link>
		<comments>http://blog.muonlab.com/2009/10/08/how-to-test-an-mvc-fileresult-points-to-an-existing-file/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 22:40:14 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=121</guid>
		<description><![CDATA[Following on from my recent post how to test asp.net mvc views existence, I found myself with in a very similar situation! This time however, it was FileResult instead of ViewResult.
I&#8217;m not making any excuses, this is far from the prettiest or most flexible solution, but for my setup it works perfectly  
Have some [...]]]></description>
			<content:encoded><![CDATA[<p>Following on from my recent post <a href="http://blog.muonlab.com/2009/08/26/testing-asp-net-mvc-views-existence/">how to test asp.net mvc views existence</a>, I found myself with in a very similar situation! This time however, it was FileResult instead of ViewResult.</p>
<p>I&#8217;m not making any excuses, this is far from the prettiest or most flexible solution, but for my setup it works perfectly <img src='http://blog.muonlab.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Have some code:</p>
<pre class="brush: csharp;">
public abstract class ControllerTest&lt;TController&gt; where TController : IController
{
	protected void AssertFileIsCorrectAndExists(FileResult result, string filename)
	{
		// hack of death!!!!
		var webProjectPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, Path.Combine("../../../", typeof(TController).Assembly.GetName().Name)));

			// crudely trim leading ~/
		if (filename.StartsWith("~/"))
			filename = filename.Substring(2);

		var fullPath = Path.Combine(webProjectPath, filename);

		Assert.IsTrue(File.Exists(fullPath), "File `" + fullPath + "` does not exist");
	}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2009/10/08/how-to-test-an-mvc-fileresult-points-to-an-existing-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing ASP.NET MVC Views’ existence</title>
		<link>http://blog.muonlab.com/2009/08/26/testing-asp-net-mvc-views-existence/</link>
		<comments>http://blog.muonlab.com/2009/08/26/testing-asp-net-mvc-views-existence/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 10:51:54 +0000</pubDate>
		<dc:creator>Andrew Bullock</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.muonlab.com/?p=109</guid>
		<description><![CDATA[Following a recent embarrassing episode where I had been banging on about how unit testing saves the world, then released a broken site, I decided a solution to prevent this happening again was necessary!
I currently test my MVC ViewResults like this:

public class when_requesting_a_login_form : ControllerTest&#60;LoginController&#62;
{
	private ViewResult result;

	protected override void Act()
	{
		this.result = this.SubjectUnderTest.LogIn() as ViewResult;
	}

	[Test]
	public void [...]]]></description>
			<content:encoded><![CDATA[<p>Following a recent embarrassing episode where I had been banging on about how unit testing saves the world, then released a broken site, I decided a solution to prevent this happening again was necessary!</p>
<p>I currently test my MVC ViewResults like this:</p>
<pre class="brush: csharp;">
public class when_requesting_a_login_form : ControllerTest&lt;LoginController&gt;
{
	private ViewResult result;

	protected override void Act()
	{
		this.result = this.SubjectUnderTest.LogIn() as ViewResult;
	}

	[Test]
	public void the_login_view_should_be_returned()
	{
		this.result.ViewName.ShouldEqual("Login");
	}
}
</pre>
<p>However this doesn&#8217;t check that the Login.aspx view actually exists (which it didn&#8217;t in the case I&#8217;m talking about, as I only found out at runtime). Below is my new test:</p>
<pre class="brush: csharp;">
[Test]
public void the_login_view_should_be_returned()
{
	AssertViewIsCorrectAndExists(result, "Login");
}</pre>
<p>This assertion not only checks that the view names match, but also that the file exists on disc.</p>
<p>The solution is far from elegant, but it works, which is better than nothing!</p>
<p>Before I show you the codes, some prerequisite knowledge about my solution setup is required.</p>
<p>My folders are ALWAYS organised like this:</p>
<pre>
/src/Project.Web/
/src/Project.Domain/
/src/Project.Tests.Unit/
</pre>
<p>with these folder names matching the assembly names. This allows the following very fragile code to work:</p>
<pre class="brush: csharp;">
protected void AssertViewIsCorrectAndExists(ViewResult result, string viewName)
{
	ViewEngines.Engines.Clear();
	ViewEngines.Engines.Add(new TestingViewEngine());
	Assert.AreEqual(viewName, result.ViewName, "View names do not match");

	var controllerContext = Stub&lt;ControllerContext&gt;();
	controllerContext.RouteData = new RouteData();
	controllerContext.Controller = SubjectUnderTest;

	var controllerName = typeof(TController).Name;
	controllerContext.RouteData.Values.Add("controller", controllerName.Substring(0, controllerName.Length - "controller".Length));

	var viewEngineResult = result.ViewEngineCollection.FindView(controllerContext, result.ViewName, result.MasterName);
	Assert.IsNotNull(viewEngineResult.View, "View '" + result.ViewName + "' could not be found");
}

public class TestingViewEngine : WebFormViewEngine
{
	public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
	{
		// hack of death!!!!
		var webProjectPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, Path.Combine("../../../", controllerContext.Controller.GetType().Assembly.GetName().Name)));

		foreach(var location in this.ViewLocationFormats)
		{
			var virtualViewPath = string.Format(location, viewName, controllerContext.RouteData.Values["controller"]);

			// crudely trim leading ~/
			virtualViewPath = virtualViewPath.Substring(2);

			var fullPath = Path.Combine(webProjectPath, virtualViewPath);

			if (File.Exists(fullPath))
				return new ViewEngineResult(MockRepository.GenerateStub&lt;IView&gt;(), this);
		}

		return new ViewEngineResult(this.ViewLocationFormats);
	}
}
</pre>
<p>Crude I know, but I hope this helps someone!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.muonlab.com/2009/08/26/testing-asp-net-mvc-views-existence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
