Sunday, December 1, 2013

Modifying NHibernate Connection String Value from MSBUILD file.

I am a big proponent of using Team City and MSBuild to create automated deployments in to Development, Testing and Staging environments.

I recently came across a problem with modifying a standard NHibernate connection string value using MSBuild and MSBuild Extension Pack, the MSBuild Extension Pack provides a collection of over 480 MSBuild Tasks, MSBuild Loggers and MSBuild Task Factories.

A typical NHibernate configuration setting looks like the following:


The section we want to change is

<property name="connection.connection_string">Data Source=FirstSample.sdf</property>
My first attempt was to use the XPath query of

/configuration/hibernate-configuration/session-factory/property[@name='connection.connection_string']
This was not matching the app.config XML which perplexed me at first until it dawned on me to use the namespace value of "urn:nhibernate-configuration-2.2".

The XMLFile class contains a namespace node


By setting the Namespaces value in the ItemGroup and then referencing it using @(Namespaces) in the Namespaces attribute of the XMLFile class I was able to get the desired result.

Saturday, September 7, 2013

Bootstrap 3 Upgrade

As a MVC developer I've been using Twitter Bootstrap for over a year to deliver responsive web designs. It gives me a massive head start on starting projects. By using Twitter Bootstrap I can reduce the Web Design cost for my clients to the point that we'll only engage a Web Designer for adding visual "icing to the cake" rather than building the site look and feel from the ground up. 

Recently Twitter Bootstrap v3.0.0 was released and if you've upgraded your project you'll noticed the layout no longer works. This is mainly in part to the new grid system. Instead of span1 you now have col-lg-1 and so on. The new (and 100% fluid) Bootstrap 3 grid now comes in 4 sizes. Tiny (for smartphones .col-xs-*), Small (for tablets .col-sm-*), Medium (for laptops .col-md-*) and Large (for laptops/desktops .col-lg-*). The 3 grid sizes enable you to control grid behavior on different devices (desktop, laptops, tablet, smartphone, etc..).

Now you can go through the official Bootstrap migration guide and manually make all the changes required or you can do as I did and use a tool. I've found that the Bootply Migration Tool to be an awesome starting point for the conversion. They'll be still a bit of manually editing but this tool will give you a good head start.

For instance copy and pasting the following HTML snippet into the tool:

Bootstrap 2 original mark up

Then hit "Convert to Bootstrap 3" and voilĂ .

Bootstrap 3 modified mark up

If you're a less addict like me you can Less mixins to migrate your grid. The ‘old’ span* will not be the same as col-* or col-lg-*. So replacing the class names in your templates will be give you better results. You will find that the col-lg-* class is in place of the former span* class. This will give you a possibility to create a mixin for span* with the same styles as col-lg-* in this case.

Sunday, May 12, 2013

Windows Service Logging and the Debug Process

I'm a big proponent of log4net for system logging. The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4 framework to the Microsoft .NET runtime. I especially like it's integration with NHibernate

This blog post is focusing in on logging in Windows Service. This is not a post about the setting up of log4net but about extending it's capabilities. There's plenty of posts on the interwebs about the actual configuration.

To give the reader some background, I am currently working on a project which requires integration points for the system. In short the system being built using Dynamics CRM needs to on a scheduled basis push and pull data from different systems. To accomplish this I've developed a Windows Service that allows for multiple jobs to be executed from it. I decided to use log4net for the logging interface. 

The issue I came across was during the debugging process. I generally debug a Windows Services on my local machine by using a Windows Form as a UI to start (or stop) the underlying service. By using the following code in the program.cs file:


Then I set whether to run the Windows Form UI by setting the command line argument for the start up project to /console as shown in the image below.

























Now when I press F5 the debug form is shown.



















The problem was I was always finding myself continuously running SQL queries during the debugging process to look at the log messages, not entirely productive. I figured there had to be a better approach. Through a bit of research I was able to find a decent approach to the problem. The solution was to use a custom AppenderSkeleton. The code is as shown below:


