My own personal code retreat

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).

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.

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.

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.
The hardest part has been just simply waking up in a positive frame of mind – I’ve found it almost impossible at times.

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.
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.

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?

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.
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.

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.

With that I’m doing my own personal code retreat to tie in with the Global day of code retreat that happens this Saturday 3rd December 2011.
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.

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.

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.

Posted at at 11:38 AM on Monday, November 28, 2011 by Posted by Justin Davies | 3 comments Links to this post   | Filed under:

How I authenticate with FubuMVC, part 2

In my last post 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 experiences on.

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.

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.

Here’s the ICacheProvider abstraction in the fubuMVC library:

  public interface ICacheProvider
  {
    object Get(string key);

    void Insert(string key, object value, CacheDependency cacheDependency, 
                         DateTime absoluteExpiration, TimeSpan slidingExpiration);
  }

And here is my own wrapper to the MemoryCache:

    public class MemoryCacheProvider : ICacheProvider
    {
        readonly MemoryCache _memoryCache;

        public MemoryCacheProvider(MemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        public object Get(string key)
        {
            return _memoryCache.Get(key);
        }

        public void Insert(string key, object value, CacheDependency cacheDependency, 
                    DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            var cacheItemPolicy = new CacheItemPolicy
                {
                    AbsoluteExpiration = (absoluteExpiration == Cache.NoAbsoluteExpiration)
                                              ? ObjectCache.InfiniteAbsoluteExpiration
                                              : new DateTimeOffset(absoluteExpiration),
                    SlidingExpiration = (slidingExpiration == Cache.NoSlidingExpiration)
                                              ? ObjectCache.NoSlidingExpiration
                                              : slidingExpiration
                };

            _memoryCache.Add(key, value, cacheItemPolicy);
        }
    }

So here are the specifications for my AuthenticatedUserProcessor:

    [Subject(typeof(AuthenticatedUserProcessor))]
    public class when_processing_the_user_and_the_user_is_not_in_the_cache
    {
        Establish context = () =>
        {
            _emailAddress = "lknkjankjsdk";
            _identity = new Mock<IIdentity>();
            _identity.Setup(i => i.Name).Returns(_emailAddress);

            _user = new User();
            _userObtainer = new Mock<IObtainUsers>();
            _userObtainer.Setup(u => u.ObtainUserFromEmailAddress(_emailAddress))
                                     .Returns(_user);

            _fubuRequest = new Mock<IFubuRequest>();

            _userRequestCache = new MemoryCacheProvider(new MemoryCache("userCache"));
            _authenticatedUserProcessor = new AuthenticatedUserProcessor(_userRequestCache, 
                                       _userObtainer.Object, _fubuRequest.Object);
        };

        Because of = () =>
            _authenticatedUserProcessor.Process(_identity.Object);

        It caches_the_user_it_obtained = () =>
            (_userRequestCache.Get(_emailAddress) as 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)));

        static AuthenticatedUserProcessor _authenticatedUserProcessor;
        static Mock<IObtainUsers> _userObtainer;
        static Mock<IFubuRequest> _fubuRequest;
        static Mock<IIdentity> _identity;
        static string _emailAddress;
        static User _user;
        static ICacheProvider _userRequestCache;
    }

    [Subject(typeof(AuthenticatedUserProcessor))]
    public class when_processing_the_user_and_the_user_is_already_in_the_cache
    {
        Establish context = () =>
        {
            _emailAddress = "onmojnouiwe";
            _identity = new Mock<IIdentity>();
            _identity.Setup(i => i.Name).Returns(_emailAddress);

            _userObtainer = new Mock<IObtainUsers>();
            _fubuRequest = new Mock<IFubuRequest>();

            _theRequestsCurrentUser = new TheRequestsCurrentUser();
            _userRequestCache = new MemoryCacheProvider(new MemoryCache("userCache"));
            _userRequestCache.Insert(_emailAddress, _theRequestsCurrentUser, null, 
                                       Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            _authenticatedUserProcessor = new 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));

        static AuthenticatedUserProcessor _authenticatedUserProcessor;
        static Mock<IObtainUsers> _userObtainer;
        static Mock<IFubuRequest> _fubuRequest;
        static Mock<IIdentity> _identity;
        static string _emailAddress;
        static ICacheProvider _userRequestCache;
        static TheRequestsCurrentUser _theRequestsCurrentUser;
    }

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.
If it is in the cache, it simply sets the cached user into the request.
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.

Here is the implementation of the processor:

    public class AuthenticatedUserProcessor : IProcessAuthenticatedUsers
    {
        readonly ICacheProvider _userRequestCache;
        readonly IObtainUsers _userObtainer;
        readonly IFubuRequest _fubuRequest;

        public AuthenticatedUserProcessor(ICacheProvider userRequestCache, 
                    IObtainUsers userObtainer, IFubuRequest fubuRequest)
        {
            _userRequestCache = userRequestCache;
            _userObtainer = userObtainer;
            _fubuRequest = fubuRequest;
        }

        public void Process(IIdentity identity)
        {
            var user = _userRequestCache.Get(identity.Name) as TheRequestsCurrentUser 
                        ?? AddUserToTheCache(identity.Name);

            _fubuRequest.Set(user);
        }

        TheRequestsCurrentUser AddUserToTheCache(string identifier)
        {
            var user = _userObtainer.ObtainUserFromEmailAddress(identifier);
            var currentUser = new TheRequestsCurrentUser {User = user};
            _userRequestCache.Insert(identifier, currentUser, null, 
                    Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            return currentUser;
        }
    }

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.

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.

Posted at at 8:26 AM on Tuesday, November 1, 2011 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,