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

<channel>
	<title>Daniel Irvine</title>
	<atom:link href="http://danielirvine.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://danielirvine.com</link>
	<description>Code in a cold climate</description>
	<lastBuildDate>Thu, 17 May 2012 17:11:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>The case for data consistency</title>
		<link>http://danielirvine.com/blog/2012/05/17/the-case-for-data-consistency/</link>
		<comments>http://danielirvine.com/blog/2012/05/17/the-case-for-data-consistency/#comments</comments>
		<pubDate>Thu, 17 May 2012 17:11:16 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=178</guid>
		<description><![CDATA[<p>This issue came up at work today and I wanted to briefly discuss it. We&#8217;re adding a new feature that would ensure a 100% validity of objects in a certain data store. I&#8217;ll describe the scenario: Suppose you have an object A in the data store and you want to ask the question is A [...]]]></description>
			<content:encoded><![CDATA[<p>This issue came up at work today and I wanted to briefly discuss it. We&#8217;re adding a new feature that would ensure a 100% validity of objects in a certain data store. I&#8217;ll describe the scenario: Suppose you have an object A in the data store and you want to ask the question <em>is A valid for use?</em> The system has a large number of objects of this type and performs a variety of operations on them, from simple &#8220;read&#8221; operations to more complicated operations like &#8220;install&#8221; and &#8220;calculate dependencies&#8221;. Before any of these operations are performed we must ensure the validity of the object, and so an &#8220;is valid&#8221; operation becomes very important.</p>
<p>Given that, isn&#8217;t it better to ensure that all objects going <em>in</em> to the data store are valid <em>and remain valid?</em> This way, all operations that read the data can safely assume that the answer to the validity question is <strong>always</strong> yes, that the object is valid. So there&#8217;s no need to do any extra processing for these operations, and the &#8220;is valid&#8221; operation itself becomes a no-op.</p>
<p>The feature we are building should ensure that only valid objects can be added and that any operations that may cause an object to become invalid are either blocked or cause affected objects to be removed from the data store <em>before</em> the operation is performed.</p>
<p>Generalizing this idea is useful: keeping data as consistent as possible will simplify your system. The more consistent your data is, the less conditional (<em>if [this] else [that]</em>) processing will be required for all operations acting on that data.</p>
<p>In this particular case, by ensuring that objects in the data store are consistently valid, we no longer have to worry about checking for validity.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2012/05/17/the-case-for-data-consistency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding 403 Forbidden</title>
		<link>http://danielirvine.com/blog/2011/07/18/understanding-403-forbidden/</link>
		<comments>http://danielirvine.com/blog/2011/07/18/understanding-403-forbidden/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 21:34:35 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[openrasta]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=164</guid>
		<description><![CDATA[<p>There&#8217;s a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that&#8217;s just it: it&#8217;s for authentication, not authorization. Receiving a 401 response is the server telling you, &#8220;you aren&#8217;t authenticated&#8211;either not authenticated at all or authenticated incorrectly&#8211;but please reauthenticate and try again.&#8221; To help you out, it will always include a [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a problem with <code>401 Unauthorized</code>, the HTTP status code for authentication errors. And that&#8217;s just it: it&#8217;s for authentication, not authorization. Receiving a 401 response is the server telling you, &#8220;you aren&#8217;t authenticated&#8211;either not authenticated at all or authenticated incorrectly&#8211;but please reauthenticate and try again.&#8221; To help you out, it will always include a <code>WWW-Authenticate</code> header that describes <em>how</em> to authenticate.</p>
<p>This is a response generally returned by your web server, not your web application.</p>
<p>It&#8217;s also something very temporary; the server is asking you to try again.</p>
<p>So, for authorization I use the <code>403 Forbidden</code> response.  It&#8217;s permanent, it&#8217;s tied to my application logic, and it&#8217;s a more concrete response than a 401.</p>
<p>Receiving a 403 response is the server telling you, &#8220;I&#8217;m sorry. I know who you are&#8211;I believe who you say you are&#8211;but you just don&#8217;t have permission to access this resource. Maybe if you ask the system administrator nicely, you&#8217;ll get permission. But please don&#8217;t bother me again until your predicament changes.&#8221;</p>
<p>In summary, a <code>401 Unauthorized</code> response should be used for missing or bad authentication, and a <code>403 Forbidden</code> response should be used afterwards, when the user is authenticated but isn&#8217;t authorized to perform the requested operation on the given resource.</p>
<p>Well that&#8217;s my view on it anyway <img src='http://danielirvine.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/07/18/understanding-403-forbidden/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Authorizing REST requests with OpenRasta</title>
		<link>http://danielirvine.com/blog/2011/06/30/authorizing-rest-requests-with-openrasta/</link>
		<comments>http://danielirvine.com/blog/2011/06/30/authorizing-rest-requests-with-openrasta/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 22:40:18 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[openrasta]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=128</guid>
		<description><![CDATA[<p>Over the next few posts I&#8217;ll discuss how I&#8217;ve implemented a variety of HTTP and REST features using OpenRasta. Being somewhat of an OpenRasta novice I can&#8217;t say that I&#8217;ve solved these problems in the best way possible, or even with total correctness, but the solutions work well enough.</p> <p>For those new to OpenRasta, the [...]]]></description>
			<content:encoded><![CDATA[<p>Over the next few posts I&#8217;ll discuss how I&#8217;ve implemented a variety of HTTP and REST features using OpenRasta. Being somewhat of an OpenRasta novice I can&#8217;t say that I&#8217;ve solved these problems in the best way possible, or even with total correctness, but the solutions work well enough.</p>
<p>For those new to OpenRasta, the system is underpinned by its pipeline model.  An HTTP request is received and flows through the pipeline, being processed and modified in various ways before coming out as an HTTP response at the other end.  Somewhere in the middle of this pipeline is the <em>resource handler</em>, which is the object that does the real work of processing your request.  Generally you&#8217;ll have one resource handler class for each domain object in your system, and it&#8217;s often the class you&#8217;ll implement first when you begin writing your service.</p>
<p>But somewhere along the way, around about the time you implement your second or third resource handler, you&#8217;ll realize you&#8217;re repeating yourself.  Each resource needs to be validated, each resource action needs to be authorized, action parameters need to be validated, et cetera. You&#8217;ll be following the same patterns for each resource.</p>
<p>But our first tenet is Don&#8217;t Repeat Yourself, right?</p>
<p>Luckily OpenRasta keeps us on the straight and narrow.  It calls a special object called the <code>OperationInterceptor</code> before and after the resource handler runs. The interceptor has the opportunity to change the response entirely, and to exit out of the pipeline if necessary (for example, to deliver a Bad Request response).  Diagrammatically it can be thought of in the following way.</p>
<div id="attachment_155" class="wp-caption aligncenter" style="width: 483px"><a href="http://danielirvine.com/wp-content/uploads/2011/06/openrasta-operation-interceptors.png"><img class="size-full wp-image-155" title="OpenRasta's pipeline model" src="http://danielirvine.com/wp-content/uploads/2011/06/openrasta-operation-interceptors.png" alt="OpenRasta's pipeline model" width="473" height="193" /></a><p class="wp-caption-text">OpenRasta&#39;s pipeline model</p></div>
<p>For the remainder of this post I&#8217;ll look at authorization, and in subsequent posts I&#8217;ll look at the other steps.</p>
<p><strong>Resource-aware authorization</strong><br />
I&#8217;ve defined an <code>IAuthorizable</code> interface that resources can implement if they are authorizable (perhaps by checking permissions in a database, for example).</p>
<pre class="prettyprint [lang-csharp]">
interface IAuthorizable {
	string RequiredPermission { get; }
	string UserName { get; }  // provided as a result of authentication
}
</pre>
<p>How the UserName gets populated is a story for another day, but assume for now that the resource request knows about it.  Next up, we have an <code>IAuthorizer</code>, which is the component that actually does the authorization of an IAuthorizable.</p>
<pre class="prettyprint [lang-csharp]">
interface IAuthorizer {
	bool IsAuthorized(IAuthorizable authorizable);
}
</pre>
<p>How you implement these classes is up to you and entirely dependent on your system.  But given these interfaces, you can write an <code>OperationInterceptor</code> that authorizes in the following way.</p>
<pre class="prettyprint [lang-csharp]">
public class AuthorizationInterceptor : OperationInterceptor
{
	readonly ICommunicationContext _context;
	readonly IAuthorizer _authorizer;

	public AuthorizationInterceptor(
		ICommunicationContext context,
		IAuthorizer authorizer)  {
		_context = context;
		_authorizer = authorizer;
	}

	public override bool BeforeExecute(IOperation operation) {
		var input = operation.Inputs.FirstOrDefault();
		if (input == null) return true;

		var parameter = input.Binder.BuildObject();
		var authorizable = parameter.Instance as IAuthorizable;
		if(authorizable != null) {
			if(!_authorizer.IsAuthorized(authorizable)) {
				_context.OperationResult
					= new OperationResult.Forbidden();
				return false;
			}
		}
	}
}
</pre>
<p>A quick walkthrough of the code: firstly, if the resource doesn&#8217;t implement <code>IAuthorizable</code>, it returns true, meaning the resource handler gets called and everything continues as normal. This is especially important because chances are that not all your resources require authorization (especially if you have an &#8220;entry&#8221; resource into your system that is accessible by all).</p>
<p>If IsAuthorized returns false, we return a <code>403 Forbidden</code> response.</p>
<p>One word of warning, if your IAuthorizer does anything useful at all, you&#8217;ll probably want to handle errors.  If your authorizer can&#8217;t reasonably make a choice—for example, let&#8217;s say the permission database can&#8217;t be accessed and throws an exception—then you <em>must, must, must</em> return a failure code: either <code>403 Forbidden</code>, or more appropriately <code>500 Internal Server Error</code>.  This code isn&#8217;t shown here but it&#8217;s not hard to add: just wrap the call to IsAuthorized in a try/catch block.</p>
<p>Finally, you may wonder why I&#8217;m returning a <code>403 Forbidden</code> and not a <code>401 Unauthorized</code>. I&#8217;ll cover that in my next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/06/30/authorizing-rest-requests-with-openrasta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenRasta testing wierdness</title>
		<link>http://danielirvine.com/blog/2011/06/24/openrasta-testing-wierdness/</link>
		<comments>http://danielirvine.com/blog/2011/06/24/openrasta-testing-wierdness/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 17:58:18 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[openrasta]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=149</guid>
		<description><![CDATA[<p>I was having trouble today with some OpenRasta tests using the InMemoryHost. The tests passed when run in isolation (i.e. together but as their own unit), but when run in the context of the entire test assembly the tests failed with this exception being thrown:</p> <p>TestFixture failed: System.TypeInitializationException : The type initializer for 'OpenRasta.Hosting.HostManager' threw [...]]]></description>
			<content:encoded><![CDATA[<p>I was having trouble today with some OpenRasta tests using the InMemoryHost. The tests passed when run in isolation (i.e. together but as their own unit), but when run in the context of the entire test assembly the tests failed with this exception being thrown:</p>
<p><code>TestFixture failed: System.TypeInitializationException : The type initializer for 'OpenRasta.Hosting.HostManager' threw an exception.<br />
  ----> OpenRasta.DI.DependencyResolutionException : No type registered for ILogger<br />
   at OpenRasta.Hosting.HostManager.RegisterHost(IHost host)<br />
   at OpenRasta.Hosting.InMemory.InMemoryHost..ctor(IConfigurationSource configuration) in c:\src\openrasta-stable\src\openrasta-core\src\OpenRasta\Hosting\InMemory\InMemoryHost.cs:line 19</code><br />
The nature of the error made me suspect a static type somewhere. I cracked open the source for HostManager (via GitHub) and tracked it down to the <code>DependencyManager</code>.  So for anyone else suffering this issue, here&#8217;s how to solve it. Calling <code>DependencyManager.SetResolver()</code> is the cause, so if you have a test that does this then you need to make sure you call <code>Dependencymanager.UnsetResolver()</code> afterwards.  Simple.</p>
<p>I should admit that I&#8217;ve only myself to blame for this, because<a href="https://github.com/openrasta/openrasta-stable/wiki/Linking-to-Resources"> it&#8217;s written right here in the documentation</a>. Schoolboy error, right?</p>
<p>Anyway. Now I&#8217;ve got 46 tests passed, 0 failed. Lovely.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/06/24/openrasta-testing-wierdness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Applying multiple OpenRasta OperationInterceptors</title>
		<link>http://danielirvine.com/blog/2011/06/10/applying-multiple-openrasta-operationinterceptors/</link>
		<comments>http://danielirvine.com/blog/2011/06/10/applying-multiple-openrasta-operationinterceptors/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 13:25:25 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[openrasta]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=126</guid>
		<description><![CDATA[<p>OpenRasta has the concept on an OperationInterceptor, a special class that runs before and after your handler method is called. It&#8217;s useful when you have a cross-cutting action that should apply across all your resources. A couple of typical examples are:</p> Validation, when you need to validate the incoming resource object on a Put or [...]]]></description>
			<content:encoded><![CDATA[<p>OpenRasta has the concept on an <code>OperationInterceptor</code>, a special class that runs before and after your handler method is called.  It&#8217;s useful when you have a cross-cutting action that should apply across all your resources.  A couple of typical examples are:</p>
<ol>
<li><strong>Validation</strong>, when you need to validate the incoming resource object on a <code>Put</code> or <code>Post</code></li>
<li><strong>Authorization</strong>, when you need to check that the authenticate user has rights to perform this action on the resource.</li>
</ol>
<p>So you create a subtype of <code>OperationInterceptor</code>, and you hook it up in your <code>IConfigurationSource</code> like this:</p>
<pre class="prettyprint [lang-csharp]">
ResourceSpace.Uses
    .CustomDependency&lt;IOperationInterceptor, MyOperationInterceptor&gt;
        (DependencyLifetime.Transient);
</pre>
<p>Unfortunately, OpenRasta only supports one <code>OperationInterceptor</code>. That makes the OpenRasta API much simpler: if OpenRasta supported multiple interceptors, it would need a mechanism for ordering each of the <code>OperationInterceptor</code> instances that you pass it.</p>
<p>Thanksfully it&#8217;s easy to get around because we can use create a <code>CompositeOperationInterceptor</code> that does our ordering for us.  It&#8217;s dead simple and you&#8217;ll find the code below.  This&#8217;ll work if you&#8217;ve got a <code>ValidationInterceptor</code> and an <code>AuthorizationInterceptor</code> (you&#8217;ll need to write these yourself, of course).</p>
<pre class="prettyprint [lang-csharp]">
public class CompositeOperationInterceptor : OperationInterceptor
{
    readonly IEnumerable&lt;OperationInterceptor&gt; _interceptors;
    public CompositeOperationInterceptor(IDependencyResolver resolver)
    {
        _interceptors = new List&lt;OperationInterceptor&gt; {
            resolver.Resolve(typeof(ValidationInterceptor))
                                     as OperationInterceptor,
            resolver.Resolve(typeof(AuthorizationInterceptor))
                                    as OperationInterceptor
        };
    }
    public override bool BeforeExecute(IOperation operation)
    {
        return _interceptors.All(i =&gt; i.BeforeExecute(operation));
    }
     public override bool AfterExecute(IOperation operation,
                      IEnumerable&lt;OutputMember&gt; outputMembers)
    {
        return _interceptors.All(i =&gt; i.AfterExecute(operation, outputMembers));
    }

}
</pre>
<p>And in your <code>IConfigurationSource</code> you need to hook up your interceptors:</p>
<pre class="prettyprint [lang-csharp]">
ResourceSpace.Uses.
    CustomDependency&lt;ValidationInterceptor, ValidationInterceptor&gt;
                                  (DependencyLifetime.Transient);
ResourceSpace.Uses.
    CustomDependency&lt;AuthorizationInterceptor, AuthorizationInterceptor&gt;
                                  (DependencyLifetime.Transient);
ResourceSpace.Uses
     .CustomDependency&lt;IOperationInterceptor, CompositeOperationInterceptor&gt;
                                  (DependencyLifetime.Transient);
</pre>
<p>Easy <img src='http://danielirvine.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Just on a final note: the exclusion of this feature in OpenRasta is a great example of API design.  It keeps the design simple, minimises the API surface area and yet doesn&#8217;t limit functionality.  Nice.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/06/10/applying-multiple-openrasta-operationinterceptors/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Beautiful errors with OpenRasta</title>
		<link>http://danielirvine.com/blog/2011/06/09/beautiful-errors-with-openrasta/</link>
		<comments>http://danielirvine.com/blog/2011/06/09/beautiful-errors-with-openrasta/#comments</comments>
		<pubDate>Thu, 09 Jun 2011 15:10:35 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[openrasta]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=139</guid>
		<description><![CDATA[<p>Disclaimer: I&#8217;m an OpenRasta newbie so what follows may be completely wrong, but it appears to work for me.</p> <p>Here&#8217;s a common feature of web services: when an error occurs during processing of a server request, the server should return a &#8220;nice&#8221; error message to the client. It goes without saying that the appropriate HTTP [...]]]></description>
			<content:encoded><![CDATA[<p><em>Disclaimer: I&#8217;m an OpenRasta newbie so what follows may be completely wrong, but it appears to work for me.</em></p>
<p>Here&#8217;s a common feature of web services: when an error occurs during processing of a server request, the server should return a <em>&#8220;nice&#8221;</em> error message to the client. It goes without saying that the appropriate HTTP status code (4xx or 5xx) should be set. </p>
<p>A <em>&#8220;nice&#8221;</em> error message in this context means two things.</p>
<ol>
<li>The message is concise, human-readable and useful.</li>
<li>The message contains no sensitive information. In other words, forwarding exceptions and stack traces are out of the question.</li>
</ol>
<p>So how do we do this with OpenRasta?</p>
<p>Let&#8217;s look at a very common example and its solution.  We&#8217;ve got an <code>OperationInterceptor</code> that does some work in its <code>BeforeExecute</code> method.  This work has the potential to throw an exception, at which point the server should hold its hands up and say &#8220;sorry, I&#8217;m borked.&#8221;  In other words we want to return an HTTP 500 Internal Server Error and possibly tell the user exactly what happened.</p>
<pre class="prettyprint [lang-csharp]">
public class MyInterceptor : OperationInterceptor {

  readonly ICommunicationContext _context;

  public MyInterceptor(ICommunicationContext context) {
    _context = context;
  }

  public override bool BeforeExecute(IOperation operation) {

    try {
       // ... do some stuff
    } catch(Exception ex) {

       // log all the gory details to the server log, available
       // only to the system admins
       LogToServerLog(ex);

       // and display a nice message to the user, see below
       // for an example of what this might say
       string description = Strings.UserSafeErrorMessage;

       // todo: how do we return this to OpenRasta?
    }

    return true;

  }
}
</pre>
<p>The key to this problem is the <code>// todo</code> above, which we can fill in the with code below.</p>
<pre class="prettyprint [lang-csharp]">
_context.OperationResult = new OperationResult.InternalServerError
{
    ResponseResource = description;
}
</pre>
<p>This isn&#8217;t enough on its own, however.  OpenRasta looks for a codec that matches the type of the object assigned to <code>ResponseResource</code>, and right now we haven&#8217;t registered a codec for the string type.  Well that&#8217;s simple; we just add the following to our <code>IConfigurationSource</code> implementation:</p>
<pre class="prettyprint [lang-csharp]">
ResourceSpace.Has
  .ResourcesOfType&lt;string&gt;()
  .WithoutUri
  .AsJsonDataContract();
</pre>
<p>Everything should now work, and (depending on how you&#8217;ve defined <code>Strings.UserSafeErrorMessage</code>) your response will be something like:</p>
<pre>
"An exception occurred while attempting to process
the request. The operation will not be allowed. The
server log contains a full exception report. Please
notify the system administrator."
</pre>
<p>Awesome! But: there&#8217;s one more thing. This is probably the minimum amount of code you can get away with to achieve this, but it&#8217;s cheeky of us.  We&#8217;re registering the string type as a resource!  It&#8217;s probably better to create our own error type that will be more useful to all parties:</p>
<pre class="prettyprint [lang-csharp]">
public class ServerError
{
  public string Error { get; set; }
}

_context.OperationResult = new OperationResult.InternalServerError
{
    ResponseResource = new ServerError { Error = description };
}

ResourceSpace.Has
  .ResourcesOfType&lt;ServerError&gt;()
  .WithoutUri
  .AsJsonDataContract();
</pre>
<p>Which will give this output instead:</p>
<pre>
{"Error":"An exception occurred while attempting
 to retrieve authorization information. The operation
 will not be allowed. The server log contains a full
 exception report. Please notify the system
 administrator."}
</pre>
<p>That&#8217;s better.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/06/09/beautiful-errors-with-openrasta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing RESTful services with OpenRasta</title>
		<link>http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/</link>
		<comments>http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/#comments</comments>
		<pubDate>Wed, 08 Jun 2011 09:00:40 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[openrasta]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=106</guid>
		<description><![CDATA[<p>This week I&#8217;ve been spending time learning<a href="http://openrasta.org/"> OpenRasta</a>, a .NET framework that&#8217;s best described as a super-awesome WCF replacement. In fact it kicks WCF&#8217;s butt.</p> <p>OpenRasta helps you write RESTful web services with very little effort. Not just the implementation but your tests too. Unfortunately the testability of OpenRasta-based systems is something of a [...]]]></description>
			<content:encoded><![CDATA[<p>This week I&#8217;ve been spending time learning<a href="http://openrasta.org/"> OpenRasta</a>, a .NET framework that&#8217;s best described as a super-awesome WCF replacement.  In fact it kicks WCF&#8217;s butt.</p>
<p>OpenRasta helps you write RESTful web services with very little effort.  Not just the implementation but your tests too. Unfortunately the testability of OpenRasta-based systems is something of a mystery to beginners like myself, since the test API documentation is non-existent. What follows is how I&#8217;ve started out with building my tests.</p>
<p>Assume you&#8217;ve got three classes ready to go: </p>
<ul>
<li>a <code>MyResource</code> type, which is your business object</li>
<li>a <code>MyResourceHandler</code>, for handling requests to the <code>MyResource</code> resource</li>
<li>a <code>Configuration</code> class for initializing OpenRasta.</li>
</ul>
<p>Normally you&#8217;ll also have an ASP.NET project that hosts OpenRasta and your functionality within IIS.  That&#8217;s what happens at runtime.  But for the purposes of testing, you can also host OpenRasta &#8220;in memory&#8221; without requiring the instantiation of IIS and without the use of &#8220;real-life&#8221; network resources.  You can programmatically fire requests at the in-memory host using a very simple API.  Here&#8217;s what a barebones test looks like:</p>
<pre class="prettyprint [lang-csharp]">
using(var host = new InMemoryHost(new Configuration()))
{
  var request = new InMemoryRequest()
    {
      Uri = new Uri("http://localhost/MyResource"),
      HttpMethod = "GET"
    };

  // set up your code formats - I'm using
  // JSON because it's awesome
  request.Entity.ContentType = MediaType.Json;
  request.Entity.Headers["Accept"] = "application/json";

  // send the request and save the resulting response
  var response = host.ProcessRequest(request);
  int statusCode = response.StatusCode;

  // deserialize the content from the response
  MyResource returnedObject;
  if(response.Entity.ContentLength &gt; 0)
  {
    // you must rewind the stream, as OpenRasta
    // won't do this for you
    response.Entity.Stream.Seek(0, SeekOrigin.Begin);

    var serializer =
        new DataContractJsonSerializer(typeof(MyResource));
    returnedObject = serializer.ReadObject(response.Entity.Stream);
  }
 }
</pre>
<p>And that&#8217;s all there is to it &#8211; for a GET operation.  If you&#8217;re doing a POST, you&#8217;ll need to make sure you populate the entity&#8217;s <code>Stream</code> and <code>ContentLength</code> properties.</p>
<pre class="prettyprint [lang-csharp]">
var serializer = new DataContractJsonSerializer(typeof(MyResource));
serializer.WriteObject(Request.Entity.Stream, content);
request.Entity.Stream.Seek(0, SeekOrigin.Begin);
request.Entity.ContentLength = Request.Entity.Stream.Length;
</pre>
<p>In my own tests I don&#8217;t have code that looks exactly like this &#8211; I&#8217;ve factored it nicely into reusable methods that belong in my test context, and that work across multiple resource types.  For example to set up my request I can write</p>
<pre class="prettyprint [lang-csharp]">
  given_new_request&lt;AnotherResource&gt;(
     "PUT",
     "AnotherResource",
     anotherResource);
</pre>
<p>One final, important point. If you&#8217;ve designed your classes well, you should be relying on unit tests that do not require OpenRasta to be instantiated at all.  Your OpenRasta tests should exist only as end-to-end integration tests and should focus on sending a variety of requests, testing the responses plus any side effects.  You should send across a variety of both well-formed and malformed HTTP requests, using the tests to ensure that you stick to REST principles.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Viewing your OpenWrap dependencies from Visual Studio</title>
		<link>http://danielirvine.com/blog/2011/05/25/viewing-your-openwrap-dependencies-from-visual-studio/</link>
		<comments>http://danielirvine.com/blog/2011/05/25/viewing-your-openwrap-dependencies-from-visual-studio/#comments</comments>
		<pubDate>Wed, 25 May 2011 22:12:30 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[openwrap]]></category>

		<guid isPermaLink="false">http://danielirvine.com/?p=99</guid>
		<description><![CDATA[<p>Just a quick tip for all OpenWrap users: you can view your resolved assemblies from inside Visual Studio using Class View (Ctrl+Shift+C).</p> <p></p> <p>I&#8217;ve always preferred the Solution Explorer and so I missed this little trick until recently, coming across it by chance. It&#8217;s a great way to check that you&#8217;re not accidentally referencing too [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick tip for all OpenWrap users: you can view your resolved assemblies from inside Visual Studio using Class View (Ctrl+Shift+C).</p>
<p><img src="http://danielirvine.com/wp-content/uploads/2011/05/classview.png" alt="" title="OpenWrap resolved assemblies in Class View" width="276" height="348" class="aligncenter size-full wp-image-103" /></p>
<p>I&#8217;ve always preferred the Solution Explorer and so I missed this little trick until recently, coming across it by chance.  It&#8217;s a great way to check that you&#8217;re not accidentally referencing too much.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/05/25/viewing-your-openwrap-dependencies-from-visual-studio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entering a new world&#8230;</title>
		<link>http://danielirvine.com/blog/2011/01/31/entering-a-new-world/</link>
		<comments>http://danielirvine.com/blog/2011/01/31/entering-a-new-world/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 21:47:48 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[cycling]]></category>
		<category><![CDATA[personal]]></category>

		<guid isPermaLink="false">http://danielirvine.com/blog/?p=82</guid>
		<description><![CDATA[<p>After a long wait, my <a href="www.cyclescheme.co.uk">Cyclescheme</a> voucher finally arrived in my postbox. I marched into the nearest bicycle shop and purchased a <a href="http://www.thebikelist.co.uk/giant/defy-2-2009">Giant Defy 2 (2009-2010 Model)</a> plus helmet, D-Lock, cycling cap and lights for the princely sum of £700. The bike is an &#8220;old&#8221; model&#8211;old in the sense that there&#8217;s a new [...]]]></description>
			<content:encoded><![CDATA[<p>After a long wait, my <a href="www.cyclescheme.co.uk">Cyclescheme</a> voucher finally arrived in my postbox. I marched into the nearest bicycle shop and purchased a <a href="http://www.thebikelist.co.uk/giant/defy-2-2009">Giant Defy 2 (2009-2010 Model)</a> plus helmet, D-Lock, cycling cap and lights for the princely sum of £700. The bike is an &#8220;old&#8221; model&#8211;old in the sense that there&#8217;s a new 2010-2011 version available&#8211;but I have a hunch that these contraptions are like razors: any innovations these days are minutely incremental in nature.  So for a bike with an RRP of £775, I saved a fair few pennies.</p>
<p>From now on I&#8217;ll be cycling to work and I&#8217;ll be blogging about my travels in and around London.  Before long I&#8217;ll probably head further afield too.</p>
<p>Now I&#8217;m a proud cyclist, no longer at the mercy of London&#8217;s temperamental tube network.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/01/31/entering-a-new-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Button.IsDefault on Silverlight</title>
		<link>http://danielirvine.com/blog/2011/01/29/button-isdefault-on-silverlight/</link>
		<comments>http://danielirvine.com/blog/2011/01/29/button-isdefault-on-silverlight/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 16:31:07 +0000</pubDate>
		<dc:creator>daniel</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://danielirvine.com/blog/?p=77</guid>
		<description><![CDATA[<p>If you&#8217;re like me, you spend a lot of time chastising UI developers for not following standard UI guidelines, like the one which says dialog boxes should have a default button.</p> <p>Unfortunately, the Silverlight team at Microsoft seemingly don&#8217;t know about that. Yes, shockingly, Button.IsDefault does not exist in Silverlight.</p> <p>If you get stuck because [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re like me, you spend a lot of time chastising UI developers for not following standard UI guidelines, like the one which says dialog boxes should have a default button.</p>
<p>Unfortunately, the Silverlight team at Microsoft seemingly don&#8217;t know about that. Yes, shockingly, Button.IsDefault does not exist in Silverlight.</p>
<p>If you get stuck because of this, an attached property will sort you out, as usual.  Here&#8217;s a related discussion and some sample code:</p>
<p><a href="http://stackoverflow.com/questions/2683891/silverlight-4-default-button-service">http://stackoverflow.com/questions/2683891/silverlight-4-default-button-service</a></p>
<p>Attached properties really are the unsung heroes of the WPF/Silverlight platform.</p>
]]></content:encoded>
			<wfw:commentRss>http://danielirvine.com/blog/2011/01/29/button-isdefault-on-silverlight/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