The is two key parts to the new CustomMemoryAppender class. Firstly, the overridden Append method. This method takes the logging event information and appends it to a StringBuilder variable called logBuffer. Secondly the public method ReadBuffer() this allows a external caller to access the current log message buffer information.

To hook this up in the Windows Form I need to override the Form OnLoad event and add some code:


The above code informs log4net to include the CustomMemoryAppender in the list of appenders the log4net with log to. It all tells log4net to log all logging events to the new appender.

Now when I press F5 I get the Debug form as well as all the logging messages. 

I've created a sample solution available at GitHub that uses a timer event to create log messages.

Tuesday, March 26, 2013

Delivering Chocolatey Goodness for Git Flow

I've been using Git Flow as a Git branching model for over 2 years on both personal and private projects. At my current job we are about to switch from SVN to Git, so we are going through a process of setting up the Developers machines for working with Git. 

One tool that can help the set of the machines is Chocolatey Nuget. Chocolatey is is a Machine Package Manager, somewhat like apt-get, but built with Windows in mind. It is set up on the same premise as Nuget both at their essence are package managers.

To set up Chocolatey open a command prompt and type 

This installs Chocolatey onto your machine.

Once this is done type the following commands at the command prompt. This installs Git, MsysGit, Posh Git and Git Flow to your machine.:

Now you have the tools to set up Git Flow on your machine. To complete the installation of Git Flow type the following into your command line:



If you get an error at the above step fix by copying the following files from the Git install path similar to C:\Users\USER_NAME\AppData\Local\GitHub\PortableGit_8810fd5c2c79c73adcc73fd0825f3b32fdb816e7.

NB: Replace PortableGit_8810fd5c2c79c73adcc73fd0825f3b32fdb816e7 with the name of your directory; you do not need the \bin at the end.

Git Flow Files












To C:\Program Files (x86)\Git\libexec\git-core (or similar)

Then you are ready to use git flow, read this article for more information about using git flow

Friday, October 26, 2012

Razor @Sections, Javascript and the conundrum of EditorTemplates

With the exception of when using Modernizr I always try to adhere to the web performance rules of css at the top of the page and javascript at the bottom. The razor @RenderSection(string name, bool required) helper class and the @Section keyword certainly helps with that goal within view pages.

I recently came across this problem in a project for partial views. For instance if I create a DateTime.cshtml to represent an EditorTemplate for DateTime properties on View Models. I can't just inject the relevant scripts for the jQuery UI Date picker extension using the @section Scripts method like you can do within normal views.

So how can a developer adhere to best practices for stylesheets and script files? By using an extension method.

Let's start with adding a couple of extension methods, Resource and RenderResources as described below.

As you can see the Resource method takes a signature of Func<object, dynamic> template which simply can be @ so when template is executed the script tag is written into the page. The other parameter type is the type of resource being rendered "css" or "js", I've created a static helper class to remove the magic string.


In the layout:


In the partial :


I haven't tested with Asp .net bundle as yet but with little or no tweaking that should work as well.

Monday, July 9, 2012

Why isn't this test passing? Must be FakeItEasy's fault.

This is a cautionary tale. Before trawling through the different communities trying to work out why something isn't working and step back and look at your code with a bit of common sense.

I had this code in my WorkoutController.



        public ActionResult Edit(Guid id) {

            WorkoutViewModel workout _workoutService.FindById(id);

            if(Request.IsAjaxRequest()) {

                return PartialView("_WorkoutEditView",  workout);

            }

            return View("Edit",  workout);

        }



A part of the Action was being tested by this Unit Test.



        [Test]

        public void EditCallsFindById() {

            Guid newGuid Guid.NewGuid();

            _controller.Edit(newGuid);

            A.CallTo(_workoutService.FindById(Guid.Empty)).WithAnyArguments().MustHaveHappened(Repeated.Exactly.Once);        }



Every time I ran the test it failed and obviously continued to fail. It was driving me nuts. I start looking at the FakeItEasy wiki and started looking at StackOverflow.

