tag:blogger.com,1999:blog-9903937020299997542022-11-09T11:36:44.157+00:00being newself improvement in .netJustin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.comBlogger97125tag:blogger.com,1999:blog-990393702029999754.post-62065991823656718692012-03-01T07:50:00.000+00:002012-03-06T09:21:56.571+00:00How I limit my abstractions in fubuMVC<p>In my <a href="http://www.beingnew.net/2012/02/seeing-light-about-abstractions.html">previous post</a> I discussed my own design of Controller Messages that I had previously used in ASP.NET MVC to force single responsibility principles and to ensure that I didn’t have any <a href="http://codebetter.com/iancooper/2008/12/03/the-fat-controller/">fat controllers</a>.</p> <p>My conclusion from that post was that I <strong>no longer need these handler abstractions now that I am using fubuMVC</strong> and I’ll attempt to illustrate what I pinched from the post that started all this thought process, namely <a href="http://ayende.com/blog/154273/limit-your-abstractions-and-how-do-you-handle-testing">Limit your abstractions: And how do you handle testing?</a></p> <p>That post shows the provision of Commands and Queries on the controller to do away with unnecessary abstractions, and it occurred to me that the fubuMVC action is itself essentially a command, one of a series of behaviours/nodes that executes in a Russian doll model – I therefore can do away with the handler abstraction and treat the fubuMVC action/controller as a command. <br />All I need to do it provide the query mechanism on a base controller:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> ControllerWithASession
{
<span class="kwrd">protected</span> ISession Session
{
get { <span class="kwrd">return</span> SessionProvider(); }
}
<span class="kwrd">public</span> Func<ISession> SessionProvider { get; set; }
<span class="kwrd">protected</span> T Query<T>(Query<T> query)
{
<span class="kwrd">if</span> (AlternativeQueriesToRun.Any())
<span class="kwrd">return</span> RunAlternativeQuery(query);
query.Session = Session;
<span class="kwrd">return</span> query.Execute();
}
T RunAlternativeQuery<T>(Query<T> query)
{
var alternate = AlternativeQueriesToRun.Where(q =>
q.GetType().IsAssignableFrom(<span class="kwrd">typeof</span>(Func<Query<T>, T>)))
.FirstOrDefault();
<span class="kwrd">if</span> (alternate == <span class="kwrd">null</span>)
<span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="kwrd">string</span>.Format(<span class="str">"Alternative queries were set up,
but there was one missing for: {0}"</span>, query.GetType().Name));
<span class="kwrd">return</span> (alternate <span class="kwrd">as</span> Func<Query<T>, T>).Invoke(query);
}
List<<span class="kwrd">object</span>> AlternativeQueriesToRun = <span class="kwrd">new</span> List<<span class="kwrd">object</span>>();
<span class="kwrd">public</span> <span class="kwrd">void</span> AddAlternativeQueryToRun(<span class="kwrd">object</span> alternativeQuery)
{
AlternativeQueriesToRun.Add(alternativeQuery);
}
}</pre>
</div>
<p>This new protected method Query<T> can run a query, but first checks if any alternatives have been set up – in my tests I’m therefore free to provide different implementations without the need for mocking an IRepository, IDataObtainer or other needless abstraction.
<br />It also ensures that if any alternatives have been provided an exception is thrown if you don’t provide every query in the test.</p>
<p>The queries are concrete implementations of a generic abstraction:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> AssignmentPendingApprovalQuery : Query<AssignmentPendingApproval>
{
<span class="kwrd">readonly</span> <span class="kwrd">int</span> _userId;
<span class="kwrd">public</span> AssignmentPendingApprovalQuery(<span class="kwrd">int</span> userId)
{
_userId = userId;
}
<span class="kwrd">public</span> <span class="kwrd">override</span> AssignmentPendingApproval Execute()
{
<span class="kwrd">return</span> <span class="rem">//implementation here;</span>
}
}
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> Query<T>
{
<span class="kwrd">public</span> ISession Session { get; set; }
<span class="kwrd">public</span> <span class="kwrd">abstract</span> T Execute();
}</pre>
</div>
<p>So with all that set up, I can now write tests like this:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(PostLoginDeciderController))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_deciding_what_to_do_after_login_and_the_user_has_no_approved_request_
and_no_assignment_approvals : TestingAController
{
Establish context = () =>
{
_user = User.ForId(8);
_theRequestsCurrentUser = <span class="kwrd">new</span> TheRequestsCurrentUser {User = _user};
_postLoginDeciderController = WithASession(<span class="kwrd">new</span> PostLoginDeciderController());
SetupQuery<RegistrationPendingApproval>(query => <span class="kwrd">null</span>);
SetupQuery<AssignmentPendingApproval>(query => <span class="kwrd">null</span>);
};
Because of = () => _continuation =
_postLoginDeciderController.DecideWhereToGoAfterLogin(_theRequestsCurrentUser);
It should_redirect_the_user_to_the_second_step_of_registration = () =>
_continuation.AssertWasRedirectedTo<RegistrationController>(r => r.StepTwo());
<span class="kwrd">static</span> PostLoginDeciderController _postLoginDeciderController;
<span class="kwrd">static</span> FubuContinuation _continuation;
}</pre>
</div>
<p>The WithASession method on the base test class ensures that the controller is set up with a mocked session and I have the ability to set up queries, here explicitly returning null for both queries because a registration process is not complete.</p>
<p>Here is the base test class:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> TestingAController
{
<span class="kwrd">protected</span> <span class="kwrd">static</span> Mock<ISession> Session { get; set; }
<span class="kwrd">protected</span> <span class="kwrd">static</span> ControllerWithASession CurrentController { get; set; }
<span class="kwrd">protected</span> <span class="kwrd">static</span> T WithASession<T>(T controller) <span class="kwrd">where</span> T : ControllerWithASession
{
CurrentController = controller;
Session = <span class="kwrd">new</span> Mock<ISession>();
controller.SessionProvider = () => Session.Object;
<span class="kwrd">return</span> controller;
}
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetupQuery<T>(Func<Query<T>, T> alternativeQuery)
{
CurrentController.AddAlternativeQueryToRun(alternativeQuery);
}
}</pre>
</div>
<p>Having reworked a number of controller/actions to use this, I have removed a fair few abstractions I was previously using.
<br />And the code makes more sense as a whole and in its individual pieces.</p>
<p>My own lesson learnt is : <strong>Don’t default all your single responsibility interactions to work through abstractions.</strong></p>
<p>To wrap it up, here is what the fubuMVC action/controller looks like with this new set up:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PostLoginDeciderController : ControllerWithASession
{
<span class="kwrd">public</span> FubuContinuation DecideWhereToGoAfterLogin(TheRequestsCurrentUser theRequestsCurrentUser)
{
var registrationPendingApproval =
Query(<span class="kwrd">new</span> NewRegistrationPendingApprovalQuery(theRequestsCurrentUser.User.Id));
<span class="kwrd">if</span> registrationPendingApproval != <span class="kwrd">null</span>)
<span class="kwrd">return</span> FubuContinuation.RedirectTo<PendingRegistrationController>(r =>
r.PendingRegistrationApproval(theRequestsCurrentUser));
var assignmentPendingApproval =
Query(<span class="kwrd">new</span> AssignmentPendingApprovalQuery(theRequestsCurrentUser.User.Id));
<span class="kwrd">if</span> (assignmentPendingApproval != <span class="kwrd">null</span>)
<span class="kwrd">return</span> FubuContinuation.RedirectTo<PendingRegistrationController>(r =>
r.PendingAssignmentApproval(theRequestsCurrentUser));
<span class="kwrd">return</span> FubuContinuation.RedirectTo<RegistrationController>(r => r.StepTwo());
}
}</pre>
</div>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com5tag:blogger.com,1999:blog-990393702029999754.post-81588958207560221862012-02-27T18:51:00.000+00:002012-03-06T09:21:42.733+00:00seeing the light about abstractions<p>What a fantastic post this is: <a href="http://ayende.com/blog/154273/limit-your-abstractions-and-how-do-you-handle-testing">Limit your abstractions: And how do you handle testing?</a></p> <p>I’m big enough to hold my hands up and say that I have often fallen foul of the needless abstraction. <br />To some extent, I did realise this when redesigning my site to work with fubuMVC –previously I had encapsulated logic in something I called controller messaging for some time (and had planned to blog about but never got around to it). </p> <p>The original version was in an ASP.NET MVC controller and was used in a similar vein to domain events:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ReportController : AuthorisedController
{
<span class="kwrd">public</span> ActionResult Create(<span class="kwrd">int</span> id)
{
var reportTreeData = ControllerMessage.Initiate<NewReportToBeCreated, ReportTreeData>
(<span class="kwrd">new</span> NewReportToBeCreated() {ReportTemplateId = 1, PupilId = id});
<span class="kwrd">return</span> View(reportTreeData);
}
}</pre>
</div>
<p>When I came to do my fubuMVC implementation I thought there was a code smell about having almost exactly the same construct as domain events, but for controllers to hook into domain logic.
<br />So instead I wanted it baked into the actions on fubuMVC - the actions/controllers in my fubuMVC application derive from a base that has an invoker:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ControllerThatCanInvoke
{
<span class="kwrd">public</span> <span class="kwrd">static</span> ControllerMessageInvoker Invoker { get; set; }
<span class="kwrd">protected</span> TResult Invoke<T, TResult>(T item)
{
<span class="kwrd">return</span> Invoker.Invoke<T, TResult>(item);
}
}</pre>
</div>
<p>It has a static invoker that is set up at the bootstrapping stage and the invoke call is delegated to the invoker.</p>
<p>The invoker comes from the IOC container and this is injected with handlers:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ControllerMessageInvoker
{
<span class="kwrd">readonly</span> IEnumerable<IHandle> _handlers;
<span class="kwrd">public</span> ControllerMessageInvoker(IEnumerable<IHandle> handlers)
{
_handlers = handlers;
}
<span class="kwrd">public</span> TResult Invoke<T, TResult>(T item)
{
<span class="kwrd">return</span> _handlers.OfType<IHandle<T, TResult>>().Single().Handle(item);
}
}</pre>
</div>
<p>With the handler interfaces:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IHandle<T, TResult> : IHandle
{
TResult Handle<T>(T item);
}
<span class="kwrd">public</span> <span class="kwrd">interface</span> IHandle { }</pre>
</div>
<p>So this enables me to invoke straight from my controller :</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ReportController : ControllerThatCanInvoke
{
<span class="kwrd">public</span> CreateReportViewModel Create(CreateReportInput input)
{
var reportTreeData =
Invoke<NewReportToBeCreated, ReportTreeData>(<span class="kwrd">new</span> NewReportToBeCreated
{
ABC = input.MMM,
XYZ = input.Id
});
<span class="kwrd">return</span> <span class="kwrd">new</span> CreateReportViewModel(reportTreeData);
}
}</pre>
</div>
<p>This allows me to test that the controller initiates the invocation and with the right inputs on a POCO class and I can test the handler independently.
<br />What that obviously means is I need a handler that answers to the invocation:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> NewReportToBeCreatedHandler : IHandle<NewReportToBeCreated, ReportTreeData>
{
<span class="kwrd">public</span> ReportTreeData Handle<T>(T item)
{
DoSomething();
<span class="kwrd">return</span> xxxx;
}
}</pre>
</div>
<p>This works well, I have separation of concerns, this handler comes from the IOC container and can have session and other dependencies injected, and I've been rolling along very happy with myself until I read the blog post I referred to.</p>
<p>It poses a question:<strong><em> Do I really need this IHandler<T,TResult> abstraction?</em></strong></p>
<p>The only friction I have at the moment is that I need two POCO classes and a handler class for every action that requires this invocation style. It ends up being a lot of classes.
<br />I’ve managed it so far with some good folder and namespace arrangement, but I now see the light:</p>
<p><strong>I do not need this abstraction and its trappings at all. </strong></p>
<p>It is a concept I carried over from an ASP.NET MVC implementation and I just don’t need it.
<br />So I’m in the process of reworking / stealing the ideas from Oren’s post and I’ll put up how I’ve reconsidered this for fubuMVC in my next post.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-61985871589396254072012-02-24T08:46:00.001+00:002012-02-24T16:19:37.163+00:00How I use domain events with fubuMVC part two<p>In my <a href="http://www.beingnew.net/2012/02/how-i-use-domain-events-with.html">previous post</a> I illustrated how I use domain events and enable a pre-commit  and post-commit behaviour on one handler interface. <br />Here I’m going to illustrate how to plug this into the fubuMVC framework.</p> <p>In <a href="http://www.beingnew.net/2011/09/how-i-use-nhibernate-with-fubumvc.html">another previous post</a> I showed how an NHibernate simple unit of work can be used in fubuMVC with a dedicated behaviour and now I want to extend that behaviour so that is processes the post-commit actions. Here’s the invoke method of that behaviour:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">void</span> Invoke()
{
_fubuRequest.Set(<span class="kwrd">new</span> Lazy<ISession>(() => _session ??
(_session = CreateTransactionalSession())));
<span class="kwrd">try</span>
{
InnerBehavior.Invoke();
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Transaction.Commit();
}
<span class="kwrd">catch</span> (Exception)
{
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Transaction.Rollback();
<span class="kwrd">throw</span>;
}
<span class="kwrd">finally</span>
{
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Dispose();
}
ProcessAfterEventConfirmationActions();
}</pre>
</div>
<p>This is the existing Invoke code with an extra method added on at the end to process these "after event confirmation" actions. Here's the implementation of that:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">void</span> ProcessAfterEventConfirmationActions()
{
var actions = _fubuRequest.Get<List<AfterEventConfirmationAction>>();
<span class="kwrd">if</span> (actions == <span class="kwrd">null</span>)
<span class="kwrd">return</span>;
actions.ForEach(action => action());
}</pre>
</div>
<p>Pretty simple stuff - it cycles through the list of after event confirmation actions that it has obtained from the current fubu request. If isolated error handling is required, it should be contained within the action itself.</p>
<p>The next step is to plug this into the domain events processor, but I have a problem. My domain event processor that I showed in my last post is obtained from the static provider delegate:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents
{
<span class="kwrd">static</span> Func<IProcessDomainEvents> _domainEventProcessorProvider;
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetDomainEventProcessorProvider(Func<IProcessDomainEvents>
domainEventProcessorProvider)
{
_domainEventProcessorProvider = domainEventProcessorProvider;
}
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Raise<TEvent>(TEvent domainEvent) <span class="kwrd">where</span> TEvent : IDomainEvent
{
var domainEventProcessor = _domainEventProcessorProvider();
domainEventProcessor.ProcessEvent(domainEvent);
}
}</pre>
</div>
<p>...and this is declared at the bottom of my HttpApplication : </p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Global : HttpApplication
{
Container _applicationsContainer;
IProcessDomainEvents _domainEventsProcessor;
<span class="kwrd">protected</span> <span class="kwrd">void</span> Application_Start(<span class="kwrd">object</span> sender, EventArgs e)
{
FubuApplication
.For<XercesFubuRegistry>()
.StructureMap(() =>
{
var container = <span class="kwrd">new</span> Container(<span class="kwrd">new</span> ContainerConfigurer().Configuration);
_applicationsContainer = container;
<span class="kwrd">return</span> container;
})
.Bootstrap(RouteTable.Routes);
DomainEvents.SetDomainEventProcessorProvider(DomainEventsProcessor);
}
<span class="kwrd">private</span> IProcessDomainEvents DomainEventsProcessor()
{
<span class="kwrd">return</span> _domainEventsProcessor ??
(_domainEventsProcessor = _applicationsContainer.GetInstance<IProcessDomainEvents>());
}
}</pre>
</div>
<p>Because the processor is obtained from the root container, any fubu request it receives will <strong>not be the one from the nested container of the current request</strong>.
<br />I therefore need to build myself a simple bridge between the two:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IFubuRequestBridge
{
<span class="kwrd">void</span> StoreRequest(IFubuRequest fubuRequest);
IFubuRequest ObtainRequest();
}
<span class="kwrd">public</span> <span class="kwrd">class</span> FubuRequestBridge : IFubuRequestBridge
{
<span class="kwrd">public</span> <span class="kwrd">const</span> <span class="kwrd">string</span> FubuRequestKey = <span class="str">"XERCES_FUBUREQUEST"</span>;
<span class="kwrd">public</span> <span class="kwrd">void</span> StoreRequest(IFubuRequest fubuRequest)
{
HttpContext.Current.Items[FubuRequestKey] = fubuRequest;
}
<span class="kwrd">public</span> IFubuRequest ObtainRequest()
{
<span class="kwrd">return</span> HttpContext.Current.Items[FubuRequestKey] <span class="kwrd">as</span> IFubuRequest;
}
}</pre>
</div>
<p>This fubu request bridge can store and provide the current request and simply places it in the current http context.</p>
<p>The storing of the request is performed using a behaviour dedicated to doing only that:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventsBehaviour : BasicBehavior
{
<span class="kwrd">readonly</span> IFubuRequest _fubuRequest;
<span class="kwrd">readonly</span> IFubuRequestBridge _fubuRequestBridge;
<span class="kwrd">public</span> DomainEventsBehaviour(IFubuRequest fubuRequest, IFubuRequestBridge fubuRequestBridge)
: <span class="kwrd">base</span>(PartialBehavior.Ignored)
{
_fubuRequest = fubuRequest;
_fubuRequestBridge = fubuRequestBridge;
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> DoNext performInvoke()
{
_fubuRequestBridge.StoreRequest(_fubuRequest);
<span class="kwrd">return</span> DoNext.Continue;
}
}</pre>
</div>
<p>Injected with the current fubu request and the bridge, it stores the fuburequest before invoking the next behaviour.
<br />I put this in the fubu registry before the simple unit of work one:</p>
<div class="codeBlock">
<pre class="csharpcode"> ApplyConvention<PermanentRedirectionConvention>();
ApplyConvention<WrapAllConvention<DomainEventsBehaviour>>();
ApplyConvention<WrapAllConvention<SimpleUnitOfWorkBehaviour>>();
ApplyConvention<AuthenticationConvention>();</pre>
</div>
<p>So now I can change my domain event processor to be injected with the bridge – to store the post event confirmation actions it simply retrieves the appropriate fubu request and places them in a list:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventProcessor : IProcessDomainEvents
{
<span class="kwrd">readonly</span> IEnumerable<IHandleDomainEvents> _domainEventHandlers;
<span class="kwrd">readonly</span> IFubuRequestBridge _fubuRequestBridge;
<span class="kwrd">public</span> DomainEventProcessor(IEnumerable<IHandleDomainEvents> domainEventHandlers,
IFubuRequestBridge fubuRequestBridge)
{
_domainEventHandlers = domainEventHandlers;
_fubuRequestBridge = fubuRequestBridge;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> ProcessEvent<T>(T domainEvent) <span class="kwrd">where</span> T : IDomainEvent
{
_domainEventHandlers.OfType<IHandleDomainEvent<T>>()
.ForEach(handler => HandleTheDomainEvent(domainEvent, handler));
}
<span class="kwrd">void</span> HandleTheDomainEvent<T>(T domainEvent, IHandleDomainEvent<T> handler)
<span class="kwrd">where</span> T : IDomainEvent
{
var afterEventConfirmationAction = handler.Handle(domainEvent);
var fubuRequest = _fubuRequestBridge.ObtainRequest();
var currentAfterEventConfirmationActions =
fubuRequest.Get<List<AfterEventConfirmationAction>>();
currentAfterEventConfirmationActions.Add(afterEventConfirmationAction);
}
}</pre>
</div>
<p>And that’s it!
<br />A lot of code in this post, but essentially a working domain events implementation in fubuMVC that does processing within a transaction and post confirmation actions after the committal.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-45917303717309675842012-02-22T06:49:00.003+00:002012-02-24T16:20:26.664+00:00How I use domain events with fubuMVC–part one<p>My fubuMVC series is back and with an interesting one hopefully – how I use domain events and work it into my fubuMVC application. <br />To illustrate this I’m going to use the registration process as a prime example of domain events in action within an application.</p> <p>When a user registers, I want to create a new user who is persisted to the database and a confirmation email sent to the user. <br />Using domain events for this I want the UserCreated event to signal that the user needs persisting so that this is loosely coupled but I only want the email sent if the entire previous transaction was successful.</p> <p>So I’m going to start with an event that has an empty marker interface IDomainEvent:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> UserCreated : IDomainEvent
{
<span class="kwrd">public</span> UserCreated(User user)
{
User = user;
}
<span class="kwrd">public</span> User User { get; <span class="kwrd">private</span> set; }
}</pre>
</div>
<p>In order to handle this event, I’m going to create a domain event handler abstraction:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IHandleDomainEvents { }
<span class="kwrd">public</span> <span class="kwrd">interface</span> IHandleDomainEvent<T> : IHandleDomainEvents
{
AfterEventConfirmationAction Handle(T domainEvent);
}
<span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> AfterEventConfirmationAction();</pre>
</div>
<p>This interface can handle a domain event T and has the option of returning an action that will happen once the <strong>event has been confirmed</strong> (i.e. transaction is complete).
<br />I chose a strong delegate as opposed to Action so that is has a recognisable name throughout the code. Here are two pseudo implementations from the registration example:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PersistTheCreatedUserHandler : IHandleDomainEvent<UserCreated>
{
<span class="kwrd">public</span> AfterEventConfirmationAction Handle(UserCreated domainEvent)
{
<span class="rem">// persist the user</span>
session.Save(user);
<span class="kwrd">return</span> Do.Nothing();
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> EmailForTheCreatedUserHandler : IHandleDomainEvent<UserCreated>
{
<span class="kwrd">public</span> AfterEventConfirmationAction Handle(UserCreated domainEvent)
{
<span class="kwrd">return</span> () => SendEmail();
}
}</pre>
</div>
<p>The difference between the two is that the persistence will happen within a transaction, yet the send email will occur only once all events have been confirmed.</p>
<p>Now onto the domain events processor – I want it injected with all the available handlers so that it can cycle through the appropriate ones and ask them to handle the event:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventProcessor : IProcessDomainEvents
{
<span class="kwrd">readonly</span> IEnumerable<IHandleDomainEvents> _domainEventHandlers;
<span class="kwrd">readonly</span> List<AfterEventConfirmationAction> _temporaryHolderForAfterEventConfirmationActions =
<span class="kwrd">new</span> List<AfterEventConfirmationAction>();
<span class="kwrd">public</span> DomainEventProcessor(IEnumerable<IHandleDomainEvents> domainEventHandlers)
{
_domainEventHandlers = domainEventHandlers;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> ProcessEvent<T>(T domainEvent) <span class="kwrd">where</span> T : IDomainEvent
{
_domainEventHandlers.OfType<IHandleDomainEvent<T>>()
.ForEach(handler => HandleTheDomainEvent(domainEvent, handler));
}
<span class="kwrd">void</span> HandleTheDomainEvent<T>(T domainEvent, IHandleDomainEvent<T> handler) <span class="kwrd">where</span> T : IDomainEvent
{
var afterEventConfirmationAction = handler.Handle(domainEvent);
_temporaryHolderForAfterEventConfirmationActions.Add(afterEventConfirmationAction);
}
}</pre>
</div>
<p>The processor ensures the domain events get handled and I don't have error handling to ensure all are fired, I personally let the error roll up and fail the entire transaction.
<br />Temporarily I’m storing the event confirmation actions and doing nothing with them – the next post will illustrate how I hook this into fubuMVC.</p>
<p>The final piece is an easy way for domain objects to raise events:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents
{
<span class="kwrd">static</span> Func<IProcessDomainEvents> _domainEventProcessorProvider;
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetDomainEventProcessorProvider(Func<IProcessDomainEvents>
domainEventProcessorProvider)
{
_domainEventProcessorProvider = domainEventProcessorProvider;
}
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Raise<TEvent>(TEvent domainEvent) <span class="kwrd">where</span> TEvent : IDomainEvent
{
var domainEventProcessor = _domainEventProcessorProvider();
domainEventProcessor.ProcessEvent(domainEvent);
}
}</pre>
</div>
<p>I do not like implementations in my static classes and methods, rather they delegate out as this one does using a static provider/factory to obtain the processor to use. Here's an example of this static in use:</p>
<div class="codeBlock">
<pre class="csharpcode"> DomainEvents.Raise(<span class="kwrd">new</span> UserCreated(user));</pre>
</div>
<p>In the next part I’ll show how these get hooked into the fubuMVC request and interact with my unit of work behaviour.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-59228666361874047362012-02-16T07:53:00.001+00:002012-02-16T07:53:58.823+00:00on behavioural testing<p>I’m back after a long spell away from blogging, having settled into a new work position and having had a few personal code retreats I recently talked about.</p> <p>In that time I wanted to explore what it means to unit test and acceptance test and came to a few conclusions that I wanted to share.</p> <h1>Test driven development</h1> <p>Years back when I first started test driven development it was a revelation – the control it gave you over your own code, the confidence in what you were delivering was amazing. I started with stubs, test spies and all kinds of funky hand rolled stuff, but soon found that mocking frameworks enabled you to gain stubs for free using their proxies. This is when the testing began to naturally morph into interaction testing – by testing the relationships between single responsibility objects I had full control over my code and could edge case everything.</p> <p>This is where I think a lot of people get to, having read debates about state vs. behavioural testing and a few blogs where great developers admit that “I made a mistake and got too involved in interaction testing”. <br />Some of us who have been through this recognise the brittle unit tests that come with behavioural unit testing, however it is not black and white that this brittleness is a bad thing.</p> <p>I specialise in helping teams become more agile and teach test driven development, and more often than not the environment that I enter is one where unit testing gets done, but test driven does not. And there are only 150 tests on a huge code base. <br />I find that a natural fit for the developers who want to get started on TDD with this code base, which is often huge classes with mangled responsibilities and little dependency injection, is to go with the tried and tested way of pulling out single responsibility behaviour using a test driven practice and moving the code out piece by piece, introducing dependency injection and abstractions where appropriate. <br />This then naturally encourages behavioural interaction using mocking frameworks for stubs because they want to ensure that these new SRP pieces speak to each other in the right way and that less TDD thinking developers don’t rip it out. <br />They embrace potentially brittle tests with the knowledge that they might need changing or reworking in the future in exchange for a higher level of confidence that the behaviour of our code is correct. More importantly their code base becomes testable. <br />Provided this is a conscious decision, I think it can have great benefits.</p> <h1>Acceptance test development</h1> <p>In an ideal world, we would start a clean project with acceptance testing up front, or rather <a href="http://specificationbyexample.com/key_ideas.html">Specifications By Example</a>. By driving features that examine how and what the product owner/customer sees in our application we can free ourselves up from a lot of the internal behavioural testing. We potentially then unit test where there is complexity or edge cases and let the acceptance tests cover the rest when we want to.</p> <p>I’m working on a project at the moment that falls somewhere between the two – there are unit tests, we are introducing dependency injection and splitting responsibilities, yet we already recognise the value of acceptance tests. More importantly, this end to end feature testing is very possible with some internal changes to the code and some abstractions. These higher level tests will free us from the test per class restraint we often find ourselves in while test driving a legacy code base.</p> <p>To conclude I think that test per class and behavioural testing is not a bad thing at all, just that if you can there are better ways to reduce brittleness and test rework.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-56465634944428882762011-12-02T11:17:00.001+00:002011-12-02T11:17:50.011+00:00My first personal code retreat<p>To tie in with the <a href="http://coderetreat.org/">Global Day of Code Retreat</a>, I’m doing some personal retreating so that I can practice and hopefully learn some new things. There is a great <a href="http://vimeo.com/18955165">intro video</a> referred by the code retreat site that gives an introduction to what it is all about – in essence “perfect practice makes perfect”. <br />Rather than trying to solve a whole problem, just code as perfect as you can for a short period of time.</p> <p>So I’ll be coding for 45 minutes recording what I’ve learnt and then in the spirit of the code retreat, deleting the code (although it will be on my blog). Repeat again same day, or another day. Each time I’ll try and learn something new.</p> <p>The Conway game of life is used for a code retreat and the rules are summarised from the <a href="http://coderetreat.com/gol.html">code retreat page</a> as:</p> <blockquote> <p>The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. <br />Every cell interacts with its eight neighbours, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur: </p> <p>Any live cell with fewer than two live neighbours dies, as if caused by under-population. <br />Any live cell with more than three live neighbours dies, as if by overcrowding. <br />Any live cell with two or three live neighbours lives on to the next generation. <br />Any dead cell with exactly three live neighbours becomes a live cell.</p> </blockquote> <p>So here goes with pure test driven development in context specification style as my first code retreat.</p> <p>(an hour later)…</p> <p>Because I’m using my usual context specification test driven style, I found it very easy to define my tests in the language of the rules themselves. This ensures there are no ambiguities and I’m writing my tests with the domain in mind. <br />This is, for me, why context specification is such a useful development tool. </p> <p>I started with one test:</p> <div class="codeBlock"> <pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_an_alive_cell_has_two_alive_neighbours
{
Establish context = () =>
{
_liveNeighbour = <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>);
_secondLiveNeighbour = <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>);
_neighbours = <span class="kwrd">new</span> List<Cell> {_liveNeighbour, _secondLiveNeighbour};
_cell = <span class="kwrd">new</span> Cell(State.Alive, _neighbours);
};
Because of = () => _stateForNextGeneration = _cell.IdentifyStateForTheNextGeneration();
It should_live_on_to_the_next_generation = () =>
_stateForNextGeneration.ShouldEqual(State.Alive);
<span class="kwrd">static</span> Cell _cell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> Cell _liveNeighbour;
<span class="kwrd">static</span> Cell _secondLiveNeighbour;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>This produced the simplest implementation possible to make this test pass:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">enum</span> State
{
Alive,
Dead
}
<span class="kwrd">public</span> <span class="kwrd">class</span> Cell
{
<span class="kwrd">public</span> Cell(State state, IEnumerable<Cell> neighbours)
{
}
<span class="kwrd">public</span> State IdentifyStateForTheNextGeneration()
{
<span class="kwrd">return</span> State.Alive;
}
}</pre>
</div>
<p>Then I moved on to some more tests that would shape the development:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_an_alive_cell_has_one_alive_neighbour
{
Establish context = () =>
{
_liveNeighbour = <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>);
_neighbours = <span class="kwrd">new</span> List<Cell> { _liveNeighbour };
_cell = <span class="kwrd">new</span> Cell(State.Alive, _neighbours);
};
Because of = () => _stateForNextGeneration = _cell.IdentifyStateForTheNextGeneration();
It should_not_live_on_to_the_next_generation_due_to_under_population = () =>
_stateForNextGeneration.ShouldEqual(State.Dead);
<span class="kwrd">static</span> Cell _cell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> Cell _liveNeighbour;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>This results in a specific guard clause to help me meet the original test and I have to expose the current state on the Cell:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> Cell
{
<span class="kwrd">public</span> State CurrentState { get; <span class="kwrd">private</span> set; }
<span class="kwrd">readonly</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">public</span> Cell(State state, IEnumerable<Cell> neighbours)
{
CurrentState = state;
_neighbours = neighbours;
}
<span class="kwrd">public</span> State IdentifyStateForTheNextGeneration()
{
<span class="kwrd">if</span>(_neighbours.Count(n => n.CurrentState == State.Alive) == 2)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}
}</pre>
</div>
<p>I know added another test that would fail:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_an_alive_cell_has_four_alive_neighbours
{
Establish context = () =>
{
_neighbours = <span class="kwrd">new</span> List<Cell> { <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>) };
_cell = <span class="kwrd">new</span> Cell(State.Alive, _neighbours);
};
Because of = () => _stateForNextGeneration = _cell.IdentifyStateForTheNextGeneration();
It should_not_live_on_to_the_next_generation_due_to_over_population = () =>
_stateForNextGeneration.ShouldEqual(State.Dead);
<span class="kwrd">static</span> Cell _cell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>To make this test pass I know have to be more specific in my guard clause:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">if</span>(_neighbours.Count(n => n.CurrentState == State.Alive) == 2)</pre>
</div>
<p>I can now refine it more for three alive neighbours:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_an_alive_cell_has_three_alive_neighbours
{
Establish context = () =>
{
_neighbours = <span class="kwrd">new</span> List<Cell> { <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>) };
_cell = <span class="kwrd">new</span> Cell(State.Alive, _neighbours);
};
Because of = () => _stateForNextGeneration = _cell.IdentifyStateForTheNextGeneration();
It should_live_on_to_the_next_generation = () =>
_stateForNextGeneration.ShouldEqual(State.Alive);
<span class="kwrd">static</span> Cell _cell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>And this once again refines my implementation:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> Cell
{
<span class="kwrd">public</span> State CurrentState { get; <span class="kwrd">private</span> set; }
<span class="kwrd">readonly</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">public</span> Cell(State state, IEnumerable<Cell> neighbours)
{
CurrentState = state;
_neighbours = neighbours;
}
<span class="kwrd">public</span> State IdentifyStateForTheNextGeneration()
{
var aliveNeighbours = _neighbours.Count(n => n.CurrentState == State.Alive);
<span class="kwrd">if</span>( aliveNeighbours == 2 || aliveNeighbours == 3)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}
}</pre>
</div>
<p>Now I thought it was time to introduce rules for a dead cell:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_dead_cell_has_two_alive_neighbours
{
Establish context = () =>
{
_neighbours = <span class="kwrd">new</span> List<Cell> { <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>) };
_deadCell = <span class="kwrd">new</span> Cell(State.Dead, _neighbours);
};
Because of = () => _stateForNextGeneration = _deadCell.IdentifyStateForTheNextGeneration();
It should_still_be_dead_on_the_next_generation = () =>
_stateForNextGeneration.ShouldEqual(State.Dead);
<span class="kwrd">static</span> Cell _deadCell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>This test fails, so once again, the simplest thing possible:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> Cell
{
<span class="kwrd">public</span> State CurrentState { get; <span class="kwrd">private</span> set; }
<span class="kwrd">readonly</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">public</span> Cell(State state, IEnumerable<Cell> neighbours)
{
CurrentState = state;
_neighbours = neighbours;
}
<span class="kwrd">public</span> State IdentifyStateForTheNextGeneration()
{
<span class="kwrd">if</span> (CurrentState == State.Dead)
<span class="kwrd">return</span> State.Dead;
var aliveNeighbours = _neighbours.Count(n => n.CurrentState == State.Alive);
<span class="kwrd">if</span>( aliveNeighbours == 2 || aliveNeighbours == 3)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}
}</pre>
</div>
<p>Another test for dead, this time for resurrection:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(Cell))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_dead_cell_has_three_alive_neighbours
{
Establish context = () =>
{
_neighbours = <span class="kwrd">new</span> List<Cell> { <span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>),
<span class="kwrd">new</span> Cell(State.Alive, <span class="kwrd">null</span>) };
_deadCell = <span class="kwrd">new</span> Cell(State.Dead, _neighbours);
};
Because of = () => _stateForNextGeneration = _deadCell.IdentifyStateForTheNextGeneration();
It should_become_alive_on_the_next_generation = () =>
_stateForNextGeneration.ShouldEqual(State.Alive);
<span class="kwrd">static</span> Cell _deadCell;
<span class="kwrd">static</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">static</span> State _stateForNextGeneration;
}</pre>
</div>
<p>Now making the implementation neat for this was interesting. What I don't want is mess with an if statement at the start of the existing method:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">if</span> (CurrentState == State.Dead)
{
<span class="kwrd">if</span> (xxxxxx)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}</pre>
</div>
<p>So instead the rules were split to make them expressive:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> Cell
{
<span class="kwrd">public</span> State CurrentState { get; <span class="kwrd">private</span> set; }
<span class="kwrd">readonly</span> IEnumerable<Cell> _neighbours;
<span class="kwrd">public</span> Cell(State state, IEnumerable<Cell> neighbours)
{
CurrentState = state;
_neighbours = neighbours;
}
<span class="kwrd">public</span> State IdentifyStateForTheNextGeneration()
{
var aliveNeighbours = _neighbours.Count(n => n.CurrentState == State.Alive);
<span class="kwrd">return</span> CurrentState == State.Alive ? IdentifyStateBecauseIAmAlive(aliveNeighbours) :
IdentifyStateBecauseIAmDead(aliveNeighbours);
}
State IdentifyStateBecauseIAmAlive(<span class="kwrd">int</span> aliveNeighbours)
{
<span class="kwrd">if</span> (aliveNeighbours == 2 || aliveNeighbours == 3)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}
State IdentifyStateBecauseIAmDead(<span class="kwrd">int</span> aliveNeighbours)
{
<span class="kwrd">if</span>(aliveNeighbours ==3)
<span class="kwrd">return</span> State.Alive;
<span class="kwrd">return</span> State.Dead;
}
}</pre>
</div>
<p>So what did I learn from this?</p>
<p>It was interesting that I was able to define the rules without actually declaring any dead neighbours at all. Because I’m working with IEnumerable<Cell> and not restricting the Cell implementation to have exactly eight neighbours or know about top, left, right, diagonal etc, my rules implementation seems to be easier and my tests certainly were easier to set up.</p>
<p>Because I started at the cell level I haven’t even explored the grid itself yet – would I have an external grid class that managed the creation of cells and ensured the neighbour arrangement for example?
<br />I also haven’t explored what happens to current state on the “tick” of the generation, something I might want to concentrate on a later retreat.</p>
<p>My tests seem very expressive, and I could write more for edge cases over and above the rules themselves, such as eight specific dead neighbours, etc.
<br />Its a shame such rich information is only available to developers, so one of my next retreats will be to look at other ways of defining these specifications.</p>
<p>So I’m happy after this retreat – although I haven’t pushed myself that much on this one, I am confident that because I’ve started with the rules from the problem domain (and not layout) I have had a relatively easy implementation of the rules and have shaped the code in a particular way that fits nicely.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-85801586531414300342011-11-28T11:38:00.002+00:002011-11-28T11:40:21.923+00:00My own personal code retreat<p>My blog has been rather quiet lately with my intention of putting one or two posts per week falling completely short – if you’ve been following my fubuMVC series you will have noticed it hasn’t gone anywhere lately (but I plan to pick it up again very soon).</p> <p>The reason is simply that times have been tough lately – I had my contract terminated (and the London market is very, very quiet for work at the moment) and at this same time, sadly my father died.</p> <p>Coping with the contract and work search is fairly easy, the nature of contracting sometimes means that I may be out of work in quiet periods. However coping with the death of my father has been a challenge.</p> <p>Losing someone close is hard, much harder than I ever anticipated. A constant that has been there for your entire life is suddenly removed and it has been very difficult - from assisting with the arrangement of the funeral, to giving a speech in front of his loved ones it has certainly been a strain. All the while I’ve been ensuring that my two older children (of three) feel that although we are all sad (and it’s OK to be sad), their life continues to be valued and has continued support. <br />The hardest part has been just simply waking up in a positive frame of mind – I’ve found it almost impossible at times.</p> <p>What all of this has done for me is to make me question what is truly important, whether everything I do has value and what can I do to ensure any regrets I have can move my life in positive directions. <br />Having time off has thankfully given me valuable and quality time with my family and my new daughter – travelling to London and back every day for a total of four hours certainly wasn’t conducive to this in the past.</p> <p>One of the things I’ve obviously therefore questioned is what I do for a living – should I continue to develop? do I really love it that much that I should be from my family for a large proportion of the week? what do I want to do going forward?</p> <p>After some reflection I can say that I do like being a developer. There is something about this profession that does enable you to push and find real value in yourself and in what you do. I love using C# and consider myself an expert in the language, something that I am very proud of especially because it is entirely self taught. <br />My father used to help me program adventure games into our ZX Spectrum when I was in my very early years and although I never studied computers or programming at university its not by chance that my work life moved from a humble dry cleaners and morphed into learning a fantastic language and development platform – it’s something that I obviously always wanted to do.</p> <p>From this reflection, I also have the desire to make the name of this blog ring true – “being new”. I do always ensure that I learn new things and I want to truly continue to find personal improvement, but this time push more and find it outside of my comfort zone. </p> <p>With that I’m doing my <strong>own personal code retreat</strong> to tie in with the <a href="http://coderetreat.org/">Global day of code retreat</a> that happens this Saturday 3rd December 2011. <br />I’m planning to start some programming again by trying different ways to do the Conway Game of life and see what I can learn. I obviously won’t be doing the pair programming bit and losing what seems to be the essential value from the code retreat, but I do plan to try and push myself and learn some new things.</p> <p>I want to share anything valuable on this blog, and am surprisingly a bit nervous about putting myself out there or committing to a new series of posts - but if it doesn’t go anywhere I’m sure anyone reading this will forgive me.</p> <p>I want to also take this opportunity to say thank you to my wife who has been very supportive and has had to put up with the private fall out and general disagreeable side of my personality while I’m away from the kids and everyone else. I just hope I’m as loving and supportive of her when she needs me most.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com3tag:blogger.com,1999:blog-990393702029999754.post-89937518709526376992011-11-01T08:26:00.001+00:002011-11-01T08:26:47.860+00:00How I authenticate with FubuMVC, part 2<p>In my <a href="http://www.beingnew.net/2011/10/how-i-authenticate-with-fubumvc.html">last post</a> I described the beginning of how to authenticate using behaviours for fubuMVC – part of a change to my production application that I’m sharing my <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">experiences</a> on.</p> <p>I already have an AuthenticationBehaviour class that hands over to an IProcessAuthenticatedUsers to process the current user identity, so I now need to define this processor. It is the responsibility of this processor to put the request’s current user in the fubu request so that models can have access to it - I have decided that it will use a user cache so that it does not have to go to the database for the user details on each request.</p> <p>I’ve also decided to try out the new MemoryCache available in 4.0, but I am going to continue to use the ICacheProvider abstraction that essentially mimics the old ASP.NET cache – this is so I can easily revert should I decide to and is purely my own implementation decision because I’m trying something new.</p> <p>Here’s the ICacheProvider abstraction in the fubuMVC library:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> ICacheProvider
{
<span class="kwrd">object</span> Get(<span class="kwrd">string</span> key);
<span class="kwrd">void</span> Insert(<span class="kwrd">string</span> key, <span class="kwrd">object</span> <span class="kwrd">value</span>, CacheDependency cacheDependency,
DateTime absoluteExpiration, TimeSpan slidingExpiration);
}</pre>
</div>
<p>And here is my own wrapper to the MemoryCache:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> MemoryCacheProvider : ICacheProvider
{
<span class="kwrd">readonly</span> MemoryCache _memoryCache;
<span class="kwrd">public</span> MemoryCacheProvider(MemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
<span class="kwrd">public</span> <span class="kwrd">object</span> Get(<span class="kwrd">string</span> key)
{
<span class="kwrd">return</span> _memoryCache.Get(key);
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Insert(<span class="kwrd">string</span> key, <span class="kwrd">object</span> <span class="kwrd">value</span>, CacheDependency cacheDependency,
DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
var cacheItemPolicy = <span class="kwrd">new</span> CacheItemPolicy
{
AbsoluteExpiration = (absoluteExpiration == Cache.NoAbsoluteExpiration)
? ObjectCache.InfiniteAbsoluteExpiration
: <span class="kwrd">new</span> DateTimeOffset(absoluteExpiration),
SlidingExpiration = (slidingExpiration == Cache.NoSlidingExpiration)
? ObjectCache.NoSlidingExpiration
: slidingExpiration
};
_memoryCache.Add(key, <span class="kwrd">value</span>, cacheItemPolicy);
}
}</pre>
</div>
<p>So here are the specifications for my AuthenticatedUserProcessor:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(AuthenticatedUserProcessor))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_processing_the_user_and_the_user_is_not_in_the_cache
{
Establish context = () =>
{
_emailAddress = <span class="str">"lknkjankjsdk"</span>;
_identity = <span class="kwrd">new</span> Mock<IIdentity>();
_identity.Setup(i => i.Name).Returns(_emailAddress);
_user = <span class="kwrd">new</span> User();
_userObtainer = <span class="kwrd">new</span> Mock<IObtainUsers>();
_userObtainer.Setup(u => u.ObtainUserFromEmailAddress(_emailAddress))
.Returns(_user);
_fubuRequest = <span class="kwrd">new</span> Mock<IFubuRequest>();
_userRequestCache = <span class="kwrd">new</span> MemoryCacheProvider(<span class="kwrd">new</span> MemoryCache(<span class="str">"userCache"</span>));
_authenticatedUserProcessor = <span class="kwrd">new</span> AuthenticatedUserProcessor(_userRequestCache,
_userObtainer.Object, _fubuRequest.Object);
};
Because of = () =>
_authenticatedUserProcessor.Process(_identity.Object);
It caches_the_user_it_obtained = () =>
(_userRequestCache.Get(_emailAddress) <span class="kwrd">as</span> TheRequestsCurrentUser)
.User.ShouldEqual(_user);
It should_place_the_user_in_the_fubu_request = () =>
_fubuRequest.Verify(f => f.Set(Moq.It.Is<TheRequestsCurrentUser>(r => r.User == _user)));
<span class="kwrd">static</span> AuthenticatedUserProcessor _authenticatedUserProcessor;
<span class="kwrd">static</span> Mock<IObtainUsers> _userObtainer;
<span class="kwrd">static</span> Mock<IFubuRequest> _fubuRequest;
<span class="kwrd">static</span> Mock<IIdentity> _identity;
<span class="kwrd">static</span> <span class="kwrd">string</span> _emailAddress;
<span class="kwrd">static</span> User _user;
<span class="kwrd">static</span> ICacheProvider _userRequestCache;
}
[Subject(<span class="kwrd">typeof</span>(AuthenticatedUserProcessor))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_processing_the_user_and_the_user_is_already_in_the_cache
{
Establish context = () =>
{
_emailAddress = <span class="str">"onmojnouiwe"</span>;
_identity = <span class="kwrd">new</span> Mock<IIdentity>();
_identity.Setup(i => i.Name).Returns(_emailAddress);
_userObtainer = <span class="kwrd">new</span> Mock<IObtainUsers>();
_fubuRequest = <span class="kwrd">new</span> Mock<IFubuRequest>();
_theRequestsCurrentUser = <span class="kwrd">new</span> TheRequestsCurrentUser();
_userRequestCache = <span class="kwrd">new</span> MemoryCacheProvider(<span class="kwrd">new</span> MemoryCache(<span class="str">"userCache"</span>));
_userRequestCache.Insert(_emailAddress, _theRequestsCurrentUser, <span class="kwrd">null</span>,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
_authenticatedUserProcessor = <span class="kwrd">new</span> AuthenticatedUserProcessor(_userRequestCache,
_userObtainer.Object, _fubuRequest.Object);
};
Because of = () =>
_authenticatedUserProcessor.Process(_identity.Object);
It should_place_the_user_in_the_fubu_request = () =>
_fubuRequest.Verify(f => f.Set(_theRequestsCurrentUser));
<span class="kwrd">static</span> AuthenticatedUserProcessor _authenticatedUserProcessor;
<span class="kwrd">static</span> Mock<IObtainUsers> _userObtainer;
<span class="kwrd">static</span> Mock<IFubuRequest> _fubuRequest;
<span class="kwrd">static</span> Mock<IIdentity> _identity;
<span class="kwrd">static</span> <span class="kwrd">string</span> _emailAddress;
<span class="kwrd">static</span> ICacheProvider _userRequestCache;
<span class="kwrd">static</span> TheRequestsCurrentUser _theRequestsCurrentUser;
}</pre>
</div>
<p>These specifications are pretty simple – if not in the cache, the user is obtained from the database and stored in the cache – it is then stored in the current fubu request.
<br />If it is in the cache, it simply sets the cached user into the request.
<br />At a later date, I hope to revisit this to provide dependencies to update the cache when the user details change, but this is a good enough solution for the time being.</p>
<p>Here is the implementation of the processor:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> AuthenticatedUserProcessor : IProcessAuthenticatedUsers
{
<span class="kwrd">readonly</span> ICacheProvider _userRequestCache;
<span class="kwrd">readonly</span> IObtainUsers _userObtainer;
<span class="kwrd">readonly</span> IFubuRequest _fubuRequest;
<span class="kwrd">public</span> AuthenticatedUserProcessor(ICacheProvider userRequestCache,
IObtainUsers userObtainer, IFubuRequest fubuRequest)
{
_userRequestCache = userRequestCache;
_userObtainer = userObtainer;
_fubuRequest = fubuRequest;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Process(IIdentity identity)
{
var user = _userRequestCache.Get(identity.Name) <span class="kwrd">as</span> TheRequestsCurrentUser
?? AddUserToTheCache(identity.Name);
_fubuRequest.Set(user);
}
TheRequestsCurrentUser AddUserToTheCache(<span class="kwrd">string</span> identifier)
{
var user = _userObtainer.ObtainUserFromEmailAddress(identifier);
var currentUser = <span class="kwrd">new</span> TheRequestsCurrentUser {User = user};
_userRequestCache.Insert(identifier, currentUser, <span class="kwrd">null</span>,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
<span class="kwrd">return</span> currentUser;
}
}</pre>
</div>
<p>That's it, the processor's single responsibility is complete for now and I have a user obtainer to create, but that easy enough without showing here.</p>
<p>In my next post, the third part of my authentication posts, I’ll show how I ensure that input models in the fubuMVC request can be provided with the current user request so user information can always be at hand at my controller actions.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-52149184012081981452011-10-06T12:41:00.001+01:002011-10-06T12:43:20.382+01:00How I authenticate with fubuMVC<p>I’ve been changing my application to use fubuMVC and have been writing about <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">my experiences</a> with this process - this post is the first one that describes how I authenticate a user. <br />It once again illustrates the simple, yet very extensible nature of the framework.</p> <p>Before I go into detail with some test driven specifications, there are a few things to point out in preparation:</p> <p>Firstly, I’m using forms authentication:</p> <div class="codeBlock"> <pre class="csharpcode"> <authentication mode=<span class="str">"Forms"</span>>
<forms protection=<span class="str">"Encryption"</span> loginUrl=<span class="str">"~/login"</span> timeout=<span class="str">"25"</span> slidingExpiration=<span class="str">"true"</span> />
</authentication></pre>
</div>
<p>Secondly, to assist with authentication the fubuMVC framework provides a security abstraction that allows you to identify the current forms authentication user, so I’m going to be using that.
<br />Here’s the interface for the security context:</p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">namespace</span> FubuMVC.Core.Security
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> ISecurityContext
{
IIdentity CurrentIdentity { get; }
IPrincipal CurrentUser { get; set; }
<span class="kwrd">bool</span> IsAuthenticated();
}
}</pre>
</div>
<p>Last of all, in order for me to authenticate in the request pipeline, with fubuMVC I need to write a custom behaviour which I can insert into the behaviour chain executed on each relevant request.
<br />It is going to need to use the IContinuationDirector from the fubuMVC framework and I <a href="http://www.beingnew.net/2011/10/how-i-register-icontinuationdirector-in.html">recently illustrated</a> how I ensure the registration of that abstraction.</p>
<p>So, here are my test driven specifications for this new behaviour (and note, these were refined and built up over a few iterations with TDD and are presented here as the final version):</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(AuthenticationBehaviour))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_invoked_and_the_user_is_authenticated
{
Establish context = () =>
{
_identity = <span class="kwrd">new</span> Mock<IIdentity>();
_currentUser = <span class="kwrd">new</span> Mock<IPrincipal>();
_currentUser.Setup(u => u.Identity).Returns(_identity.Object);
_securityContext = <span class="kwrd">new</span> Mock<ISecurityContext>();
_securityContext.Setup(s => s.IsAuthenticated()).Returns(<span class="kwrd">true</span>);
_securityContext.Setup(s => s.CurrentUser).Returns(_currentUser.Object);
_continuationDirector = <span class="kwrd">new</span> Mock<IContinuationDirector>();
_outputWriter = <span class="kwrd">new</span> Mock<IOutputWriter>();
_authenticatedUserProcessor = <span class="kwrd">new</span> Mock<IProcessAuthenticatedUsers>();
_nextBehaviour = <span class="kwrd">new</span> Mock<IActionBehavior>();
_authenticationBehaviour = <span class="kwrd">new</span> AuthenticationBehaviour(_securityContext.Object,
() => _continuationDirector.Object,
_outputWriter.Object,
_authenticatedUserProcessor.Object)
{
InsideBehavior = _nextBehaviour.Object
};
};
Because of = () => _authenticationBehaviour.Invoke();
It should_tell_the_user_processor_to_process_the_current_user = () =>
_authenticatedUserProcessor.Verify(u => u.Process(_identity.Object));
It should_continue_to_invoke_further_behaviours = () =>
_nextBehaviour.Verify(b => b.Invoke());
<span class="kwrd">static</span> Mock<ISecurityContext> _securityContext;
<span class="kwrd">static</span> AuthenticationBehaviour _authenticationBehaviour;
<span class="kwrd">static</span> Mock<IActionBehavior> _nextBehaviour;
<span class="kwrd">static</span> Mock<IProcessAuthenticatedUsers> _authenticatedUserProcessor;
<span class="kwrd">static</span> Mock<IPrincipal> _currentUser;
<span class="kwrd">static</span> Mock<IContinuationDirector> _continuationDirector;
<span class="kwrd">static</span> Mock<IOutputWriter> _outputWriter;
<span class="kwrd">static</span> Mock<IIdentity> _identity;
}</pre>
</div>
<p>In my specification I’m setting up an identity and principal which are provided by the ISecurityContext CurrentUser.
<br />I’m setting IsAuthenticated to true to emulate the user being authenticated and I verify that it should tell the user processor to process the user and it should continue to invoke further behaviours.</p>
<p>I also have the specification for when the user is not authenticated:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(AuthenticationBehaviour))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_invoked_and_the_user_is_not_authenticated
{
Establish context = () =>
{
_securityContext = <span class="kwrd">new</span> Mock<ISecurityContext>();
_securityContext.Setup(s => s.IsAuthenticated()).Returns(<span class="kwrd">false</span>);
_continuationDirector = <span class="kwrd">new</span> Mock<IContinuationDirector>();
_outputWriter = <span class="kwrd">new</span> Mock<IOutputWriter>();
_authenticatedUserProcessor = <span class="kwrd">new</span> Mock<IAuthenticatedUserProcessor>();
_nextBehaviour = <span class="kwrd">new</span> Mock<IActionBehavior>();
_authenticationBehaviour = <span class="kwrd">new</span> AuthenticationBehaviour(_securityContext.Object,
() => _continuationDirector.Object,
_outputWriter.Object,
_authenticatedUserProcessor.Object)
{
InsideBehavior = _nextBehaviour.Object
};
};
Because of = () => _authenticationBehaviour.Invoke();
It should_ensure_the_response_is_not_authorised = () =>
_outputWriter.Verify(o => o.WriteResponseCode(HttpStatusCode.Forbidden));
It should_redirect_the_user_so_that_they_can_login = () =>
_continuationDirector.Verify(c => c.RedirectToCall(Moq.It.Is<ActionCall>(a =>
a.HandlerType == <span class="kwrd">typeof</span>(LoginController) && a.Method.Name == <span class="str">"Root"</span>)));
It should_not_continue_to_invoke_further_behaviours = () =>
_nextBehaviour.VerifyNeverHappened(b => b.Invoke());
<span class="kwrd">static</span> Mock<ISecurityContext> _securityContext;
<span class="kwrd">static</span> AuthenticationBehaviour _authenticationBehaviour;
<span class="kwrd">static</span> Mock<IActionBehavior> _nextBehaviour;
<span class="kwrd">static</span> Mock<IAuthenticatedUserProcessor> _authenticatedUserProcessor;
<span class="kwrd">static</span> Mock<IContinuationDirector> _continuationDirector;
<span class="kwrd">static</span> Mock<IOutputWriter> _outputWriter;
}</pre>
</div>
<p>In this scenario I want to write a forbidden response code, redirect the user to the login page and not invoke any further behaviours.</p>
<p>Here’s the implementation of my behaviour:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> AuthenticationBehaviour : BasicBehavior
{
<span class="kwrd">readonly</span> ISecurityContext _securityContext;
<span class="kwrd">readonly</span> IContinuationDirector _continuationDirector;
<span class="kwrd">readonly</span> IOutputWriter _outputWriter;
<span class="kwrd">readonly</span> IProcessAuthenticatedUsers _authenticatedUserProcessor;
<span class="kwrd">public</span> AuthenticationBehaviour(ISecurityContext securityContext,
Func<IContinuationDirector> continuationDirectorFactory,
IOutputWriter outputWriter,
IProcessAuthenticatedUsers authenticatedUserProcessor)
: <span class="kwrd">base</span>(PartialBehavior.Ignored)
{
_securityContext = securityContext;
_continuationDirector = continuationDirectorFactory();
_outputWriter = outputWriter;
_authenticatedUserProcessor = authenticatedUserProcessor;
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> DoNext performInvoke()
{
<span class="kwrd">if</span>(!_securityContext.IsAuthenticated())
{
_outputWriter.WriteResponseCode(HttpStatusCode.Forbidden);
_continuationDirector.RedirectToCall(<br /> ActionCall.For<LoginController>(c => c.Root()));
<span class="kwrd">return</span> DoNext.Stop;
}
_authenticatedUserProcessor.Process(_securityContext.CurrentUser.Identity);
<span class="kwrd">return</span> DoNext.Continue;
}
}</pre>
</div>
<p>To insert this new behaviour into the behaviour graph I need a convention:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> AuthenticationConvention : IConfigurationAction
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Configure(BehaviorGraph graph)
{
graph.Actions()
.Where(c => !c.HandlerType.Namespace.Contains(<span class="str">"Home"</span>)
&& !c.HandlerType.Namespace.Contains(<span class="str">"Login"</span>)
&& !c.HandlerType.Namespace.Contains(<span class="str">"Signup"</span>)
.Each(c => c.WrapWith<AuthenticationBehaviour>());
}
}</pre>
</div>
<p>And I now add this convention to my fubu registry:</p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
<span class="kwrd">public</span> XercesFubuRegistry()
{
IncludeDiagnostics(<span class="kwrd">true</span>);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes.HomeIs<HomeController>(c => c.FrontPage())
.IgnoreControllerNamespaceEntirely()
.UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>();
ApplyConvention<PermanentRedirectionConvention>();
ApplyConvention<SimpleUnitOfWorkConvention>();
ApplyConvention<AuthenticationConvention>(); <- new line
<span class="kwrd">this</span>.UseSpark();
Views.TryToAttachWithDefaultConventions();
Output.ToJson.WhenCallMatches(action => action.Returns<AjaxResponse>());
}
}</pre>
</div>
<p>In my next post I’ll show what happens when the authenticated user is processed by the IProcessAuthenticatedUsers implementation and how I make the current user available to my input models.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-647522644309489742011-10-04T08:48:00.001+01:002011-10-04T08:48:32.378+01:00How I register the IContinuationDirector in fubuMVC<p>I’m blogging about <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">my experiences</a> with fubuMVC and an interesting thing I came across recently was the lack of a registration for a concrete IContinuationDirector in the structure map container.</p> <p>The IContinuationDirector abstraction enables you to transfer or redirect a request efficiently and I have a need for this in quite a few places. Here’s the interface:</p> <div class="codeBlock"> <pre class="csharpcode"><span class="kwrd">namespace</span> FubuMVC.Core.Continuations
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> IContinuationDirector
{
<span class="kwrd">void</span> InvokeNextBehavior();
<span class="kwrd">void</span> RedirectTo(<span class="kwrd">object</span> input);
<span class="kwrd">void</span> RedirectToCall(ActionCall call);
<span class="kwrd">void</span> TransferTo(<span class="kwrd">object</span> input);
<span class="kwrd">void</span> TransferToCall(ActionCall call);
}
}</pre>
</div>
<p>So I registered the concrete implementation that exists in fubuMVC:</p>
<div class="codeBlock">
<pre class="csharpcode"> x.For<IContinuationDirector>().Use(c => <span class="kwrd">new</span> ContinuationHandler(c.GetInstance<IUrlRegistry>(),
c.GetInstance<IOutputWriter>(),
c.GetInstance<IFubuRequest>(),
c.GetInstance<IPartialFactory>()));</pre>
</div>
<p>But at runtime, this <a href="http://groups.google.com/group/fubumvc-devel/msg/4829d9511424dbe9">known problem</a> reared its head:</p>
<p><b>Unable to cast object of type 'FubuMVC.Core.Diagnostics.Tracing.BehaviorTracer'
<br />to type 'FubuMVC.Core.Continuations.IContinuationDirector'.</b></p>
<p>The solution was easy – defer creation of the continuation handler until it is required by the behaviour that needs it and it is then not wrapped by any diagnostics:</p>
<div class="codeBlock">
<pre class="csharpcode">x.For<Func<IContinuationDirector>>().Use(c => <br /> () => <span class="kwrd">new</span> ContinuationHandler(c.GetInstance<IUrlRegistry>(),
c.GetInstance<IOutputWriter>(),
c.GetInstance<IFubuRequest>(),
c.GetInstance<IPartialFactory>()));</pre>
</div>
<p>So now I just take a Func<IContinuationDirector> as a dependency rather than the interface and my problems are solved.</p>
<p>Note: there could very well be a known solution to this issue by now, so I’m merely illustrating my own method for resolving this. Also note that I don’t use it as a behaviour node, but as a redirection/transfer abstraction in my actions.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-18543230308148644162011-09-22T18:42:00.001+01:002011-09-22T18:42:55.755+01:00How I use NHibernate with fubuMVC<p>I’m currently upgrading my production website to use the excellent fubuMVC framework and have been writing about <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">my experiences</a> with it.</p> <p>One of the early needs for me was to integrate NHibernate and I wanted to do this in as simple a way as possible without extra unit of work classes or transaction/session managers. <br />Here’s what I came up with:</p> <p>Every request, I want a new session for the entire request and I want everything within that request in a transaction that can be committed or rolled back. However not all requests will use a session, so it will be inefficient to open a new session on every single request, so I need to make that session lazy. <br />Let’s start with the specifications:</p> <div class="codeBlock"> <pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(SimpleUnitOfWorkBehaviour))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_invoked
{
Establish context = () =>
{
_sessionFactory = <span class="kwrd">new</span> Mock<ISessionFactory>();
_fubuRequest = <span class="kwrd">new</span> Mock<IFubuRequest>();
_innerBehaviour = <span class="kwrd">new</span> Mock<IActionBehavior>();
_simpleUnitOfWorkBehaviour = <span class="kwrd">new</span> SimpleUnitOfWorkBehaviour(_sessionFactory.Object, <br /> _fubuRequest.Object)
{
InnerBehavior = _innerBehaviour.Object
};
};
Because of = () => _simpleUnitOfWorkBehaviour.Invoke();
It should_provide_a_lazy_session_in_the_fubu_request = () =>
_fubuRequest.Verify(f => f.Set(Moq.It.IsAny<Lazy<ISession>>()));
It should_invoke_the_inner_behaviour = () =>
_innerBehaviour.Verify(b => b.Invoke());
It should_not_yet_open_the_session = () =>
_sessionFactory.VerifyNeverHappened(f => f.OpenSession());
<span class="kwrd">static</span> SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour;
<span class="kwrd">static</span> Mock<ISessionFactory> _sessionFactory;
<span class="kwrd">static</span> Mock<IFubuRequest> _fubuRequest;
<span class="kwrd">static</span> Mock<IActionBehavior> _innerBehaviour;
}</pre>
</div>
<p>I’m specifying a new fubuMVC behaviour – SimpleUnitOfWorkBehaviour – which is injected with an NHibernate session factory and the FubuRequest via the constructor and the InnerBehaviour via a property as per the fubuMVC inner behaviour convention.
<br />Once invoked, this behaviour should provide a lazy session in the fubu request, it should invoke the inner behaviour but, importantly it should not yet open the session.
<br />Here’s the implementation of that:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> SimpleUnitOfWorkBehaviour : IActionBehavior
{
<span class="kwrd">readonly</span> IFubuRequest _fubuRequest;
<span class="kwrd">readonly</span> ISessionFactory _sessionFactory;
<span class="kwrd">public</span> IActionBehavior InnerBehavior { get; set; }
<span class="kwrd">public</span> SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, <br /> IFubuRequest fubuRequest)
{
_sessionFactory = sessionFactory;
_fubuRequest = fubuRequest;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Invoke()
{
_fubuRequest.Set(<span class="kwrd">new</span> Lazy<ISession>());
InnerBehavior.Invoke();
}
<span class="kwrd">public</span> <span class="kwrd">void</span> InvokePartial() { InnerBehavior.InvokePartial(); }
}</pre>
</div>
<p>Pretty basic (there isn’t even an actual session yet) but functional so it needs pushing with some new specifications:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(SimpleUnitOfWorkBehaviour))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_invoked_and_the_inner_behaviour_chain_consumes_the_session
{
Establish context = () =>
{
_transaction = <span class="kwrd">new</span> Mock<ITransaction>();
_session = <span class="kwrd">new</span> Mock<ISession>();
_session.Setup(s => s.BeginTransaction()).Returns(_transaction.Object);
_session.SetupGet(s => s.Transaction).Returns(_transaction.Object);
_sessionFactory = <span class="kwrd">new</span> Mock<ISessionFactory>();
_sessionFactory.Setup(f => f.OpenSession()).Returns(_session.Object);
_fubuRequest = <span class="kwrd">new</span> Mock<IFubuRequest>();
_fubuRequest.Setup(f => f.Set(Moq.It.IsAny<Lazy<ISession>>()))
.Callback<Lazy<ISession>>(lazySession => _lazySession = lazySession);
_innerBehaviour = <span class="kwrd">new</span> Mock<IActionBehavior>();
_innerBehaviour.Setup(b => b.Invoke()).Callback(() => {var s=_lazySession.Value;});
_simpleUnitOfWorkBehaviour = <span class="kwrd">new</span> SimpleUnitOfWorkBehaviour(_sessionFactory.Object, <br /> _fubuRequest.Object)
{
InnerBehavior = _innerBehaviour.Object
};
};
Because of = () => _simpleUnitOfWorkBehaviour.Invoke();
It should_open_the_session = () =>
_sessionFactory.Verify(f => f.OpenSession());
It should_begin_a_transaction = () =>
_session.Verify(s => s.BeginTransaction());
It should_commit_the_transaction = () =>
_transaction.Verify(t => t.Commit());
It should_dispose_the_session = () =>
_session.Verify(s => s.Dispose());
<span class="kwrd">static</span> SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour;
<span class="kwrd">static</span> Mock<ISessionFactory> _sessionFactory;
<span class="kwrd">static</span> Mock<IFubuRequest> _fubuRequest;
<span class="kwrd">static</span> Mock<IActionBehavior> _innerBehaviour;
<span class="kwrd">static</span> Lazy<ISession> _lazySession;
<span class="kwrd">static</span> Mock<ISession> _session;
<span class="kwrd">static</span> Mock<ITransaction> _transaction;
}</pre>
</div>
<p>This one is a bit more complex as it is setting up quite a few behaviours on the mocks – first it sets up the session and transaction along with the session factory providing that session when OpenSession is called.
<br />Then there is a callback on the FubuRequest so that when the Lazy<ISession> is set, it can be captured and finally the inner behaviour is set up to consume the captured lazy session.</p>
<p>It should then open the session, begin a transaction, commit it and then dispose of that session.
<br />Here’s the implementation so far:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> SimpleUnitOfWorkBehaviour : IActionBehavior
{
<span class="kwrd">readonly</span> IFubuRequest _fubuRequest;
<span class="kwrd">readonly</span> ISessionFactory _sessionFactory;
ISession _session;
<span class="kwrd">public</span> IActionBehavior InnerBehavior { get; set; }
<span class="kwrd">public</span> SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, <br /> IFubuRequest fubuRequest)
{
_sessionFactory = sessionFactory;
_fubuRequest = fubuRequest;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Invoke()
{
_fubuRequest.Set(<span class="kwrd">new</span> Lazy<ISession>(() => <br /> _session ?? (_session = CreateTransactionalSession())));
InnerBehavior.Invoke();
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
{
_session.Transaction.Commit();
_session.Dispose();
}
}
ISession CreateTransactionalSession()
{
var session = _sessionFactory.OpenSession();
session.BeginTransaction();
<span class="kwrd">return</span> session;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> InvokePartial() { InnerBehavior.InvokePartial(); }
}</pre>
</div>
<p>There is no error handling yet, so it is time for a specification for that:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(SimpleUnitOfWorkBehaviour))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_invoked_and_the_inner_behaviour_chain_consumes_the_session_but_<br /> something_goes_wrong
{
Establish context = () =>
{
_transaction = <span class="kwrd">new</span> Mock<ITransaction>();
_session = <span class="kwrd">new</span> Mock<ISession>();
_session.Setup(s => s.BeginTransaction()).Returns(_transaction.Object);
_session.SetupGet(s => s.Transaction).Returns(_transaction.Object);
_sessionFactory = <span class="kwrd">new</span> Mock<ISessionFactory>();
_sessionFactory.Setup(f => f.OpenSession()).Returns(_session.Object);
_fubuRequest = <span class="kwrd">new</span> Mock<IFubuRequest>();
_fubuRequest.Setup(f => f.Set(Moq.It.IsAny<Lazy<ISession>>()))
.Callback<Lazy<ISession>>(lazySession => _lazySession = lazySession);
_exception = <span class="kwrd">new</span> Exception();
_innerBehaviour = <span class="kwrd">new</span> Mock<IActionBehavior>();
_innerBehaviour.Setup(b => b.Invoke()).Callback(() =>
{
var s = _lazySession.Value;
<span class="kwrd">throw</span> _exception;
});
_simpleUnitOfWorkBehaviour = <span class="kwrd">new</span> SimpleUnitOfWorkBehaviour(_sessionFactory.Object, <br /> _fubuRequest.Object)
{
InnerBehavior = _innerBehaviour.Object
};
};
Because of = () => <br /> _caughtException = Catch.Exception(() => _simpleUnitOfWorkBehaviour.Invoke());
It should_rollback_the_transaction = () =>
_transaction.Verify(t => t.Rollback());
It should_dispose_the_session = () =>
_session.Verify(s => s.Dispose());
It should_not_swallow_the_problem = () =>
_caughtException.ShouldEqual(_exception);
<span class="kwrd">static</span> SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour;
<span class="kwrd">static</span> Mock<ISessionFactory> _sessionFactory;
<span class="kwrd">static</span> Mock<IFubuRequest> _fubuRequest;
<span class="kwrd">static</span> Mock<IActionBehavior> _innerBehaviour;
<span class="kwrd">static</span> Lazy<ISession> _lazySession;
<span class="kwrd">static</span> Mock<ISession> _session;
<span class="kwrd">static</span> Mock<ITransaction> _transaction;
<span class="kwrd">static</span> Exception _exception;
<span class="kwrd">static</span> Exception _caughtException;
}</pre>
</div>
<p>This specification has the same kind of setup yet this time the inner behaviour has changed to not only consume the session, but to throw an exception. It should then rollback the transaction, dispose the session and not swallow the exception and let it bubble up.</p>
<p>Here’s the final implementation of the SimpleUnitOfWorkBehaviour:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> SimpleUnitOfWorkBehaviour : IActionBehavior
{
<span class="kwrd">readonly</span> IFubuRequest _fubuRequest;
<span class="kwrd">readonly</span> ISessionFactory _sessionFactory;
ISession _session;
<span class="kwrd">public</span> IActionBehavior InnerBehavior { get; set; }
<span class="kwrd">public</span> SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, <br /> IFubuRequest fubuRequest)
{
_sessionFactory = sessionFactory;
_fubuRequest = fubuRequest;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Invoke()
{
_fubuRequest.Set(<span class="kwrd">new</span> Lazy<ISession>(() => <br /> _session ?? (_session = CreateTransactionalSession())));
<span class="kwrd">try</span>
{
InnerBehavior.Invoke();
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Transaction.Commit();
}
<span class="kwrd">catch</span> (Exception)
{
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Transaction.Rollback();
<span class="kwrd">throw</span>;
}
<span class="kwrd">finally</span>
{
<span class="kwrd">if</span> (_session != <span class="kwrd">null</span>)
_session.Dispose();
}
}
ISession CreateTransactionalSession()
{
var session = _sessionFactory.OpenSession();
session.BeginTransaction();
<span class="kwrd">return</span> session;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> InvokePartial() { InnerBehavior.InvokePartial(); }
}</pre>
</div>
<p>Finally, I need to think about how this lazy session will be consumed – I want a delegate to the session rather than anything else knowing about the laziness of the session, so I’m going to use a http scoped Func<ISession> that is injected into any instance that needs a session.</p>
<p>So I need to set up the container accordingly:</p>
<div class="codeBlock">  <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ContainerConfigurer : IConfigureContainers
{
<span class="kwrd">public</span> ContainerConfigurer()
{
Configuration = x =>
{
x.Scan(i =>
{
i.TheCallingAssembly();
i.AssemblyContainingType<UserVerifier>();
i.SingleImplementationsOfInterface();
});
x.For<Func<ISession>>().HttpContextScoped().Use(<br /> c => () => c.GetInstance<IFubuRequest>().Get<Lazy<ISession>>().Value);<br />
x.For<ISessionFactory>().Singleton().Use(<br /> c => c.GetInstance<ISessionFactoryCreator>().CreateFactory(<span class="str">"Xerces"</span>));<br />
x.For<ISessionFactoryCreator>().Singleton().Use<SessionFactoryCreator>();
};
}
}</pre>
</div>
<p>I’m registering a delegate for an ISession that when invoked will get the current IFubuRequest and obtain the current Lazy<ISession> value, thus opening the session and providing it on demand for that current request.</p>
<p>So there it is a simple unit of work behaviour for fubuMVC that defers the opening of the session until needed.</p>
<p><em>(Note that this does not work if I have a singleton instance that consumes the Func<ISession> as the resolution inside the delegate will be in the wrong nested scope. However I personally always ensure that singleton state is kept outside of data providers that need the session - the data providers themselves are transient and can be injected with singleton caches for example).</em></p>
<p>Here’s a simple example of that delegate in use:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> UserObtainer : IObtainUsers
{
<span class="kwrd">readonly</span> Func<ISession> _sessionProvider;
<span class="kwrd">public</span> UserObtainer(Func<ISession> sessionProvider)
{
_sessionProvider = sessionProvider;
}
<span class="kwrd">public</span> User ObtainUserFromEmailAddress(<span class="kwrd">string</span> emailAddress)
{
var session = _sessionProvider();
<span class="kwrd">return</span> session.CreateCriteria<User>()
.Add<User>(u => u.EmailAddress == emailAddress)
.UniqueResult<User>();
}
}</pre>
</div> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-1818495047172546632011-09-13T18:34:00.001+01:002011-09-13T18:34:30.425+01:00How I removed magic strings from my fubuMVC redirection policy<p>In my <a href="http://www.beingnew.net/2011/09/how-i-improved-my-fubumvc-redirection.html">previous post</a> on my <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">experiences with fubuMVC</a> I had implemented a redirection policy but was not too happy with the magic strings needed within my convention to point at the methods on my home controller.</p> <p>Here’s what I currently have:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PermanentRedirectionConvention : IConfigurationAction
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Configure(BehaviorGraph graph)
{
graph.Behaviors
.Where(c => c.FirstCall().HandlerType == <span class="kwrd">typeof</span>(HomeController)
&& c.FirstCall().Method.Name.ToLower() == <span class="str">"news"</span>)
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span>(PermanentNewsRedirectionBehaviour))));
graph.Behaviors
.Where(c => c.FirstCall().HandlerType == <span class="kwrd">typeof</span>(HomeController)
&& c.FirstCall().Method.Name.ToLower() == <span class="str">"about"</span>)
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span>(PermanentAboutRedirectionBehaviour))));
}
}</pre>
</div>
<p>Above, I am using the FirstCall() method to retrieve the ActionCall and examining the handler type and method info to establish if it meets my criteria. </p>
<p>To improve this I need an extension method on the ActionCall that will let me point at a method on it’s HandlerType, so this argument will need to be an Expression<Action<THandlerType>> :</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> BehaviourExtensions
{
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> MatchesHandler<THandlerType>(<span class="kwrd">this</span> ActionCall actionCall,
Expression<Action<THandlerType>> handlerExpression)
{
var methodCallExpression = handlerExpression.Body <span class="kwrd">as</span> MethodCallExpression;
<span class="kwrd">if</span>(methodCallExpression==<span class="kwrd">null</span>)
<span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">"Expected a method call expression"</span>);
<span class="kwrd">return</span> <span class="kwrd">typeof</span>(THandlerType) == actionCall.HandlerType
&& methodCallExpression.Method == actionCall.Method;
}
}</pre>
</div>
<p>This new extension method returns the match between the generic THandlerType and the ActionCall’s HandlerType and also the method from the method call expression against the ActionCall’s method.</p>
<p>This now enables me to remove my magic strings:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PermanentRedirectionConvention : IConfigurationAction
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Configure(BehaviorGraph graph)
{
graph.Behaviors
.Where(c => c.FirstCall()<br /> .MatchesHandler<HomeController>(controller => controller.News()))
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span>(PermanentNewsRedirectionBehaviour))));
graph.Behaviors
.Where(c => c.FirstCall()<br /> .MatchesHandler<HomeController>(controller => controller.About()))
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span>(PermanentAboutRedirectionBehaviour))));
}
}</pre>
</div> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-375198027544720882011-09-06T07:35:00.000+01:002011-09-06T07:35:00.102+01:00How I improved my fubuMVC redirection policy with a convention<p>In the <a href="http://www.beingnew.net/2011/09/how-i-permanently-redirect-using.html">previous post</a> of this <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">fubuMVC series</a>, I showed how I had implemented permanent redirection for a url using fubuMVC. I had enriched the action call for the old route with a behaviour that issues a permanent redirection and this behaviour occurred after the action call.</p> <p>In this post I’m going to illustrate how I gained more control over where the behaviour was added – to do this I wrote a convention that implements IConfigurationAction and hooked this into the fubuMVC registry.</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PermanentRedirectionConvention : IConfigurationAction
{
<span class="kwrd">public</span> <span class="kwrd">void</span> Configure(BehaviorGraph graph)
{
graph.Behaviors
.Where(c => c.FirstCall().HandlerType == <span class="kwrd">typeof</span> (HomeController)
&& c.FirstCall().Method.Name.ToLower() == <span class="str">"news"</span>)
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span> (PermanentNewsRedirectionBehaviour))));
graph.Behaviors
.Where(c => c.FirstCall().HandlerType == <span class="kwrd">typeof</span> (HomeController)
&& c.FirstCall().Method.Name.ToLower() == <span class="str">"about"</span>)
.Each(c => c.Prepend(<span class="kwrd">new</span> Wrapper(<span class="kwrd">typeof</span>(PermanentAboutRedirectionBehaviour))));
}
}</pre>
</div>
<p>When you implement a convention you are given the behaviour graph so that you can amend it as you see fit.
<br />Here I am filtering the IEnumerable<BehaviorChain> on the graph, called “Behaviors”, and looking for the one that represents the HomeController and “news” method.
<br />Once I have the behaviour chain that corresponds to this action I am going to ensure that this behaviour sits at the top using the Prepend method.
<br />I’ve also done the same for another action that I am permanently redirecting.</p>
<p>In order to plug this into my fubu registry I am going to replace the policies enrichment with my convention instead:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
<span class="kwrd">public</span> XercesFubuRegistry()
{
IncludeDiagnostics(<span class="kwrd">true</span>);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes.HomeIs<HomeController>(c => c.FrontPage())
.IgnoreControllerNamespaceEntirely()
.UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>();
ApplyConvention<PermanentRedirectionConvention>(); <-- <span class="kwrd">new</span> line
<span class="kwrd">this</span>.UseSpark();
Views.TryToAttachWithDefaultConventions();
}
}</pre>
</div>
<p>This leaves me with a different behaviour graph from last time where my own behaviour is above the action call:</p>
<p><a href="http://lh6.ggpht.com/-XaA4_7F5_ck/TmCI3CtxuCI/AAAAAAAAAKU/8oI7nME68TY/s1600-h/redirectchain2%25255B4%25255D.png"><img style="background-image: none; border-right-width: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="redirectchain2" border="0" alt="redirectchain2" src="http://lh6.ggpht.com/-l5eUsyNjeNI/TmCI7eUUt4I/AAAAAAAAAKY/s4AwoqImphg/redirectchain2_thumb%25255B2%25255D.png?imgmax=800" width="702" height="302" /></a></p>
<p>This now enables me to amend my HomeController to better reflect the fact that the news and action methods should never be called:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> HomeController
{
<span class="kwrd">public</span> HomeViewModel FrontPage()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> HomeViewModel();
}
<span class="kwrd">public</span> AutomaticRedirection News()
{
<span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">"Automatic redirection should have occurred
before reaching this method"</span>);
}
<span class="kwrd">public</span> AutomaticRedirection About()
{
<span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">"Automatic redirection should have occurred
before reaching this method"</span>);
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeViewModel { }
<span class="kwrd">public</span> <span class="kwrd">class</span> AutomaticRedirection { }</pre>
</div>
<p>There’s my redirection policy implemented – there are a couple of things I would like to review though…</p>
<p>The first is that its a shame that I have to have “placeholder” actions in order to point to them in my conventions but by nature of the behaviour graph being built up front we no longer have the dynamic resolution of routes and actions (and that is a good thing for more deterministic and testable behaviour).
<br />I did look at how we might add permanent redirection into fubuMVC itself, but it meant adding behaviour chains that have no action calls and outputs and was not a quick feat, so have not pursued that yet.</p>
<p>The second point is the “magic strings” I’m using in the convention itself for the method names – I don’t like magic strings.
<br />In my next post I’ll show how I removed those and tightened the implementation.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-68069534077275352402011-09-01T22:23:00.000+01:002011-09-01T22:23:00.203+01:00How I permanently redirect using fubuMVC<p>In the process of migrating to fubuMVC I’ve <a href="http://www.beingnew.net/2011/08/how-i-customised-my-fubumvc-routes-with.html">previously touched upon</a> a change in urls in one of my previous posts on my <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">experiences with fubuMVC</a>. <br />In this process I have changed the urls for my static pages from “/home/news” to “/news” for instance and this means that I now have to deal with permanent redirections and issuing 301 redirects for the original urls.</p> <p>With fubuMVC, I’m going to achieve this with a custom behaviour that is inserted into the behaviour chain.</p> <p><em>(to learn more about behaviour chains there are a number of good articles out there, here’s one: </em><a href="http://murrayon.net/2011/06/fubumvc-behavior-chains-bmvc-pattern.html"> <br /><em>http://murrayon.net/2011/06/fubumvc-behavior-chains-bmvc-pattern.html</em></a><em>)</em></p> <p>In order to write a custom behaviour that issues a response I am going to need to interact with the IOutputWriter abstraction and write a response code and custom headers to show the new location of the permanent redirect.</p> <p>At the time of writing this, the IOutputWriter doesn’t yet support writing headers so I’m going to have to extend its functionality for the time being. Here’s the current interface in fubuMVC:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IOutputWriter
{
<span class="kwrd">void</span> WriteFile(<span class="kwrd">string</span> contentType, <span class="kwrd">string</span> localFilePath, <span class="kwrd">string</span> displayName);
<span class="kwrd">void</span> Write(<span class="kwrd">string</span> contentType, <span class="kwrd">string</span> renderedOutput);
<span class="kwrd">void</span> RedirectToUrl(<span class="kwrd">string</span> url);
<span class="kwrd">void</span> AppendCookie(HttpCookie cookie);
<span class="kwrd">void</span> WriteResponseCode(HttpStatusCode status);
RecordedOutput Record(Action action);
}</pre>
</div>
<p>So here’s a simple extension which will write my header directly into the HttpResponse (normally this would be in the HttpOutputWriter concrete class, but I’m extending the interface for my own project here, so don’t have much choice but to place it there; perhaps we can get it added to fubuMVC very soon).</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> OutputWriterExtensions
{
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WriteHeader(<span class="kwrd">this</span> IOutputWriter outputWriter,
<span class="kwrd">string</span> headerName, <span class="kwrd">string</span> headerValue)
{
HttpContext.Current.Response.AppendHeader(headerName, headerValue);
}
}</pre>
</div>
<p>I’m also going to wrap the writing of the response code and the header generation into a specific method, again an extension. I also need to send the IEndpointService in the method call because it is an extension method.
<br />Here’s the wrapper:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> OutputWriterExtensions
{
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WritePermanentRedirectTo<T>(<span class="kwrd">this</span> IOutputWriter outputwriter,
Expression<Action<T>> actionExpression, IEndpointService endpointService)
{
var endpoint = endpointService.EndpointFor(actionExpression);
outputwriter.WriteHeader(<span class="str">"Location"</span>, endpoint.Url);
outputwriter.WriteResponseCode(HttpStatusCode.MovedPermanently);
}
}</pre>
</div>
<p>This now enables me to point at a method on an action and permanently redirect to it.</p>
<p>Now for the behaviour itself – I’m going to inherit from BasicBehavior which does most of the heavy lifting for me leaving me to override the perform invoke method:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> PermanentNewsRedirectionBehaviour : BasicBehavior
{
<span class="kwrd">private</span> <span class="kwrd">readonly</span> IOutputWriter _outputWriter;
<span class="kwrd">private</span> <span class="kwrd">readonly</span> IEndpointService _endpointService;
<span class="kwrd">public</span> PermanentNewsRedirectionBehaviour(IOutputWriter outputWriter,
IEndpointService endpointService)
: <span class="kwrd">base</span>(PartialBehavior.Ignored)
{
_outputWriter = outputWriter;
_endpointService = endpointService;
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> DoNext performInvoke()
{
_outputWriter.WritePermanentRedirectTo<NewsController>(c => c.Root(),
_endpointService);
<span class="kwrd">return</span> DoNext.Stop;
}
}</pre>
</div>
<p>
<br />This is a behaviour that will redirect to the news action using the new extension method I’ve written for the output writer.
<br />The simplest way of putting this into my fubuMVC registry is to use the “EnrichCallsWith” functionality for policies:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
<span class="kwrd">public</span> XercesFubuRegistry()
{
IncludeDiagnostics(<span class="kwrd">true</span>);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes.HomeIs<HomeController>(c => c.FrontPage())
.IgnoreControllerNamespaceEntirely()
.UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>();
Policies.EnrichCallsWith<PermanentNewsRedirectionBehaviour>(call =>
call.HandlerType == <span class="kwrd">typeof</span>(HomeController) &&
call.Method.Name.ToLower() == <span class="str">"news"</span>);
<span class="kwrd">this</span>.UseSpark();
Views.TryToAttachWithDefaultConventions();
}
}</pre>
</div>
<p>The new part of the registry code above is the Policies section where I am enriching a call to the HomeController for a “news” method, a new one as a placeholder for this redirection:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> HomeController
{
<span class="kwrd">public</span> HomeViewModel FrontPage()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> HomeViewModel();
}
<span class="kwrd">public</span> AutomaticRedirection News()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> AutomaticRedirection();
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeViewModel
{}
<span class="kwrd">public</span> <span class="kwrd">class</span> AutomaticRedirection
{}</pre>
</div>
<p>I’ve created a new class called AutomaticRedirection just as another placeholder to indicate what will happen for this method.
<br />In order to see this new functionality I can look at another part of the fubuMVC diagnostics – the behaviour chain and the specific chain for the “home/news” route:</p>
<p><a href="http://lh3.ggpht.com/-CHwxXo6Noec/Tl_2Pd9GEYI/AAAAAAAAAKM/Tywiwkhj1bw/s1600-h/redirectchain%25255B4%25255D.png"><img style="background-image: none; border-right-width: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="redirectchain" border="0" alt="redirectchain" src="http://lh6.ggpht.com/-mH94LHiGMF8/Tl_2Pibs-uI/AAAAAAAAAKQ/rCh2-pFRp3Y/redirectchain_thumb%25255B2%25255D.png?imgmax=800" width="699" height="300" /></a> </p>
<p>I now have permanent redirection in place and baked into fubuMVC in the way that I want it to.
<br />By enriching this action, the action call will occur first and then the wrapper takes effect and permanently redirects - all requests to “home/news” now 301 redirect to “news”.
<br />
<br />In the next post I will show how a custom convention that implements IConfigurationAction can instead give me more fine grained control over where the behaviour is inserted in the graph.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-52646007993366602392011-08-30T06:42:00.000+01:002011-08-30T06:42:00.678+01:00How I link to my fubuMVC actions<p>I’m in the process of migrating an existing production web project to use fubuMVC and all the power that it provides and I’m currently <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">writing a series</a> on my experiences with it – this is the third in that series.</p> <p>I’ve already begun to migrate my static content pages and now need to link to them in my spark views. <br />Obviously hard coding the urls defeats the whole point of routes and actions being malleable so I want a way to look back at  my actions and have fubuMVC find the appropriate url.</p> <p>This is provided by fubuMVC in the form of Url Resolution and my spark views are already integrated with an overloaded LinkTo() method that allows me to refer back to my actions or input models.</p> <p>So here’s the first stab at the navigation in my site using this method:</p> <div class="codeBlock"> <pre class="csharpcode"> <div id=<span class="str">"menu"</span>>
<ul id=<span class="str">"headerLinks"</span>>
<li>${<span class="kwrd">this</span>.LinkTo<HomeController>(c => c.FrontPage()).Text(<span class="str">"home"</span>)}</li>
<li>${<span class="kwrd">this</span>.LinkTo<NewsController>(c => c.Root()).Text(<span class="str">"news"</span>)}</li>
<li>${<span class="kwrd">this</span>.LinkTo<AboutController>(c => c.Root()).Text(<span class="str">"about"</span>)}</li>
<li>${<span class="kwrd">this</span>.LinkTo<LoginController>(c => c.Root()).Text(<span class="str">"login"</span>)}</li>
</ul>
</div></pre>
</div>
<p>This works a treat, but I'm not so sure about breaking out into code all the time. Is there anyway I can embrace the tag nature of the spark view engine and have an element that would do this for me?</p>
<p>Spark bindings allow you to do just that - you can add custom elements that wrap your code by simply providing a bindings.xml file in your shared folder allowing you to hook them into the spark view engine.
<br />Here's my bindings.xml file:</p>
<div class="codeBlock">
<pre class="csharpcode"><?xml version=<span class="str">"1.0"</span>?>
<bindings>
<element name=<span class="str">"linkTo"</span>><span class="kwrd">this</span>.LinkTo&lt;@action&gt;(c => c.@method).Text(<span class="str">"child::*"</span>)</element>
</bindings></pre>
</div>
<p>I’m declaring a new “linkTo” element and chopping up the previous code with parameters I expect on that element.
<br />This allows me to now have a better flowing syntax for my links:</p>
<div class="codeBlock">
<pre class="csharpcode"> <div id=<span class="str">"menu"</span>>
<ul id=<span class="str">"headerLinks"</span>>
<li><linkTo action=<span class="str">"HomeController"</span> method=<span class="str">"FrontPage()"</span>>home</linkTo></li>
<li><linkTo action=<span class="str">"NewsController"</span> method=<span class="str">"Root()"</span>>news</linkTo></li>
<li><linkTo action=<span class="str">"AboutController"</span> method=<span class="str">"Root()"</span>>about</linkTo></li>
<li><linkTo action=<span class="str">"LoginController"</span> method=<span class="str">"Root()"</span>>login</linkTo></li>
</ul>
</div></pre>
</div> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-54038869468205659652011-08-25T07:29:00.001+01:002011-08-25T12:23:23.939+01:00How I customised my fubuMVC routes with a url policy<p>I’m currently re-writing my existing application so that it uses fubuMVC and I shared my experiences in how easy it was to <a href="http://www.beingnew.net/2011/08/how-i-got-started-with-fubumvc.html">get started with fubuMVC</a> – this is the second post in a series on fubuMVC in action.</p> <p>I’m migrating the static pages for my website – the home, news, about pages – and I now have an opportunity to change a few things around. <br />One of the things I was doing when using ASP.NET MVC was to have a HomeController that had actions for these pages:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> HomeController : Controller
{
<span class="kwrd">public</span> ActionResult Index()
{
<span class="kwrd">return</span> View();
}
<span class="kwrd">public</span> ActionResult About()
{
<span class="kwrd">return</span> View();
}
<span class="kwrd">public</span> ActionResult News()
{
<span class="kwrd">return</span> View();
}
}</pre>
</div>
<p>This resulted in urls of “home/index”, “home/about”, “home/news”.</p>
<p>So the first thing I want to change is to ditch the “home” part of the url – for the first one, I’ve already declared my HomeController.FrontPage() method as the root url for my website in my FubuRegistry, so that is taken care of.
<br />I now have the other two to tackle so I want these to be simply “/news” and “/about”.</p>
<p>Here comes the fubu power because I am now free to think of <strong>any convention I like</strong> to make this happen – once I’ve come up with one, I can declare that convention in my own FubuRegistry.</p>
<p>I decide that for my project, any action that has a method called “Root” will have a custom url that ignores the method and just uses the prefix name of the controller.</p>
<p>To enable this, I’m going to define a custom IUrlPolicy (to read more about policies, see Josh Arnold’s post on <a href="http://lostechies.com/josharnold/2011/07/09/patterns-of-compositional-architecture-policies/">compositional patterns - policies</a>).</p>
<p>The IUrlPolicy interface contract is:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IUrlPolicy
{
<span class="kwrd">bool</span> Matches(ActionCall call, IConfigurationObserver log);
IRouteDefinition Build(ActionCall call);
}</pre>
</div>
<p>Being always test driven, I define my tests for the matching process first using Machine.Specifications :</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(EnsureControllersCanHaveARootUrlPolicy))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_matching_against_a_non_root_action_call
{
Establish context = () =>
{
_actionCall = ActionCall.For<HomeController>(h => h.FrontPage());
_log = <span class="kwrd">new</span> Mock<IConfigurationObserver>();
_matches = <span class="kwrd">true</span>;
_urlPolicy = <span class="kwrd">new</span> EnsureControllersCanHaveARootUrlPolicy();
};
Because of = () => _matches = _urlPolicy.Matches(_actionCall, _log.Object);
It should_not_match = () => _matches.ShouldBeFalse();
<span class="kwrd">private</span> <span class="kwrd">static</span> EnsureControllersCanHaveARootUrlPolicy _urlPolicy;
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> _matches;
<span class="kwrd">private</span> <span class="kwrd">static</span> ActionCall _actionCall;
<span class="kwrd">private</span> <span class="kwrd">static</span> Mock<IConfigurationObserver> _log;
}
[Subject(<span class="kwrd">typeof</span>(EnsureControllersCanHaveARootUrlPolicy))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_matching_against_a_root_action_call
{
Establish context = () =>
{
_actionCall = ActionCall.For<NewsController>(h => h.Root());
_log = <span class="kwrd">new</span> Mock<IConfigurationObserver>();
_urlPolicy = <span class="kwrd">new</span> EnsureControllersCanHaveARootUrlPolicy();
};
Because of = () => _matches = _urlPolicy.Matches(_actionCall, _log.Object);
It should_match = () => _matches.ShouldBeTrue();
<span class="kwrd">private</span> <span class="kwrd">static</span> EnsureControllersCanHaveARootUrlPolicy _urlPolicy;
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> _matches;
<span class="kwrd">private</span> <span class="kwrd">static</span> ActionCall _actionCall;
<span class="kwrd">private</span> <span class="kwrd">static</span> Mock<IConfigurationObserver> _log;
}</pre>
</div>
<p>So here I’m writing specifications for my new class “EnsureControllersCanHaveARootUrlPolicy” and the first should not match on an action call to the HomeController’s FrontPage method.
<br />The second should match on an action call to a new class, NewsController, and its new Root method that meets my convention.
<br />Here’s the implementation for this:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> EnsureControllersCanHaveARootUrlPolicy : IUrlPolicy
{
<span class="kwrd">public</span> <span class="kwrd">bool</span> Matches(ActionCall call, IConfigurationObserver log)
{
<span class="kwrd">return</span> call.Method.Name.EndsWith(<span class="str">"Root"</span>);
}
}</pre>
</div>
<p>My next specification is for the building of the route definition when the policy executes:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(EnsureControllersCanHaveARootUrlPolicy))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_building_a_route_definition
{
Establish context = () =>
{
_actionCall = ActionCall.For<NewsController>(h => h.Root());
_urlPolicy = <span class="kwrd">new</span> EnsureControllersCanHaveARootUrlPolicy();
};
Because of = () =>
_routeDefinition = _urlPolicy.Build(_actionCall);
It should build_the_route_from_the_prefix_of_the_controller = () =>
_routeDefinition.Pattern.ShouldEqual(<span class="str">"news"</span>);
<span class="kwrd">private</span> <span class="kwrd">static</span> EnsureControllersCanHaveARootUrlPolicy _urlPolicy;
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> _matches;
<span class="kwrd">private</span> <span class="kwrd">static</span> ActionCall _actionCall;
<span class="kwrd">private</span> <span class="kwrd">static</span> Mock<IConfigurationObserver> _log;
<span class="kwrd">private</span> <span class="kwrd">static</span> IRouteDefinition _routeDefinition;
}</pre>
</div>
<p>When the route definition is required, I want this policy to make sure that “controller” is stripped from the name of the handling type (in this case NewsController) and that the name is in lower case.</p>
<p>Here’s the full implementation of the policy:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> EnsureControllersCanHaveARootUrlPolicy : IUrlPolicy
{
<span class="kwrd">public</span> <span class="kwrd">bool</span> Matches(ActionCall call, IConfigurationObserver log)
{
<span class="kwrd">return</span> call.Method.Name.EndsWith(<span class="str">"Root"</span>);
}
<span class="kwrd">public</span> IRouteDefinition Build(ActionCall call)
{
var newRoute = call.HandlerType.Name.Replace(<span class="str">"Controller"</span>, <span class="kwrd">string</span>.Empty).ToLower();
var routeDefinition = call.ToRouteDefinition();
routeDefinition.Append(newRoute);
<span class="kwrd">return</span> routeDefinition;
}
}</pre>
</div>
<p>The next thing to do is to create a new view model in the NewsController and hook it up to my old news spark view that I’m migrating across. Here’s the news controller:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> NewsController
{
<span class="kwrd">public</span> NewsViewModel Root()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> NewsViewModel();
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> NewsViewModel
{
}</pre>
</div>
<p>In my spark view, I ensure that the page is using this new output view model:</p>
<div class="codeBlock">
<pre class="csharpcode"><viewdata model=<span class="str">"Xerces.Web.Core.Home.NewsViewModel"</span> /></pre>
</div>
<p>Last thing to do is declare this policy in my own fubu registry :</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
<span class="kwrd">public</span> XercesFubuRegistry()
{
IncludeDiagnostics(<span class="kwrd">true</span>);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes.HomeIs<HomeController>(c => c.FrontPage())
.IgnoreControllerNamespaceEntirely()
.UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>(); <-- <span class="kwrd">new</span> line
<span class="kwrd">this</span>.UseSpark();
Views.TryToAttachWithDefaultConventions();
Output.ToJson.WhenCallMatches(action => action.Returns<AjaxResponse>());
}
}</pre>
</div>
<p>I already have the start url of my web application pointed to the “_fubu/actions” url so that it goes straight to diagnostics, so I now debug the application to examine my new action set up:</p>
<p><a href="http://lh6.ggpht.com/-y6nQkOeqnGU/TlJgBOij3rI/AAAAAAAAAKE/XSPqCYnOfh4/s1600-h/urlpolicy3.png"><img style="background-image: none; border-right-width: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="urlpolicy" border="0" alt="urlpolicy" src="http://lh5.ggpht.com/-DidOnN_ZE_Q/TlJgByuDJwI/AAAAAAAAAKI/67JpawSGlXo/urlpolicy_thumb1.png?imgmax=800" width="731" height="262" /></a></p>
<p>I now have a new action registered for NewsController.Root() that points to my news.spark view and has a route of “news”. In the bottom left corner is the hover on the news link, showing that it points to “/news”.</p>
<p>As you can see it is very easy to customise your MVC application and have it work exactly how you want with the powerful hooks that fubuMVC has provided.
<br />In this convention I had decided to have a HomeController.FrontPage(), NewsController.Root(), AboutController.Root() – this is my personal preference so they are isolated and quite easy to remember that they will generate a root url.</p>
<p>However, let us look at an alternative just to show how customisable these rules are.. what if I had wanted to stick to my original ASP.NET MVC layout where the HomeController had methods called News() and About()?</p>
<p>If I say that my new convention is any method on the HomeController that is not FrontPage() has the method name used as the root url, this should give me the same output.
<br />I would end up with something like:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> EnsureHomeControllerCanGenerateRootUrlsPolicy : IUrlPolicy
{
<span class="kwrd">public</span> <span class="kwrd">bool</span> Matches(ActionCall call, IConfigurationObserver log)
{
<span class="kwrd">return</span> call.HandlerType == <span class="kwrd">typeof</span>(HomeController)
&& call.Method.Name.ToLower() != <span class="str">"frontpage"</span>;
}
<span class="kwrd">public</span> IRouteDefinition Build(ActionCall call)
{
var newRoute = call.Method.Name.ToLower();
var routeDefinition = call.ToRouteDefinition();
routeDefinition.Append(newRoute);
<span class="kwrd">return</span> routeDefinition;
}
}</pre>
</div>
<p>This time I would be using the HandlerType of the action call and if it is the HomeController and the action call method is not the FrontPage method, then it would be eligible to build a route definition and it would use the lowercase name for that.</p>
<p>So that’s how I customised my routes with a url policy – oh and did I say that fubuMVC is great?!</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com1tag:blogger.com,1999:blog-990393702029999754.post-90756048632889653542011-08-23T07:24:00.019+01:002012-03-04T20:37:24.716+00:00My experiences with fubuMVC<p>I’m currently writing a series on my experiences using the excellent fubuMVC open source framework and thought I’d list the topics I’m writing about here.</p>
<p>It's a "How I..." series because fubuMVC allows you to customise and take control anyway <b>you</b> want.<br/>It's amazing.</p><p>Here are all the posts in this series:</p> <ul class="post-list"> <li><a href="http://www.beingnew.net/2011/08/how-i-got-started-with-fubumvc.html">How I got started with fubuMVC</a> </li> <li><a href="http://www.beingnew.net/2011/08/how-i-customised-my-fubumvc-routes-with.html">How I customised my fubuMVC routes with a url policy</a></li>
<li><a href="http://www.beingnew.net/2011/08/how-i-link-to-my-fubumvc-actions.html">How I link to my fubuMVC actions</a></li>
<li><a href="http://www.beingnew.net/2011/09/how-i-permanently-redirect-using.html">How I permanently redirect with fubuMVC behaviours</a></li> <li><a href="http://www.beingnew.net/2011/09/how-i-improved-my-fubumvc-redirection.html">How I improved my fubuMVC redirect behaviour</a></li> <li><a href="http://www.beingnew.net/2011/09/how-i-removed-magic-strings-from-my.html">How I removed magic strings from my fubuMVC redirection policy</a></li>
<li><a href="http://www.beingnew.net/2011/09/how-i-use-nhibernate-with-fubumvc.html">How I use NHibernate with fubuMVC</a></li>
<li><a href="http://www.beingnew.net/2011/10/how-i-register-icontinuationdirector-in.html">How I register the IContinuationDirector in fubuMVC</a></li>
<li><a href="http://www.beingnew.net/2011/10/how-i-authenticate-with-fubumvc.html">How I authenticate using fubuMVC behaviours (part one)</a></li>
<li><a href="http://www.beingnew.net/2011/11/how-i-authenticate-with-fubumvc-part-2.html">How I authenticate using fubuMVC behaviours (part two)</a></li>
<li><a href="http://www.beingnew.net/2012/02/how-i-use-domain-events-with.html">How I use DomainEvents with fubuMVC - part one</a></li>
<li><a href="http://www.beingnew.net/2012/02/how-i-use-domain-events-with-fubumvc.html">How I use DomainEvents with fubuMVC - part two</a></li>
<li><a href="http://www.beingnew.net/2012/03/how-i-limit-my-abstractions-in-fubumvc.html">How I limit my abstractions in fubuMVC</a></li>
<li>How I handle unexpected exceptions using fubuMVC behaviours</li>
</ul>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com1tag:blogger.com,1999:blog-990393702029999754.post-68749987145201512452011-08-20T17:47:00.003+01:002011-10-04T11:09:57.536+01:00How I got started with fubuMVC<p>I’m in the <a href="http://www.beingnew.net/2011/08/my-experiences-with-fubumvc.html">process of re-writing</a> my own production project to use fubuMVC and I wanted to share how easy it was to get started with the framework and use the fubu power to get up and running with very little ceremony.</p> <h2>Step one:</h2> <p>Create a new 4.0 ASP.NET web application and reference the libraries I need to use fubuMVC:</p> <p><a href="http://lh3.ggpht.com/-SEs4LNLTDR4/Tk_lDijNAJI/AAAAAAAAAJs/xQqFQHS6v4w/s1600-h/xercesweb%25255B7%25255D.png"><img style="background-image: none; border-right-width: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="xercesweb" border="0" alt="xercesweb" src="http://lh6.ggpht.com/-azH1negqBEY/Tk_lD3hDx-I/AAAAAAAAAJw/hOhOauzoDUY/xercesweb_thumb%25255B5%25255D.png?imgmax=800" width="312" height="246" /></a></p> <h2>Step two:</h2> <p>In the Global.asax.cs start wiring up the FubuApplication. </p> <p>To do this, in my application start method I hook up my own (currently empty) implementation of FubuRegistry, with a new structure map container and Bootstrap using the routes from the route table.</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">protected</span> <span class="kwrd">void</span> Application_Start(<span class="kwrd">object</span> sender, EventArgs e)
{
FubuApplication
.For<XercesFubuRegistry>()
.StructureMap(() => <span class="kwrd">new</span> Container())
.Bootstrap(RouteTable.Routes);
}
<span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
}</pre>
</div>
<h2>Step three:</h2>
<p>Declare the setup of my FubuRegistry</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> XercesFubuRegistry : FubuRegistry
{
<span class="kwrd">public</span> XercesFubuRegistry()
{
IncludeDiagnostics(<span class="kwrd">true</span>);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes.HomeIs<HomeController>(c => c.FrontPage())
.IgnoreControllerNamespaceEntirely();
<span class="kwrd">this</span>.UseSpark();
Views.TryToAttachWithDefaultConventions();
}
}</pre>
</div>
<p>I’m including diagnostics so that I can use fubuMVC’s excellent diagnostic features to help me visualise how the code in the site works for each url as I build it (more on this below).</p>
<p>I’ve decided to stick with a “controller actions” concept so I tell fubuMVC that actions are those classes that end with “Controller”.</p>
<p>I declare my home route as the HomeController (which I’ve yet to create) and declared a method on there called FrontPage.
<br />I also tell fubuMVC to ignore the namespaces of my controller class when building the routes.</p>
<p>I’m using the spark view engine and I tell fubuMVC to wire up the views with default conventions – here it will use a number of ways to match the view based on the model returned by the FrontPage method – I’m essentially wanting it to look for the only concrete implementation of that type.</p>
<h2>Step four:</h2>
<p>Create the controller – it does not take any parameters in the front page method and it returns a HomeViewModel.
<br />This is a zero model in, one model out concept that fubuMVC is very opinionated on (along with the one model in, one model out concept).</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> HomeController
{
<span class="kwrd">public</span> HomeViewModel FrontPage()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> HomeViewModel();
}
}
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeViewModel
{
}</pre>
</div>
<h2>Step five:</h2>
<p>Create my view.</p>
<p>I’m actually importing the code from my existing home page but now I can call this view whatever I want rather than relying on naming conventions and location matching – one of the beautiful things about fubuMVC is that I am free to put my actions and views <strong>anywhere I like</strong> and it will hook them up based on the types concerned – a HomeController type for the action and a view that uses the HomeViewModel for my output.</p>
<p>My spark view, frontpage.spark, now uses the HomeViewModel:</p>
<div class="codeBlock">
<pre class="csharpcode"><viewdata model=<span class="str">"Xerces.Web.Core.Home.HomeViewModel"</span> />
<div id=<span class="str">"imageContainer"</span>>
...etc</pre>
</div>
<p>Here’s a picture of my web application illustrating that I can have the action and views where I want:</p>
<p><a href="http://lh6.ggpht.com/-oxwYPBFxbxQ/Tk_lEdRRHuI/AAAAAAAAAJ0/ThWz0g7C0K0/s1600-h/xercesweb2%25255B4%25255D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="xercesweb2" border="0" alt="xercesweb2" src="http://lh5.ggpht.com/-Wr_3U3BZQtA/Tk_lE5qe3LI/AAAAAAAAAJ4/FBQD7AsDgsM/xercesweb2_thumb%25255B2%25255D.png?imgmax=800" width="312" height="311" /></a></p>
<h2>Step six:</h2>
<p>Confirm that it all works!</p>
<p>I set the start page of my web application to “_fubu/actions” – this points to one of the diagnostics pages for my fubuMVC application – and I debug the website:</p>
<p><a href="http://lh5.ggpht.com/-IQA3eToFyvI/Tk_lFbJocgI/AAAAAAAAAJ8/HMJWMFLQDJk/s1600-h/xercesweb3%25255B7%25255D.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="xercesweb3" border="0" alt="xercesweb3" src="http://lh5.ggpht.com/-NC3YS24FNTM/Tk_lF8HKYrI/AAAAAAAAAKA/eTrMomwdLfE/xercesweb3_thumb%25255B3%25255D.png?imgmax=800" width="756" height="163" /></a></p>
<p>The fubuMVC diagnostics shows me that I have one registered action that is the HomeController I set up. The action returns a HomeViewModel and the view it has found that ties up with this output model is my frontpage.spark view.</p>
<p>I can click on the “(default)” route to take me to the website and my home page loads!
<br /><em>(note that using the diagnostics as my start page is a personal preference and isn’t required)</em></p>
<p>This was <strong>very easy</strong> and fubuMVC is doing a lot of the work for me so that out of the box it just makes my life simple.
<br />I’m going to love working with this framework.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com4tag:blogger.com,1999:blog-990393702029999754.post-10982921031604307592010-10-28T08:17:00.001+01:002010-10-28T08:17:51.558+01:00verifying my robot manipulation<p>In this post I'm going to wrap up this <a title="implementing a robocode robot" href="http://www.beingnew.net/2010/08/implementing-robocode-robot.html">second robocode series</a> by verifying that my new design works the way I want it to and hopefully showing that all this work has paid off.</p> <p>To review, here's a brief description of my design:</p> <ul> <li>the run method is called on my robot by robocode</li> <li>my robot first retrieves a robot engine from a service locator and passes itself to the engine</li> <li>the run infinite loops begins and there is only one thing to do each loop: the robot asks the robot engine to ensure the world state is up to date</li> <li>the robot engine processes any pending world state updates that have been stored by events</li> <li>if there are no updates, this process finishes until the next loop</li> <li>otherwise, it pushes the updated world state to each context translator</li> <li>the context translators convert the world state into a new state for that bounded context</li> <li>the observable situation (using rx observables) is updated</li> <li>any observers with subscriptions that meet the new state come into effect</li> </ul> <p>I have two observers at present, one in the decision context to write statistics out for my acceptance test, showing that the robot was not disabled at the start of the battle (and there are no terminal exceptions as a result of new code). <br />The second is a manipulation observer that looks for enemies when we have no focus.</p> <p>As I <a title="working with robocode and rx framework" href="http://www.beingnew.net/2010/08/working-with-robocode-and-rx-framework.html">cannot debug my robot</a> through visual studio, I have littered areas of my code with WriteDebugMessage statements for this exercise so I can watch the turn snapshot window.</p> <p>So to begin, here's the battlefield:</p> <p><a href="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjdfVrJFI/AAAAAAAAAIo/3qupu9pWSjY/s1600-h/Verifying1%5B4%5D.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="277" alt="Verifying1" src="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjeYE3IDI/AAAAAAAAAIs/NTpTIRb1_SQ/Verifying1_thumb%5B2%5D.png?imgmax=800" width="278" border="0" /></a> </p> <p>At the start of the battle, there's not much activity yet on turn 0 as expected:</p> <p><a href="http://lh3.ggpht.com/_Osl8Rl-slhQ/TMkjerdrVYI/AAAAAAAAAIw/GKpHbh5pLqA/s1600-h/verifying2%5B5%5D.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="78" alt="verifying2" src="http://lh3.ggpht.com/_Osl8Rl-slhQ/TMkjfZDs4DI/AAAAAAAAAI0/12PJSjgiD5I/verifying2_thumb%5B3%5D.png?imgmax=800" width="479" border="0" /></a> </p> <p>But moving onto turn 1 and there's a lot going on:</p> <p><a href="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjgMbk2GI/AAAAAAAAAI4/vjmKKFddxSU/s1600-h/verifying3%5B10%5D.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="147" alt="verifying3" src="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjgr0GDuI/AAAAAAAAAI8/ohxhyR_QO4s/verifying3_thumb%5B6%5D.png?imgmax=800" width="698" border="0" /></a> </p> <p>The OnStatus event has been called and the robot is about to publish the world state update to the robot engine as a pending update. <br />The world state update is processed by the run loop and the robot engine starts pushing the state update to the bounded contexts.</p> <p>The decision context translator gets the first update and updates the decision state keeper. This publishes the decision state via an observable situation. My only observer in this context waits for turn fifty, so it is not yet called.</p> <p>The manipulation context translator now gets an update and this flows through to the manipulation state keeper. Again, the observable situation for this bounded context is updated and we do have an observer subscribing to when there is no focus (and there will always be no focus at present). <br />This "we have no focus observer" is responsible for pushing a command to the robot via the ImARobot interface to look for enemies.</p> <p>Turn two occurs and we have some activity! The robot has issued a TurnRadarRight(360) and this radar scan has begun.</p> <p><a href="http://lh3.ggpht.com/_Osl8Rl-slhQ/TMkjhRio9-I/AAAAAAAAAJA/0CROnUDyqmc/s1600-h/verifying4%5B4%5D.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="276" alt="verifying4" src="http://lh4.ggpht.com/_Osl8Rl-slhQ/TMkjiUQZ-lI/AAAAAAAAAJE/v33-wpj5jic/verifying4_thumb%5B2%5D.png?imgmax=800" width="274" border="0" /></a> </p> <p>For the next few turns, the turn snapshot window is a little quieter as the blocking call (because this is a standard robot) takes effect. <br />What is interesting is that as the OnStatus call still takes place, the world state updates are stored in the robot engine:</p> <p><a href="http://lh4.ggpht.com/_Osl8Rl-slhQ/TMkji-hnI0I/AAAAAAAAAJI/pdyTBpTfKGE/s1600-h/verifying5%5B3%5D.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="94" alt="verifying5" src="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjjzOdEBI/AAAAAAAAAJM/2pcmnQBTYds/verifying5_thumb%5B1%5D.png?imgmax=800" width="697" border="0" /></a> </p> <p>So all of these stay as pending updates in the robot engine until the robot run loops kicks in again and we can begin processing again. This is exactly what the design called for and I'm very pleased with that.</p> <p> When the radar scan is over, it all kicks in again, on turn ten:</p> <p><a href="http://lh4.ggpht.com/_Osl8Rl-slhQ/TMkjko-AtfI/AAAAAAAAAJQ/aeWxyDtVT_I/s1600-h/verifying6%5B3%5D.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="187" alt="verifying6" src="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjlg3yBCI/AAAAAAAAAJU/84U1JrgFtF8/verifying6_thumb%5B1%5D.png?imgmax=800" width="470" border="0" /></a> </p> <p>I still have no focus so the manipulation observer once again issues the look for enemies command:</p> <p><a href="http://lh6.ggpht.com/_Osl8Rl-slhQ/TMkjmiuqHkI/AAAAAAAAAJY/EX2p7pSCiq8/s1600-h/verifying7%5B3%5D.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="261" alt="verifying7" src="http://lh4.ggpht.com/_Osl8Rl-slhQ/TMkjnoYkiuI/AAAAAAAAAJc/E-TNV8Ahwro/verifying7_thumb%5B1%5D.png?imgmax=800" width="260" border="0" /></a> </p> <p>So it all looks to be working the way I wanted it to. I have a domain driven design model that is completely independent from the robocode library using the adapter robot to act as the anti corruption layer. <br />I have a command being pushed to the robot and my efforts seem to have paid off.</p> <p>If you have been following this series, please let me know what you think about my experiments.</p> <p>My next robocode series will look at making the robot do some more interesting things and expanding upon this design.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com1tag:blogger.com,1999:blog-990393702029999754.post-88389547289919235602010-10-26T19:29:00.001+01:002010-10-26T19:29:56.993+01:00manipulating my robocode robot<p>I'm at a stage in my robocode implementation that I can begin to write some more observations and begin manipulating my robot. In this post I'll be:</p> <ul> <li>creating a new observer for when there is no focus </li> <li>issuing instructions to the robot to look for enemies </li> <li>investigating and resolving a stackoverflow exception! </li> <li>finally watching my robot be manipulated for the first time in my domain driven design code. At last! </li> </ul> <p>The observer I'm wanting to begin with is the one that will ensure the robot looks for enemies and will effectively stop the robot being dormant. I therefore want to check if we are focused on anything and if we are not, I want to issue instructions to the robot engine. Here's the specification for this observer:</p> <div class="codeBlock"> <pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(WeHaveNoFocusObserver))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_there_is_no_current_focus
{
Establish context = () =>
{
manipulationState = <span class="kwrd">new</span> ManipulationState { WeAreFocusedOnSomething = <span class="kwrd">false</span> };
manipulationStateEvent = MockRepository.GenerateStub<IEvent<ManipulationState>>();
manipulationStateEvent.Stub(s => s.EventArgs).Return(manipulationState);
manipulationStateObservable = Observable.Return(manipulationStateEvent);
robotEngine = MockRepository.GenerateStub<ImARobotEngine>();
robotEngine.Stub(e => e.IssueInstructionsToRobot(<span class="kwrd">null</span>))
.IgnoreArguments().Do(RecordInstruction);
weHaveNoFocusObserver = <span class="kwrd">new</span> WeHaveNoFocusObserver(robotEngine);
};
Because of = () => weHaveNoFocusObserver.Observe(manipulationStateObservable);
It should_subscribe_to_the_observable_and_recognise_that_we_have_no_focus = () =>
weHaveNoFocusObserver.RecognisedThatWeHaveNoFocus.ShouldBeTrue();
It should_issue_instructions_for_the_robot_engine_to_look_for_enemies = () =>
ShouldHaveIssuedInstruction(x => x.LookForEnemies());
<span class="kwrd">static</span> Action<Action<ImARobot>> RecordInstruction = i =>
instructionSentToRobotEngine = i;
<span class="kwrd">static</span> <span class="kwrd">void</span> ShouldHaveIssuedInstruction(Action<ImARobot> expectedInstruction)
{
var robot = MockRepository.GenerateStub<ImARobot>();
<span class="kwrd">if</span> (instructionSentToRobotEngine != <span class="kwrd">null</span>)
instructionSentToRobotEngine(robot);
robot.AssertWasCalled(expectedInstruction);
}
<span class="kwrd">static</span> ManipulationState manipulationState;
<span class="kwrd">protected</span> <span class="kwrd">static</span> IEvent<ManipulationState> manipulationStateEvent;
<span class="kwrd">protected</span> <span class="kwrd">static</span> IObservable<IEvent<ManipulationState>> manipulationStateObservable;
<span class="kwrd">static</span> WeHaveNoFocusObserver weHaveNoFocusObserver;
<span class="kwrd">static</span> ImARobotEngine robotEngine;
<span class="kwrd">static</span> Action<ImARobot> instructionSentToRobotEngine;
}</pre>
</div>
<p>This specification is very similar to the original start of the battle observer (if you have been following the whole series) which is now removed and replaced by this new manipulation state observer. </p>
<p>Essentially the specification is setting up some manipulation state which shows there is currently nothing in focus and providing this via an observable when it is told to observe.
<br />Then, a robot engine is stubbed and it is set to record any instruction action of type Action<ImARobot> that is sent to it.</p>
<p>Finally I'm then taking the recorded action and manipulating a newly stubbed robot - this way I can determine what the action delegate contains and assert that it was the expected instruction of LookForEnemies().</p>
<p>Here's the implementation to make this pass:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> WeHaveNoFocusObserver : IObserveToManipulate
{
ImARobotEngine robotEngine;
<span class="kwrd">public</span> WeHaveNoFocusObserver(ImARobotEngine robotEngine)
{
<span class="kwrd">this</span>.robotEngine = robotEngine;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Observe(IObservable<IEvent<ManipulationState>> situation)
{
situation.Where(s => s.EventArgs.WeAreFocusedOnSomething == <span class="kwrd">false</span>)
.Subscribe(s =>
{
RecognisedThatWeHaveNoFocus = <span class="kwrd">true</span>;
robotEngine.IssueInstructionsToRobot(r => r.LookForEnemies());
});
}
<span class="kwrd">public</span> <span class="kwrd">bool</span> RecognisedThatWeHaveNoFocus { get; <span class="kwrd">private</span> set; }
}</pre>
</div>
<p>It is now looking very simple for me to add behaviour into my robocode code - the above code now subscribes to when there is no focus and looks for enemies. Here's the code for that LookForEnemies() call that was built in a <a title="making the robocode robot work" href="www.beingnew.net/2010/08/making-robocode-robot-work.html">previous post</a>, and only part of the robot is shown here :</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> SlayerRobot : Robot, ImARobot
{
<span class="kwrd">public</span> <span class="kwrd">void</span> <b style="color: black; background-color: #ffff66">LookForEnemies</b>()
{
TurnRadarRight(360);
}
}</pre>
</div>
<p>This all looks great, but when I run through robocode it completely crashes on me!
<br />A stackoverflow exception is killing the application.</p>
<p>After a little digging it is because I have a circular dependency in the constructor of the ManipulationStateKeeper.
<br />When a robot engine is resolved from the IOC container, it creates a manipulation state keeper and the constructor of this is then asking the service locator to resolve a robot engine; this then creates another manipulation state keeper and so on until it crashes.</p>
<p>The solution is to ensure the service locator caches the resolved robot engine and to then change the ManipulationStateKeeper so that the process of passing the robot engine to the manipulation observers occurs a little later:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ManipulationStateKeeper : StateKeeper<ManipulationState, IObserveToManipulate>
{
<span class="kwrd">public</span> ManipulationStateKeeper(IEnumerable<IObserveToManipulate> observers) :
<span class="kwrd">base</span>(observers)
{
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> ManipulationState EnsureThatStateHasBeenCreated()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> ManipulationState();
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> IObservable<IEvent<ManipulationState>>
EnsureThatTheObservableHasBeenCreated()
{
EnsureThatObserversAreGivenTheRobotEngine();
<span class="kwrd">return</span> Observable.FromEvent<ManipulationState>(
ev => <span class="kwrd">this</span>.StateHasUpdated += ev,
ev => <span class="kwrd">this</span>.StateHasUpdated -= ev);
}
<span class="kwrd">void</span> EnsureThatObserversAreGivenTheRobotEngine()
{
var robotEngine = ServiceLocator.ObtainThePreviouslyRequestedRobotEngine();
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> observers)
{
observer.UseTheRobotEngine(robotEngine);
}
}
}</pre>
</div>
<p>Now when I run my code in a battle, my robot is finally manipulated and scans for enemies!</p>
<p><a href="http://lh5.ggpht.com/_Osl8Rl-slhQ/TMceHGrZi-I/AAAAAAAAAIg/_N0VGTOdFPU/s1600-h/MyRobotIsManipulated%5B4%5D.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="212" alt="MyRobotIsManipulated" src="http://lh3.ggpht.com/_Osl8Rl-slhQ/TMceIsyZf5I/AAAAAAAAAIk/qkgiWL9WP0o/MyRobotIsManipulated_thumb%5B2%5D.png?imgmax=800" width="284" border="0" /></a></p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-82979164541672264482010-10-18T08:22:00.001+01:002010-10-18T08:22:12.753+01:00making manipulation possible for my robocode implementation<p>More robocode again and I'm attempting to introduce an observer that will ensure my robot looks for enemies at the start of the battle, replacing the one I have discarded since I went down the domain driven route. At the moment, my robot is inanimate, so it is essential I get some manipulation in place.</p> <p>Here's what I look at in this post:</p> <ul> <li>the creation of a new manipulation state keeper using the generic state keeper </li> <li>implement the context translator to turn the world state into the manipulation state </li> <li>look at obtaining the robot engine from the service locator </li> <li>pass this robot engine to all manipulation observers </li> </ul> <p>So I start with the creation of a new manipulation state keeper and using the generic state keeper from my last post, it should be very easy to manage manipulation state and the observable situation. I'll start with a specification for my manipulation state keeper in the new manipulation namespace:</p> <div class="codeBlock"> <pre class="csharpcode"><span class="kwrd">namespace</span> Specifications.Model.Manipulation
{
[Subject(<span class="kwrd">typeof</span>(ManipulationStateKeeper))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_provided_with_a_state_update
{
Establish context = () =>
{
manipulationObserver = MockRepository.GenerateStub<IObserverToManipulate>();
manipulationStateKeeper = <span class="kwrd">new</span> ManipulationStateKeeper(
<span class="kwrd">new</span> List<IObserverToManipulate> {manipulationObserver});
manipulationStateKeeper.Situation.Subscribe(s =>
{
observedManipulationState = s.EventArgs;
});
manipulationStateUpdate = s => s.WeAreFocusedOnAnything = <span class="kwrd">true</span>;
};
Because of = () =>
manipulationStateKeeper.UpdateState(manipulationStateUpdate);
It should_update_the_situation_observable = () =>
observedManipulationState.ShouldNotBeNull();
It should_have_the_correct_manipulation_state_after_the_update = () =>
observedManipulationState.WeAreFocusedOnAnything.ShouldBeTrue();
<span class="kwrd">static</span> IObserverToManipulate manipulationObserver;
<span class="kwrd">static</span> ManipulationStateKeeper manipulationStateKeeper;
<span class="kwrd">static</span> ManipulationState observedManipulationState;
<span class="kwrd">static</span> Action<ManipulationState> manipulationStateUpdate;
}
}</pre>
</div>
<p>Implementing this is very easy now that most of the behaviour is in the base generic state keeper:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ManipulationStateKeeper : StateKeeper<ManipulationState, IObserverToManipulate>
{
<span class="kwrd">public</span> ManipulationStateKeeper(IEnumerable<IObserverToManipulate> observers) :
<span class="kwrd">base</span>(observers)
{
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> ManipulationState EnsureThatStateHasBeenCreated()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> ManipulationState();
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> IObservable<IEvent<ManipulationState>>
EnsureThatTheObservableHasBeenCreated()
{
<span class="kwrd">return</span> Observable.FromEvent<ManipulationState>(
ev => <span class="kwrd">this</span>.StateHasUpdated += ev,
ev => <span class="kwrd">this</span>.StateHasUpdated -= ev);
}
}</pre>
</div>
<p>The next thing to write is my context translator - this will push the state from the world state into my manipulation state. At the moment I have no state to push, so this is going to be the bare bones implementation for the time being:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(ManipulationContextTranslator))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_publishing_a_state_change
{
Establish context = () =>
{
worldState = MockRepository.GenerateStub<IWorldState>();
manipulationStateUpdater = MockRepository.GenerateStub<IUpdateManipulationState>();
manipulationContextTranslator =
<span class="kwrd">new</span> ManipulationContextTranslator(manipulationStateUpdater);
};
Because of = () => manipulationContextTranslator.PublishAStateChange(worldState);
It should_update_state_via_the_manipulation_state_updater = () =>
manipulationStateUpdater.AssertWasCalled(m =>
m.UpdateState(Arg<Action<ManipulationState>>.Is.NotNull));
<span class="kwrd">static</span> ManipulationContextTranslator manipulationContextTranslator;
<span class="kwrd">static</span> IUpdateState<ManipulationState> manipulationStateUpdater;
<span class="kwrd">static</span> IWorldState worldState;
}</pre>
</div>
<p>This specification ensures that the manipulation state keeper is sent an action to update the manipulation state. This will then fire the event and thus the situation observable. Here's the implementation for now to meet this specification:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ManipulationContextTranslator : IContextTranslator
{
IUpdateState<ManipulationState> manipulationStateUpdater;
<span class="kwrd">public</span> ManipulationContextTranslator(IUpdateState<ManipulationState>
manipulationStateUpdater)
{
<span class="kwrd">this</span>.manipulationStateUpdater = manipulationStateUpdater;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> PublishAStateChange(IWorldState worldState)
{
manipulationStateUpdater.UpdateState(m => { });
}
}</pre>
</div>
<p>Next, I want to revisit the state keeper - when it is created, I want it to to have a copy of the robot engine so that it can pass it to all the manipulation observers. They will then be able to issue manipulation commands appropriately.</p>
<p>Unfortunately, if it comes in on the constructor then Autofac gives ma a circular dependency problem as the robot engine is at the root of all my dependency resolution already.
<br />So how should I provide this via the service locator? This is currently an instance class that the robot itself creates and uses to resolve the engine and thus hook into IOC and the resolving of all dependencies when robocode activates the robot.
<br />I'll have to have a static that returns the robot engine and though this is not ideal, it will serve my needs for the time being until I come up with a better plan.</p>
<p>There's one problem though, how do I test that the state keeper obtains the robot engine via a new static method or member?  Using delegates, I should be able to sort this out. So first, let me go back to the service locator specs and add a second specification:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> when_told_to_provide_a_robot_engine
{
Establish context = () => serviceLocator = <span class="kwrd">new</span> ServiceLocator();
Because of = () => robotEngine = serviceLocator.ProvideRobotEngine();
It should_return_a_valid_robot_engine = () =>
robotEngine.ShouldNotBeNull();
It should_ensure_we_are_able_to_obtain_the_same_robot_engine_by_another_route = () =>
ServiceLocator.ObtainThePreviouslyRequestedRobotEngine().ShouldEqual(robotEngine);
<span class="kwrd">static</span> ILocateServices serviceLocator;
<span class="kwrd">static</span> ImARobotEngine robotEngine;
}</pre>
</div>
<p>I have a new specification here that ensures that when a robot engine is obtained statically from the service, that it is the same robot engine instance that the robot obtains from the instance method ProvideRobotEngine().
<br />Here's the implementation for that:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ServiceLocator : ILocateServices
{
<span class="kwrd">static</span> IContainer _container;
<span class="kwrd">public</span> ServiceLocator()
{
RegisterEverything();
}
<span class="kwrd">void</span> RegisterEverything()
{
var builder = <span class="kwrd">new</span> ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsImplementedInterfaces();
builder.RegisterType<RobotEngine>().As<ImARobotEngine>().SingleInstance();
_container = builder.Build();
}
<span class="kwrd">public</span> ImARobotEngine ProvideRobotEngine()
{
<span class="kwrd">return</span> _container.Resolve<ImARobotEngine>();
}
<span class="kwrd">public</span> <span class="kwrd">static</span> Func<ImARobotEngine> ObtainThePreviouslyRequestedRobotEngine =
() => _container.Resolve<ImARobotEngine>();
}</pre>
</div>
<p>I now have the robot engine registered as a single instance in Autofac and the delegate at the foot of the class ensures the same robot engine can be provided. I can also use this as a hook for testing the manipulation state keeper:</p>
<div class="codeBlock">
<pre class="csharpcode"> [Subject(<span class="kwrd">typeof</span>(ManipulationStateKeeper))]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_created
{
Establish context = () =>
{
firstManipulationObserver = MockRepository.GenerateStub<IObserveToManipulate>();
secondManipulationObserver = MockRepository.GenerateStub<IObserveToManipulate>();
robotEngine = MockRepository.GenerateStub<ImARobotEngine>();
ServiceLocator.ObtainThePreviouslyRequestedRobotEngine = () => robotEngine;
};
Because of = () => manipulationStateKeeper =
<span class="kwrd">new</span> ManipulationStateKeeper(<span class="kwrd">new</span> List<IObserveToManipulate>
{ firstManipulationObserver, secondManipulationObserver });
It should_pass_the_robot_engine_from_the_service_locator_to_the_first_observer =
() => firstManipulationObserver.AssertWasCalled(o => o.UseTheRobotEngine(robotEngine));
It should_pass_the_robot_engine_from_the_service_locator_to_the_second_observer =
() => secondManipulationObserver.AssertWasCalled(o => o.UseTheRobotEngine(robotEngine));
<span class="kwrd">static</span> ManipulationStateKeeper manipulationStateKeeper;
<span class="kwrd">static</span> IObserveToManipulate firstManipulationObserver;
<span class="kwrd">static</span> IObserveToManipulate secondManipulationObserver;
<span class="kwrd">static</span> ImARobotEngine robotEngine;
}</pre>
</div>
<p>In the context I am replacing the delegate on the service locator so that it returns a stubbed robot engine.
<br />Then I can observe that is passes this robot engine to each observer.
<br />Here's the result:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> ManipulationStateKeeper : StateKeeper<ManipulationState, IObserveToManipulate>
{
<span class="kwrd">public</span> ManipulationStateKeeper(IEnumerable<IObserveToManipulate> observers)
: <span class="kwrd">base</span>(observers)
{
var robotEngine = ServiceLocator.ObtainThePreviouslyRequestedRobotEngine();
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> observers)
{
observer.UseTheRobotEngine(robotEngine);
}
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> ManipulationState EnsureThatStateHasBeenCreated()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> ManipulationState();
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> IObservable<IEvent<ManipulationState>>
EnsureThatTheObservableHasBeenCreated()
{
<span class="kwrd">return</span> Observable.FromEvent<ManipulationState>(
ev => <span class="kwrd">this</span>.StateHasUpdated += ev,
ev => <span class="kwrd">this</span>.StateHasUpdated -= ev);
}
}
<span class="kwrd">public</span> <span class="kwrd">interface</span> IObserveToManipulate : IContextObserver<ManipulationState>
{
<span class="kwrd">void</span> UseTheRobotEngine(ImARobotEngine robotEngine);
}</pre>
</div>
<p>This hasn't been an ideal situation as I now have a public static delegate member on my service locator and this abstraction is now leaking, but I spent a long time trying to find a solution to the circular dependency issue, and this is the only real alternative I have at present.
<br />In my next post I'll finally be writing the observer and making some commands to my robot.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-90780183424471338632010-10-11T07:41:00.002+01:002010-10-11T07:52:11.563+01:00the generic state keeper and the observer<p>In my <a href="http://www.beingnew.net/2010/10/revisiting-robocode-state-with-generics.html">previous post</a> I explored the state keepers for my <a href="http://www.beingnew.net/2010/08/implementing-robocode-robot.html">robocode implementation</a> and had a working generic state keeper. <br />However, there was a problem that this new design created and I'm going to discuss this by looking at my existing observer. Here's the original code for that observer before the change:</p> <div class="codeBlock"> <pre class="csharpcode"><span class="kwrd">namespace</span> TeamSlayer.Model.Decision
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> IObserveToMakeDecisions
{
<span class="kwrd">void</span> Observe(IKeepDecisionState decisionStateKeeper);
}
<span class="kwrd">public</span> <span class="kwrd">class</span> BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
{
<span class="kwrd">readonly</span> IManageStatistics statisticsManager;
<span class="kwrd">public</span> BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
{
<span class="kwrd">this</span>.statisticsManager = statisticsManager;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Observe(IKeepDecisionState decisionStateKeeper)
{
decisionStateKeeper.Situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
.Subscribe(s =>
{
ReachedTurnFifty = <span class="kwrd">true</span>;
statisticsManager.WriteStatistics(ReachedTurnFifty);
});
}
<span class="kwrd">public</span> <span class="kwrd">bool</span> ReachedTurnFifty { get; <span class="kwrd">private</span> set; }
}
}</pre>
</div>
<p>To recap, this code is in the decision bounded context and namespace and the observer is presented with the decision state keeper when asked to observe; the observer then subscribes to the observable situation.</p>
<p>Here's the new code once the generic state keeper is in place:</p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">using</span> TeamSlayer.Model.World;
<span class="kwrd">namespace</span> TeamSlayer.Model.Decision
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> IObserveToMakeDecisions : IContextObserver<DecisionState>
{
}
<span class="kwrd">public</span> <span class="kwrd">class</span> BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
{
<span class="kwrd">readonly</span> IManageStatistics statisticsManager;
<span class="kwrd">public</span> BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
{
<span class="kwrd">this</span>.statisticsManager = statisticsManager;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Observe(IKeepState<DecisionState> decisionStateKeeper)
{
decisionStateKeeper.Situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
.Subscribe(s =>
{
ReachedTurnFifty = <span class="kwrd">true</span>;
statisticsManager.WriteStatistics(ReachedTurnFifty);
});
}
<span class="kwrd">public</span> <span class="kwrd">bool</span> ReachedTurnFifty { get; <span class="kwrd">private</span> set; }
}
}</pre>
</div>
<p>The decision observer interface now has no implementation and simply declares the state type for the context observer. This is great as it effectively acts as a translator, abstracting the world namespace away from anything in the decision context - I'm very happy with this.</p>
<p>The observer is now presented with a generic state keeper via the IKeepState<State> interface and this <strong>I do not like</strong> - the using statement shown at the top clearly shows I'm violating my domain driven design concept of a bounded context that I originally wanted.
<br />I now have to think about how to address this and after some tinkering I come to the conclusion that the Situation observable is effectively typed by the decision state keeper, so I should be able to use this. </p>
<p>To get this to work though, I have to change the generic state keeper around - I'm going to omit the specifications for brevity once again as this takes a bit of explaining. First, I change the contract of the context observer to use the observable situation instead of the state keeper itself and replace the Situation property in the observer call in place of sending "this" into the method call:</p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">namespace</span> TeamSlayer.Model.World
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> IContextObserver<State>
{
<span class="kwrd">void</span> Observe(IObservable<IEvent<State>> situation);
}
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> Observer : IContextObserver<State>
<span class="kwrd">where</span> State : EventArgs
{
<span class="rem">// rest of the class left out for this illustration</span>
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();
<span class="kwrd">public</span> IObservable<IEvent<State>> Situation
{
get
{
<span class="kwrd">return</span> situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
}
}
<span class="kwrd">public</span> StateKeeper(IEnumerable<Observer> observers)
{
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> observers)
{
observer.Observe(<font color="red">Situation</font>);
}
}
}
}</pre>
</div>
<p>I've highlighted a problem in red that this change presents - my situation property calls out to a derived implementation of this class through an abstract method and this is not a good situation. This is the same problem I outlined in my last post where we would be calling into a derived class whilst in the base constructor and we will not be able to guarantee the derived class is initialised properly.</p>
<p>So to fix this, I'm going to have to pull the observer registration to when the update change is pushed to the state keeper:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> Observer : IContextObserver<State>
<span class="kwrd">where</span> State : EventArgs
{
IEnumerable<Observer> observers;
IObservable<IEvent<State>> situation;
<span class="kwrd">bool</span> weHaveNotYetShownObserversOurSituation = <span class="kwrd">true</span>;
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = EnsureThatStateHasBeenCreated() );
}
}
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> State EnsureThatStateHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<State> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
<span class="kwrd">if</span> (weHaveNotYetShownObserversOurSituation)
{
EnsureThatObserversHaveRegisteredObservations();
weHaveNotYetShownObserversOurSituation = <span class="kwrd">false</span>;
}
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
<span class="kwrd">void</span> EnsureThatObserversHaveRegisteredObservations()
{
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> observers)
{
observer.Observe(Situation);
}
}
<span class="kwrd">public</span> IObservable<IEvent<State>> Situation
{
get
{
<span class="kwrd">if</span> (situation == <span class="kwrd">null</span>)
situation = EnsureThatTheObservableHasBeenCreated();
<span class="kwrd">return</span> situation;
}
}
<span class="kwrd">public</span> StateKeeper(IEnumerable<Observer> observers)
{
<span class="kwrd">this</span>.observers = observers;
}
}</pre>
</div>
<p>In the constructor, I'm simply storing the observers and when the update state happens I check if I have asked the observers to observe and if that has not already taken place, I do so.</p>
<p>The implementation of the original observer that had the bounded context leak issue now changes to:</p>
<div class="codeBlock">
<pre class="csharpcode"><span class="kwrd">namespace</span> TeamSlayer.Model.World
{
<span class="kwrd">public</span> <span class="kwrd">interface</span> IContextObserver<State>
{
<span class="kwrd">void</span> Observe(IObservable<IEvent<State>> situation);
}
}
<span class="kwrd">namespace</span> TeamSlayer.Model.Decision
{
<span class="kwrd">public</span> <span class="kwrd">class</span> BattleReachedAReasonableTurnObserver : IObserveToMakeDecisions
{
<span class="kwrd">readonly</span> IManageStatistics statisticsManager;
<span class="kwrd">public</span> BattleReachedAReasonableTurnObserver(IManageStatistics statisticsManager)
{
<span class="kwrd">this</span>.statisticsManager = statisticsManager;
}
<span class="kwrd">public</span> <span class="kwrd">void</span> Observe(IObservable<IEvent<DecisionState>> situation)
{
situation.Where(s => s.EventArgs.TheNumberOfTurnsSoFar == 50)
.Subscribe(s =>
{
ReachedTurnFifty = <span class="kwrd">true</span>;
statisticsManager.WriteStatistics(ReachedTurnFifty);
});
}
<span class="kwrd">public</span> <span class="kwrd">bool</span> ReachedTurnFifty { get; <span class="kwrd">private</span> set; }
}
}</pre>
</div>
<p>I've now removed the using statement to the world context and this observer is now isolated in the decision context once again.</p>
<p>What is interesting is that as this observer is now passed the situation observable, typed to the state of this bounded context, this in fact makes much more sense than the previous implementation. Once again, a code change has moved me towards deeper insight about my code and cleared this area up - the bounded context concept has made me think about isolation in a new way.</p>Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-69436719552042398132010-10-07T08:17:00.001+01:002010-10-07T08:17:05.835+01:00revisiting robocode state with generics<p>In my robocode series I've reworked my code into bounded contexts and so far I have a robot that does not get disabled in battle and can report that it reached turn fifty. <br />However, it still does very little and does not move or scan for enemies. <br />I have an additional acceptance test that ensures I win against the sitting duck robot so my next piece of work is to get this test to pass. I think this is going to need some more decision context work and the introduction of some new bounded contexts.</p> <p>Before I reworked my code to use domain driven design concepts, I had a simple observer that at the start of the battle issued instructions for the robot to look for enemies. I want to re-implement this in one of my contexts and I decide that the manipulation context is the best location for this as I will be manipulating the robot with this observation.</p> <p>I start to write my specifications for the ManipulationContextTranslator and this suggests I require a ManipulationState and thus something to keep and update this state, for example ManipulationStateKeeper.</p> <p>When beginning the specs for this, it is clear that the code is almost exactly the same as the previous DecisionStateKeeper so I decide to stop and instead see if I can make any of this code reusable, using the existing DecisionStateKeeper as the blueprint and running its unit test as I go.</p> <p>Here's what I originally had in the DecisionStateKeeper as a reminder:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> DecisionStateKeeper : IKeepDecisionState, IUpdateDecisionState
{
DecisionState internalDecisionState;
<span class="kwrd">public</span> DecisionStateKeeper(IEnumerable<IObserveToMakeDecisions> <br /> decisionMakingObservers)
{
CreateObservableForDecisionState();
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> decisionMakingObservers)
{
observer.Observe(<span class="kwrd">this</span>);
}
}
<span class="kwrd">public</span> IObservable<IEvent<DecisionState>> Situation { get; <span class="kwrd">private</span> set; }
<span class="kwrd">event</span> EventHandler<DecisionState> DecisionStateHasUpdated;
<span class="kwrd">void</span> CreateObservableForDecisionState()
{
Situation = Observable.FromEvent<DecisionState>(
ev => <span class="kwrd">this</span>.DecisionStateHasUpdated += ev,
ev => <span class="kwrd">this</span>.DecisionStateHasUpdated -= ev);
}
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<DecisionState> decisionStateUpdate)
{
decisionStateUpdate(InternalDecisionState);
DecisionStateHasUpdated(<span class="kwrd">this</span>, InternalDecisionState);
}
<span class="kwrd">protected</span> DecisionState InternalDecisionState
{
get
{
<span class="kwrd">return</span> internalDecisionState ?? (internalDecisionState = <span class="kwrd">new</span> DecisionState());
}
}
}</pre>
</div>
<p>To make this generic I start with a StateKeeper (compiler errors shown in red and I'm omitting any StateKeeper specific specs in this email for brevity):</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> <font color="red">StateKeeper<State></font> : IUpdateState<State>
{
}
<span class="kwrd">public</span> <span class="kwrd">interface</span> IUpdateState<State>
{
<span class="kwrd">void</span> UpdateState(Action<State> stateUpdate);
}</pre>
</div>
<p>I have a new generic interface to replace the specific IUpdateDecisionState and I'm not implementing the underlying member, so have a compilation error. I introduce that member and pull the code from the original state keeper in:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>
{
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(<font color="red">InternalState</font>);
<font color="red">StateHasUpdated</font>(<span class="kwrd">this</span>, <font color="red">InternalState</font>);
}
}</pre>
</div>
<p>I need to pull more code in from the original class to make this work:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>
{
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = <font color="red">xxxx?</font> );
}
}
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<<font color="red">State></font> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
}</pre>
</div>
<p>I've now got two issues - the State generic type does not derive from EventArgs and I need to be able to create a new State if the internal state is not available. I can fix both issues with the following:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>
<span class="kwrd">where</span> State : EventArgs
{
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = EnsureThatStateHasBeenCreated());
}
}
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> State EnsureThatStateHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<State> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
}</pre>
</div>
<p>I now have an abstract method to ensure that the state gets created and I have a generic type constraint on my class.
<br />My next step is to make the IKeepDecisionState interface more generic:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IKeepState<State>
{
IObservable<IEvent<State>> Situation { get; }
}</pre>
</div>
<p>The StateKeeper also needs to implement this interface and I pull in the constructor code from the DecisionStateKeeper:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> State : EventArgs
{
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = EnsureThatStateHasBeenCreated());
}
}
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> State EnsureThatStateHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<State> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
<span class="kwrd">public</span> IObservable<IEvent<State>> Situation { get; <span class="kwrd">private</span> set; }
<span class="kwrd">public</span> StateKeeper()
{
<font color="red">CreateObservableForDecisionState()</font>;
}
}</pre>
</div>
<p>I now have my observable at the bottom of this class and I have the constructor from the old DecisionStateKeeper.
<br />This now presents me with a problem - I can make this method an abstract method but this would be bad thing to do.</p>
<p>Calling a virtual method from a constructor is a very bad idea - the base class constructors are called before the derived version so it is not good practice to call out to the derived class until it has been initialised.
<br />I therefore need to move this to the situation property itself when it is accessed:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> State : EventArgs
{
IObservable<IEvent<State>> situation;
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = EnsureThatStateHasBeenCreated());
}
}
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> State EnsureThatStateHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<State> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
<span class="kwrd">public</span> IObservable<IEvent<State>> Situation
{
get
{
<span class="kwrd">return</span> situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
}
}
<span class="kwrd">public</span> StateKeeper() { }
}</pre>
</div>
<p>I now create the observable situation when it is first accessed and there is an abstract method to ensure this happens.</p>
<p>The final piece of this generic work is to introduce the observers - I need a generic interface for this to replace the IObserveToMakeDecisions interface that took in a DecisionStateKeeper and made observations on it:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">interface</span> IContextObserver<State>
{
<span class="kwrd">void</span> Observe(IKeepState<State> stateKeeper);
}</pre>
</div>
<p>To implement this in the StateKeeper I have two choices: I can either use IContextObserver<State> directly or I can declare another generic type for the observers, abstracting that interface type. Samples of both are shown below:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> State : EventArgs
{
IEnumerable<IContextObserver<State>> observers;
<span class="kwrd">public</span> StateKeeper(IEnumerable<IContextObserver<State>> observers) { }
}
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> Observer : IContextObserver<State>
<span class="kwrd">where</span> State : EventArgs
{
IEnumerable<Observer> observers;
<span class="kwrd">public</span> StateKeeper(IEnumerable<Observer> observers) { }
}</pre>
</div>
<p>I prefer the second option so am going to run with that. I now implement the observers in full:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> StateKeeper<State, Observer> : IUpdateState<State>, IKeepState<State>
<span class="kwrd">where</span> Observer : IContextObserver<State>
<span class="kwrd">where</span> State : EventArgs
{
IObservable<IEvent<State>> situation;
State internalState;
State InternalState
{
get
{
<span class="kwrd">return</span> internalState ?? (internalState = EnsureThatStateHasBeenCreated());
}
}
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> State EnsureThatStateHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">abstract</span> IObservable<IEvent<State>> EnsureThatTheObservableHasBeenCreated();
<span class="kwrd">protected</span> <span class="kwrd">event</span> EventHandler<State> StateHasUpdated;
<span class="kwrd">public</span> <span class="kwrd">void</span> UpdateState(Action<State> stateUpdate)
{
stateUpdate(InternalState);
StateHasUpdated(<span class="kwrd">this</span>, InternalState);
}
<span class="kwrd">public</span> IObservable<IEvent<State>> Situation
{
get
{
<span class="kwrd">return</span> situation ?? ( situation = EnsureThatTheObservableHasBeenCreated());
}
}
<span class="kwrd">public</span> StateKeeper(IEnumerable<Observer> observers)
{
<span class="kwrd">foreach</span> (var observer <span class="kwrd">in</span> observers)
{
observer.Observe(<span class="kwrd">this</span>);
}
}
}</pre>
</div>
<p>I've now got my first cut of this generic class and this changes the Decision State Keeper and the future Manipulation State Keeper dramatically.
<br />I'll leave you with the now more lightweight and cleaner Decision State Keeper and in my next post I'll discuss one of the domain driven design issues with the observers themselves that is caused by this change.</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> DecisionStateKeeper : StateKeeper<DecisionState, IObserveToMakeDecisions>
{
<span class="kwrd">public</span> DecisionStateKeeper(IEnumerable<IObserveToMakeDecisions> observers)
: <span class="kwrd">base</span>(observers)
{
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> DecisionState EnsureThatStateHasBeenCreated()
{
<span class="kwrd">return</span> <span class="kwrd">new</span> DecisionState();
}
<span class="kwrd">protected</span> <span class="kwrd">override</span> IObservable<IEvent<DecisionState>>
EnsureThatTheObservableHasBeenCreated()
{
<span class="kwrd">return</span> Observable.FromEvent<DecisionState>(
ev => <span class="kwrd">this</span>.StateHasUpdated += ev,
ev => <span class="kwrd">this</span>.StateHasUpdated -= ev);
}
}
<span class="kwrd">public</span> <span class="kwrd">interface</span> IObserveToMakeDecisions : IContextObserver<DecisionState>
{
}</pre>
</div> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-17685239175034977782010-09-27T06:42:00.000+01:002010-09-27T06:42:00.626+01:00the structure of my robocode implementation<p>There has been a lot of code on this blog for my robocode series and I thought I would illustrate the current structure of the codebase to provide some clarity to those following my growing implementation. </p> <p>Here's the structure of my code so far:</p> <p><a href="http://lh4.ggpht.com/_Osl8Rl-slhQ/TJpOXZDw8FI/AAAAAAAAAIY/0N-kbvRaaHE/model9.png?imgmax=800"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="597" alt="model" src="http://lh6.ggpht.com/_Osl8Rl-slhQ/TJpOgk5BNsI/AAAAAAAAAIc/w9uD4ZPwwHQ/model_thumb5.png?imgmax=800" width="298" border="0" /></a> </p> <p>The "Adapter" namespace is where my robot resides and this is the only area that knows about the robocode library and its types. This keeps a clean separation between my own model and the robocode library and acts as an anti corruption layer.</p> <p>The "Battles" namespace is where all my battle code lives for parsing battle results and running acceptance tests - I covered the creation of these in earlier blog posts.</p> <p>The "Decision" namespace is my new bounded context for decision making. I have a DecisionContextTranslator that knows how to convert the world state into decision state and from there the code is pretty much isolated (although at present it uses the statistics manager directly and I plan to change this in the future if statistics writing requirements grow).</p> <p>The "Manipulation" namespace is where my robot engine lives and the robot interface that the adapter robot implements so I can speak to it in my model's terms.  I plan on having a context translator here that will know how to issue instructions to the ImARobot interface, through the robot engine.</p> <p>The "Service" namespace is where I keep my service locator that abstracts from the underlying IOC container. I need this because the robot is created by robocode itself and I need a hook into service resolution to get the robot engine and the resulting dependency tree.</p> <p>The "Statistics" namespace contains the classes for writing statistics out to assist with acceptance testing requirements.</p> <p>Finally, the "World" namespace separates out the world state as this transcends into the context translators in each bounded context and resides as an instance in the robot engine. Pulling it out seemed a logical thing to do.</p> <p>From my original design when thinking about bounded contexts I expect to have a new calculation context introduced soon that will deal with calculations based on the decisions made by the decision context.</p> <p>There we have it, the "Slayer" robocode implementation so far. <br />So much code to do so very little! (as my robot doesn't even move, scan or fire yet) <br />Regardless of battle achievements it has been a really valuable exercise in context specification, test driving something new, acceptance test first development, using domain driven design concepts and experimenting with the new RX framework.</p> <p>I just hope I can now build on this foundation and get the robot to do some interesting things!</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0tag:blogger.com,1999:blog-990393702029999754.post-69693059183179867232010-09-23T07:15:00.000+01:002010-09-23T07:15:00.323+01:00acceptance, more debugging and head scratching<p>In my last few posts in my robocode series I've developed a bounded context for decision making and it is ready to try out. I have some acceptance tests written that ensure I meet some conditions and the definitive one to check things are working is the test that ensures I reach turn 50, thus asserting that the robot is not disabled at the start of the battle.</p> <p>When I run the acceptance test it fails which indicates there is something wrong and the robot is being disabled. The error from the acceptance test is actually that the statistics file is old (and not because it doesn't reach turn 50). <br />This means that the robot's Run() method hasn't been called correctly and the robot engine is not initialised.</p> <p>Sure enough, when I manually run the robocode GUI and watch my robot it is immediately disabled at the start of the battle. <br />So what could be going wrong? <br />After much head scratching and rechecking the code and the specifications I can't see anything wrong - the execution paths look like they should be doing what I've specified so I need to do some debugging.</p> <p>I insert some debugging statements into the code of the Slayer Robot as the first line of the following two methods:</p> <div class="codeBlock"> <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">void</span> Run(<span class="kwrd">bool</span> shouldContinueToLoop)
{
DebugProperty[<span class="str">"run is called"</span>] = <span class="str">"true"</span>;
robotEngine = ServiceLocator.ProvideRobotEngine();
robotEngine.Initialise(<span class="kwrd">this</span>);
Scan();
<span class="kwrd">bool</span> shouldLoop = <span class="kwrd">true</span>;
<span class="kwrd">while</span>(shouldLoop)
{
robotEngine.EnsureTheWorldStateIsUpToDate();
shouldLoop = shouldContinueToLoop;
}
}
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnStatus(StatusEvent e)
{
DebugProperty[<span class="str">"on status called"</span>] = <span class="str">"true"</span>;
robotEngine.PublishToTheWorldState(w =>
{
w.CurrentTurnNumber = e.Status.Time;
w.GunTemperature = e.Status.GunHeat;
});
}</pre>
</div>
<p>Now when I observe a battle through the GUI and bring up the turn snapshot from the battle log I observe that on the very first turn, turn 0, the following debug properties are available:</p>
<p><a href="http://lh3.ggpht.com/_Osl8Rl-slhQ/TJpMgB5o6yI/AAAAAAAAAII/TnX0L2-0eg0/s1600-h/debugStatus4.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="220" alt="debugStatus" src="http://lh5.ggpht.com/_Osl8Rl-slhQ/TJpMiO2CgdI/AAAAAAAAAIM/kK97M3-UyUs/debugStatus_thumb2.png?imgmax=800" width="534" border="0" /></a> </p>
<p>It appears that the status method is being called, but the run is not and would suggest that there is a sequencing issue with my code.</p>
<p>I write a specification for this potential bug:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">class</span> when_robocode_updates_the_turn_status_on_a_robot_and_run_has_not_occurred
{
Establish context = () =>
{
robotStatus = RobocodeSpy.CreateARobotStatus(0, 0);
statusEvent = <span class="kwrd">new</span> StatusEvent(robotStatus);
robot = <span class="kwrd">new</span> SlayerRobot();
};
Because of = () => caughtException = Catch.Exception(() => robot.OnStatus(statusEvent));
It should_not_fail_because_the_robot_engine_is_not_available =
() => caughtException.ShouldBeNull();
<span class="kwrd">static</span> SlayerRobot robot;
<span class="kwrd">static</span> RobotStatus robotStatus;
<span class="kwrd">static</span> StatusEvent statusEvent;
<span class="kwrd">static</span> Exception caughtException;
}</pre>
</div>
<p>When I run this specification it fails because a null reference exception is returned due to the missing robot engine instance.
<br />I can fix this quickly with the following code:</p>
<div class="codeBlock">
<pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnStatus(StatusEvent e)
{
<span class="kwrd">if</span> (robotEngine == <span class="kwrd">null</span>)
<span class="kwrd">return</span>;
robotEngine.PublishToTheWorldState(w =>
{
w.CurrentTurnNumber = e.Status.Time;
w.GunTemperature = e.Status.GunHeat;
});
}</pre>
</div>
<p>Although this fixes this particular issue, if I want to keep this same code structure I've been developing then I have to accept that I will never get a status update on turn 0, the first turn, right at the start of the battle - I decide that this is acceptable, at least at this very early stage of development.</p>
<p>When I run the acceptance test once again, it now passes:</p>
<p><a href="http://lh6.ggpht.com/_Osl8Rl-slhQ/TJpMi6FAkkI/AAAAAAAAAIQ/SkhyqbzOetU/passingAcceptance4.png?imgmax=800"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="171" alt="passingAcceptance" src="http://lh3.ggpht.com/_Osl8Rl-slhQ/TJpMpZQb4II/AAAAAAAAAIU/dwJsij-fzkQ/passingAcceptance_thumb2.png?imgmax=800" width="566" border="0" /></a> </p>
<p>The important takeaway from this lesson in head scratching is what I can learn from this error. I had a huge assumption that robocode would call my Run() method before the status would update for turn zero. On reflection it makes sense that before commands are accepted from a robot, the status at the beginning of the battle is published, so I'm not really sure where that came from.
<br />I also think that if this was a professional codebase at a client and this was, for example, and email class deriving from a template patterned base class, I would have coded for every eventuality of calls being made out of sequence.
<br />So lesson learned - no assumptions in my personal projects and cover every possibility with specifications, just like I normally would at work.</p> Justin Davieshttp://www.blogger.com/profile/07619046251401049138noreply@blogger.com0