Thursday, 18 April 2013

My Journey with Asp.Net MVC and RavenDB – Introduction to Tournament

The idea of this journey is based on a number of reasons. The main two are to learn how to use and work with RavenDB, focusing the usage in an Asp.Net MVC context and the other is to re-work a site which has been live for the past 4 years which has had minimal change over that time and needs a refresh and admin functionality.

I have chosen to use RavenDB as the backend of this system due to the nature of how the data is stored. The site is a sporting results site so once an event has taken place the results will not change. They may need some tweaking while entering them but once in and confirmed they won’t change. Due to this a relational database I feel isn’t the best fit for the data. Reading and speed of reading the data is the main function. The current site calculates scores on the fly all the time where as this isn’t required due to the previous reason of once the results are in they’re in.

I have decided to post the code onto GitHub during the development so the world can see how I’m progressing. I will also be posting about what I have learnt, what issues I’ve come across and how I’ve over come them. Also I believe it’s a good way to show case of what I am capable of. This series won’t be a step by step walk through but I hope with looking at the code and the description of the main parts in the blog it should aid others in how to get up and running.

Any pointers, comments, suggestions please let me know via Twitter or leave a comment on this blog.

Let’s start the journey ….

Friday, 22 March 2013

British Heart Foundation Warwick Castle Half Marathon 2013

On Sunday 17th March 2013 I ran my first ever half marathon in aid of the British Heart Foundation. It started and finished in the grounds of Warwick Castle.

My training had been going ok in the couple of months leading up to the race but I’d been ill a couple of weeks before so the preparation could have been better.

Anyway, it went well, the weather was actually relatively ok. It was cold but dry to start and then started sleeting at about mile 7. This which was nice for a couple of miles but then it was just cold.

I successfully completed the race in 2 hrs 9 mins 56 secs which I was very happy with!

Roll on the training and next year; target …. under 2 hours!

Wednesday, 20 March 2013

View Driven Data Design; don’t let your view shape your data

Recently I have found myself coming across a couple of view to data scenarios where you can see that the view has driven the data model. This makes my spidey sense tingle as this strikes me as too tight coupling between data and view.

So what am I actually talking about? I’ve called it “View Driven Data Design”.

So an example to make things clearer; any developer who has been in the business long enough will have had the opportunity to work with a UI which involves category and sub category dropdowns / pickers. These values are usually driven by a data source (database, xml definition etc.) which are dynamic. What do I mean by dynamic? I’m referring to none hard coded values which require recompilation to be available. Either through an administration function, a nightly batch job updating the data or through a configuration file. These can have some cascading / restriction functionality built in to improve usability but are dynamic. These values can be stored by id – usually Foreign Keyed to the source – to allow for normalisation etc. This is fine for this scenario however there are times when this approach is overkill and can cause future issues and frustrations.

Imagine a scenario where you have an single data item (entity) which is modelled as a single class definition. An instance of this class requires classification. Unlike our earlier example the “category” is driven by a list of hard coded enum values. The UI designer has specified that on a specific value of category there will be another option to further categorise the entity. This is also driven by a distinct number of values in another enum. Further more there is a specific correlation between category and sub category options. So like before these values can be stored on two properties of the entity. What’s wrong with this I hear you ask? On the face of it nothing is wrong. It is however when you come to use these categorisations in other parts of the system when the problems creep in.

So you’ve created the instances in your CRUD section of the application and it’s all running fine however you now have another requirement to use them in a different form and you require to run some logic depending on classification – this is where the issue raises it’s ugly head.

When trying to classify an instance of the entity you now need to check different combinations of two properties. This involves the same business logic being put in, potentially, multiple places in the code base which is bad. If there are other values to check as well this adds unnecessary noise and complexity to the business logic. So how do we make the developers life easier and keep the UI designer happy at the same time?

It all starts at the data model level and answering “what value(s) do we actually have to store and how can this improve code clarity?”.

Start off by looking to see if the distinct list of defined combinations between the two enum sets can be merged into one set. If there are two many options then leaving them split will probably need to remain, however if the sub categories only apply to a small number of main categories then making one set may be on. This will need to be determined on an implementation case by case basis.

Right we have one property on the entity and the UI designer still wants their category and sub category dropdowns with visibility rules etc. This is where we need to loosely couple the data model away from the view. This is the exact reason why we have the concept of a view model. Using the entity data model we can define and populate a specific model to drive the view. In this case this will probably include like for like property mapping where nothing special needs to happen (eg. simple text values such as names) but for the single category enum it will need to get mapped to the two different options and can then drive the visibility rules etc. On the save action a conversion can map from the two options back into one ready to save.

This allows for the UI to be driven with the user experience the designer/analyst required while also making further business logic simpler and clearer to understand for the developer; both to write originally but also for future code maintenance.

So in the future when your designer wants fancy dropdowns and categorisations take a moment to ask does it need to be stored that way? Your future self will thank you instead of taking your name in vein.

Sunday, 20 January 2013

Hello World with KnockoutJs–Code Restructure

Recently I have been reading a number of articles and watching training videos from Pluralsight about Javascript and KnockoutJs. After reading the “Hello world, with Knockout JS and ASP.NET MVC 4!” by Amar Nityananda I wanted to see if I could apply the techniques of what I’d learnt to a relatively simple example. After reading the original article I couldn’t help but think “this Js could be better structured, I think I could do this” … so this is what I came up with.