I left the problem overnight and came back to it this morning. When I look at the test first thing it hit me. The signature of A.CallTo() that I was looking for was

public static IReturnValueArgumentValidationConfiguration CallTo(Expression<Func> callSpecification)

Hence when I changed my test to:

Code Snippet

        [Test]        public void EditCallsFindById() {
            
            Guid newGuid Guid.NewGuid();

            _controller.Edit(newGuid);

            A.CallTo(()=>_workoutService.FindById(Guid.Empty)).WithAnyArguments().MustHaveHappened(Repeated.Exactly.Once);
        }



That is I need to added the lambda expression.

The moral to this story is always cast a critical eye over your code before really getting into troubleshooting mode.

Friday, March 9, 2012

WebApi - An Example with Database Persistance

As discussed in my last post the new Web Api feature which is packaged with the MVC4 beta rollout allows for the use of Inversion Of Control (Dependency Injection) similar to that of MVC3.

In this post I am going to step through a "real life" Web Api project called "Healthy Muscle Web", which will allow consumers of the API to interact with a set of data relating to workouts. Whether the consumers be mobile applications (iPhone, Android), mashups or other web platforms (Ruby, php, AspNet MVC).

Let's start with a data model


Code Snippet

    public class Workout
    {
        public virtual Guid Id { get; set; }
        public virtual string DateTime { get; set; }
        public virtual string WorkoutName { get; set; }
    }



For the persistence I will be using NHibernate. Now onto the controller implementation. From my understanding in REST, there are 4 primary verbs that we are concerned with:


  1. POST: Create a new entity

  2. PUT: Update an existing entity

  3. GET: Retrieve a specified entity

  4. DELETE: Delete a specified entity





Code Snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NHibernate.Linq;
using WebApi.Data.Configuration;
using WebApi.Data.Models;

namespace WebApi.Controllers
{
    public class WorkoutController : ApiController
    {
        private readonly IUnitOfWork _unitOfWork;

        public WorkoutController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        // GET /api/workouts
        [HttpGet]
        public IEnumerable<Workout> Get()
        {
            return _unitOfWork.CurrentSession.Query<Workout>().AsEnumerable();
        }

        // GET /api/workout/5
        [HttpGet]
        public Workout Get(Guid id)
        {
            var workout = _unitOfWork.CurrentSession.Query<Workout>().SingleOrDefault(x => x.Id == id);

            //If entity expected does not exist return 404.
            if (workout == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            return workout;
        }

        // POST /api/workouts
        [HttpPost]
        public HttpResponseMessage<Workout> Post(Workout workout)
        {
            var id = _unitOfWork.CurrentSession.Save(workout);
            _unitOfWork.Commit();

            var response = new HttpResponseMessage<Workout>
                (workout, HttpStatusCode.Created);
            response.Headers.Location = new Uri(Request.RequestUri,
                Url.Route(null, new { id }));

            return response;
        }

        // PUT /api/workouts
        [HttpPut]
        public Workout Put(Workout workout)
        {
            var existingWorkout = _unitOfWork.CurrentSession.Query<Workout>().SingleOrDefault(x => x.Id == workout.Id);

            //check to ensure update can occur
            if(existingWorkout==null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            //merge detached entity into session
            _unitOfWork.CurrentSession.Merge(workout);
            _unitOfWork.Commit();

            return workout;
        }

        // DELETE /api/workouts/5
        [HttpDelete]
        public HttpResponseMessage Delete(Guid id)
        {
            var existingWorkout = _unitOfWork.CurrentSession.Query<Workout>().SingleOrDefault(x => x.Id == id);

            //check to ensure delete can occur
            if(existingWorkout==null)
                return new HttpResponseMessage(HttpStatusCode.NoContent);

            _unitOfWork.CurrentSession.Delete(existingWorkout);

            _unitOfWork.Commit();

            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}



For some methods I am just returning an entity, in this case Workout, and in other instances I am returning a hopefully more informational HttpResponseMessage. For example, in the case of the Post of a new entity, I need to tell the REST Client the new location of the newly added product in the header. In other actions I am also throwing a HttpResponseException if the resource requested is not found as per the Get method.

The routing configuration in the Global.asax look like


Code Snippet

routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );



Looking at the WorkoutController there is a dependency on the interface IUnitOfWork


Code Snippet

    public interface IUnitOfWork : IDisposable
    {
        ISession CurrentSession { get; }
        void Commit();
        void Rollback();
    }



which has a concrete implementation of


Code Snippet

public class UnitOfWork : IUnitOfWork
    {
        private readonly ISessionFactory _sessionFactory;
        private readonly ITransaction _transaction;

        public UnitOfWork(ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
            CurrentSession = _sessionFactory.OpenSession();
            _transaction = CurrentSession.BeginTransaction();
        }

        public ISession CurrentSession { get; private set; }

        public void Dispose()
        {
            CurrentSession.Close();
            CurrentSession = null;
        }

        public void Commit()
        {
            if (_transaction.IsActive)
                _transaction.Commit();
        }

        public void Rollback()
        {
            _transaction.Rollback();
        }
    }



Nothing too out there at the moment (nor will there be)

I have two Structure Map Registries



Code Snippet

public class NHibernateRegistry : Registry
    {
        public NHibernateRegistry()
        {
            var cfg = new NHibernate.Cfg.Configuration()
                .SetProperty(Environment.ReleaseConnections, "on_close")
                .SetProperty(Environment.Dialect, typeof(MsSqlCe40Dialect).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionDriver, typeof(SqlServerCeDriver).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionStringName, "WebApi")
                .AddAssembly(typeof(Workout).Assembly);

            var sessionFactory = cfg.BuildSessionFactory();

            For<NHibernate.Cfg.Configuration>().Singleton().Use(cfg);

            For<ISessionFactory>().Singleton().Use(sessionFactory);

            
            For<ISession>().HybridHttpOrThreadLocalScoped()
                .Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());

            For<IUnitOfWork>().HybridHttpOrThreadLocalScoped()
                .Use<UnitOfWork>();
        }
    }



and



Code Snippet

public class DomainRegistry : Registry
    {
        public DomainRegistry()
        {
            Scan(x =>
                     {
                         x.TheCallingAssembly();
                         x.WithDefaultConventions();
                     });
        }
    }



To bootstrap the IOC configuration I have a class



Code Snippet

public class DependencyRegistrar
    {
        protected static bool DependenciesRegistered;

        private static void RegisterDependencies()
        {
            ObjectFactory.Initialize(x => x.Scan(y =>
            {
                y.AssemblyContainingType<DomainRegistry>();
                y.AssemblyContainingType<NHibernateRegistry>();
                y.LookForRegistries();
            }));
        }

        private static readonly object Sync = new object();

        public void ConfigureOnStartup()
        {
            RegisterDependencies();
        }

        public static bool Registered(Type type)
        {
            EnsureDependenciesRegistered();
            return ObjectFactory.GetInstance(type) != null;
        }

        public static void EnsureDependenciesRegistered()
        {
            if (DependenciesRegistered) return;
            lock (Sync)
            {
                if (DependenciesRegistered) return;
                RegisterDependencies();
                DependenciesRegistered = true;
            }
        }
    }



The Global.asax is as follows



Code Snippet

protected void Application_Start()
        {
            new DependencyRegistrar().ConfigureOnStartup();

            var container = ObjectFactory.Container;

            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
                new StructureMapDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            BundleTable.Bundles.RegisterTemplateBundles();
        }



EDIT: As Rob pointed out in the comments I'm not releasing the instances of IUnitOfWork so the disposing method is not being called, which could have an impact on the memory. Thanks Rob for the pick up. I've added the below code in the Global.asax which is called on the Appication_EndRequest event.


        protected void Application_EndRequest(object sender, EventArgs e) {
            ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
        }




The StructureMap configuration along with the Dependency Resolver (as discussed in my last post) allows for dependency injection.

You can see the full implementation at GitHub.com