To get an understanding of the problem please read the original article first.

I’ve only concentrated on the client side JavaScript as this was the challenge …

// setup the namespace
var my = my || {};

$(function () {

    my.Customer = function () {
        var self = this;
        self.id = ko.observable();
        self.displayName = ko.observable();
        self.age = ko.observable();
        self.comments = ko.observable();
    };

    my.vm = function () {
        var 
            // the storing array
            customers = ko.observableArray([]),
            // the current editing customer
            customer = ko.observable(new my.Customer()),
            // visible flag
            hasCustomers = ko.observable(false),
           
            // get the customers from the server
            getCustomers = function() {
                // clear out the client side and reset the visibility
                this.customers([]);
                hasCustomers(false);
               
                // get the customers from the server
                $.getJSON("/api/customer/", function(data) {
                    $.each(data, function(key, val) {
                        var item = new my.Customer()
                            .id(val.id)
                            .displayName(val.displayName)
                            .age(val.age)
                            .comments(val.comments);
                        customers.push(item);
                    });
                    hasCustomers(customers().length > 0);
                });
            },
            // add the customer from the entry boxes
            addCustomer = function() {
                $.ajax({
                    url: "/api/customer/",
                    type: 'post',
                    data: ko.toJSON(customer()),
                    contentType: 'application/json',
                    success: function (result) {
     // add it to the client side listing, this will add the id to the record;
     // not great for multi user systems as one client may miss an updated record
     // from another user
                        customers.push(result);
                        customer(new my.Customer());
                    }
                });
            };

        return {
            customers: customers,
            customer: customer,
            getCustomers: getCustomers,
            addCustomer: addCustomer,
            hasCustomers: hasCustomers
        };
    } ();

    ko.applyBindings(my.vm);
});

The main points I was trying to cover are:

  • Code organisation through namespaces – I don’t want any potential naming conflicts. This isn’t a big issue in a small application but once they start growing it’s good to try and avoid putting definitions into the global namespace.
  • Expose the details of the view model through the Revealing Module pattern – this keeps details clean as well as improved data binding clarity.

I haven’t gone into too much detail as the rest of the project infrastructure is very similar to the original article and can be found there. I wanted to post this as an example of how to make the Js structured.

Happy to discuss further; contactable in the comments or via twitter.

Updated Edit

After a comment from ranga I have read the link posted and update the code (see below). I have moved the view model and the Customer declaration outside of the on document ready event. I have also change hasCustomers to be a computed value. The interesting read about the performance hit about the events firing on array manipulation was really interesting – worth a read.

// setup the namespace
var my = my || {};

my.Customer = function () {
    var self = this;
    self.id = ko.observable();
    self.displayName = ko.observable();
    self.age = ko.observable();
    self.comments = ko.observable();
};

my.vm = function () {
    var
    // the storing array
    customers = ko.observableArray([]),
    // the current editing customer
    customer = ko.observable(new my.Customer()),
    // visible flag
    hasCustomers = ko.computed(function () {
        return customers().length > 0;
    }),

    // get the customers from the server
    getCustomers = function () {
        // clear out the client side
        this.customers([]);

        // get the customers from the server
        $.getJSON("/api/customer/", function (data) {
            var items = new Array();
            $.each(data, function (key, val) {
                var item = new my.Customer()
                    .id(val.id)
                    .displayName(val.displayName)
                    .age(val.age)
                    .comments(val.comments);
                items.push(item);
            });
            customers(items);
        });
    },

    // add the customer from the entry boxes
    addCustomer = function () {
        $.ajax({
            url: "/api/customer/",
            type: 'post',
            data: ko.toJSON(customer()),
            contentType: 'application/json',
            success: function (result) {
                // add it to the client side listing, this will add the id to the record;
                // not great for multi user systems as one client may miss an updated record
                // from another user
                customers.push(result);
                customer(new my.Customer());
            }
        });
    };

    return {
        customers: customers,
        customer: customer,
        getCustomers: getCustomers,
        addCustomer: addCustomer,
        hasCustomers: hasCustomers
    };
} ();

$(function () {
    ko.applyBindings(my.vm);
});

Keep the feedback coming, I’m always up for learning and improving.

Thursday, 15 November 2012

Software Bucket List–Nov 2012

After reading Rob Maher’s blog post about the concept of software bucket list it got me thinking.

Let’s take a step back for a minute; what’s a bucket list? A bucket list is a list of all the things you want to do before you pass away. So a software bucket list for a developer is a list of software you’d ideally like to write before you retire. As Rob says it can be anything, not learn this or learn that etc. but what would you like to do?

So this brings me back to me, his blog post got me thinking. The whole idea of the list is that it will evolve over time but as of November 2012 this is my list:

  • Integrated disc golf membership system with result submission with associated automated renewals etc.
  • Work for and write software for a Formula 1 team
  • Multi player strategy re-write (modernise) of an old game we use to play in the early 00’s – Europa
  • Build <insert description here> to enable working from home for my own company – idea still hasn’t been thought of yet.

The last one doesn’t quite fit but it’s more a target to keep me inspired about moving forward.

Anyway, this is just a start and now it’s a seed that’s planted I’m sure I’ll come up with more but for now what’s yours?