RSS

Category Archives: Uncategorized

ASP.NET MVC – Solution Template

I have built a number of large enterprise-grade projects in asp.net MVC over the last few years. Whenever I build new projects now I use the following structure for my solution. It allows for easy unit testing, custom membership and role providers and abstracts out the database operations into repositories.

I am always open to comments and improvements though so feel free to contact me via this site with any suggestions.

Anyway, here it is:

Solution Structure

  • Website
  • Website.Tests
  • ServiceInterface
  • ServiceImplementation
  • ServiceImplementation.Tests
  • RepositoryInterface
  • RepositoryImplementation
  • RepositoryImplementation.Tests
  • Mocks
  • Providers
  • Providers.Tests
  • DomainEntities
  • Extensions
  • Extensions.Tests

Website

This project is the asp.net MVC project as set up by the asp.net MVC project template.

Website.Tests

Contains tests for controller methods in the website. The mocked service implementation should be injected into these controllers so you are basically testing for control flow and nothing else.

ServiceInterface

Contains method signatures for ‘services’. Each fundamental domain entity class (ie such as ‘User’) should possess it’s own service interface. Methods should encapsulate well-defined use-cases such as ‘Register’, ‘PostComment’, ‘CreateGroup’ etc.

ServiceImplementation

Implementations of classes in the ServiceInterface project. Ideally these implementations will in a ‘user context’. In other words all operations are performed from that user’s perspective. Therefore Get() fetches the currently logged in user, PostComment(comment) posts a comment by the logged in user etc. The logged in user can be injected into the service instance on construction. Obviously some methods such as Register are performed anonymously.

Service implementations will more often than not require several Repository instances injecting into them on construction.

ServiceImplementation.Tests

These unit tests will test the logic and return values of the service implementation. In order to isolate the methods, you should inject the appropriate mocked repositories rather than using a repository implementation that is tied to the database.

RepositoryInterface

Classes in this project should contain simple CRUD methods to access the database and materialise the row data into instances of the classes in the DomainEntities project. It’s possible to use a generic base interface to specify the CRUD methods and just derive from that, adding any methods that are specific to each interface.

RepositoryImplementation

Contains implementations of classes in the RepositoryInterface project and will include database-specific code and/or use of any ORM tools.

RepositoryImplementation.Tests

Unit tests the repository implementation – should use a test database which is cleared after the tests have run, making execution of these tests idempotent.

Mocks

Use Mock factory classes to serve up mocks which implement classes in ServiceInterface and RepositoryInterface here. You can then call the factory methods from your test projects.

Providers

ASP.NET uses providers to perform authentication, authorisation and to provide profile information (though I’ve never actually used the latter). These providers are then specified in the web.config file.

You could use the RepositoryImplementation assembly to provide access to any data from the database here. Again, be sure to provide a way to inject any repositories so you can unit test the providers in isolation.

If you want to be able to use the providers in other solutions, just factor out a simple repository interface/class rather than use your existing repositories.

Providers.Tests

Unit tests for providers – inject repository mocks in order to isolate the functionality.

DomainEntities

Classes that provide simple business rules and logic which are used throughout the application. Anything more complicated should be factored into the ServiceImplementation. For example, methods such as User.Block(), ForumPost.Reply(Reply reply) are good candidates to include here. Any logic that alters the state of other classes as well as the one containing the method should be included in the Service Implementation rather than here.

Extensions

Any useful extension methods can go here – you can then re-use this project in other solutions.

Extensions.Tests

Nuff said.

Hope this gives someone out there a bit of a head start when setting up a nice new ASP.NET project.

 
Leave a comment

Posted by on September 24, 2013 in Uncategorized

 

Alternative to switch-case for complex comparisons

I usually try very hard to avoid non-trivial switch-case statements, they look awful. One of the limitations with switch-case is you can only use primitive types. This is fine for most cases, but sometimes you want to do a switch-case with a more complex object. For example, if you were developing a generic method that processed some value according to the type specified in the generic type argument of the method signature, switch case could not be used. Alternatively, you could use if…else if statements to decide how to process the value based on the type, as follows:

public T Parse<T>(string value) where T : struct
{
    T result;
    if(typeof(T) == typeof(int))
    {
        result = int.Parse(value);
    }
    else if(typeof(T) == typeof(long))
    {
        result = long.Parse(value);
    }
    else if(typeof(T) == typeof(short))
    { 
        result = short.Parse(value);
    }
    return (T) result;
}

This method is intended as a convenience method for parsing a string into whatever type is specified in T, we therefore do an if…else if statement on the typeof(T), calling the appropriate static Parse() method and casting/returning the result.

It’s easy to see how unmaintainable this would be once x number of type conditions were added. There is however a nice alternative, which is easily maintainable and won’t take you half an hour to scroll from top to bottom of the code block. We can use a generic dictionary to store type => function mappings and just return the outcome of the function mapped to the type. First, we need to define the dictionary. We can do this as follows:

var mappings = new Dictionary<Type, Func<Type,object>>() {
    { typeof(int), value => int.Parse(value) },
    { typeof(long), value => long.Parse(value) },
    { typeof(short), value => short.Parse(value) }
}

We can then call the appropriate method, depending on the type of T as follows:

return (T) mappings[typeof(T)](value);

This is much more compact than our unwieldy if…else if statement above, and easier to add new mappings for the various other different types should the need arise. Performance-wise I don’t know how this would compare with the if…else if block, but wouldn’t have thought there was that much difference in it for long code blocks, as Dictionary will call the GetHashCode() method of each Type instance in the dictionary’s keys, using it to quickly reference the value (the anonymous function). However I would store the dictionary in an appropriate context rather than constructing it every time the method is called, it’s up to you.

Putting it all together, here’s the whole if…else if method rewritten to use the mappings dictionary:

public T Parse<T>(string value) where T : struct
{
    var mappings = new Dictionary<Type, Func<Type,object>>() {
        { typeof(int), value => int.Parse(value) },
        { typeof(long), value => long.Parse(value) },
        { typeof(short), value => short.Parse(value) }
    }

    return (T) mappings[typeof(T)](value);
}

When you are forced to use a long, unwieldy if…else if statement due to the limitations of switch…case, this technique is well worth considering.

 
Leave a comment

Posted by on September 12, 2012 in Uncategorized

 

Javascript templated MVC framework using dojo and underscore.js

Recently I’ve been working on a client-side MVC setup for web elements and I thought it may be helpful to others if I published it. I used the opportunity to have a look at Dojo as so far I’ve only used jquery for client-side code.

My first impressions of dojo as a noob are that it is better organised than JQuery in terms of loading js files etc, and has very powerful features for writing classes in javascript. The downside in my opinion is that the documentation is inferior to jquery, it is less intuitive and the declarative markup is intrusive.

For my MVC client app I therefore decided not to use dojo widgets, and instead use a templating solution to render the views.

For those not familiar with MVC, it is a design pattern used in Object Oriented applications. Basically it separates data from it’s presentation to the user by:

  • Storing the data in a ‘Model’, which updates all its associated ‘Views’ every time it is changed
  • Using a ‘Controller’ to interact with the UI to change values in the model

I’ve created a simple diagram of how our sample app will work, as you can see, the DOM (ie the UI) interacts with our Controller via event handlers. The Controller changes the appropriate values in its Model, which then updates all its associated views which are rendered back to the DOM:

The first task was therefore to find a suitable templating solution and wrap it in a class so I can potentially change the templating engine if the one I was using fell short in any way.

In jquery I use jqote for all my client-side templating. It’s simple, intuitive and very fast. However for this project I didn’t want to have to include jquery, therefore I opted for the engine in underscore.js, which supports logic within templates and is comparable in terms of performance to jqote.

Here’s the ‘wrapper’ class I wrote to encapsulate the templating functionality:

require(['dojo/_base/declare'],
    function (declare) {

        return declare('dojoSandbox.Templater', null, {

            template: null, // contains compiled template

            constructor: function(templateString) {
                this.template = _.template(templateString);
            },

            render: function(data) {

                return this.template(data);

            }
        })
    });

I now needed to write a base class for a templated view, with some common methods to render and a couple of handlers should I need them, we’ll call the base class _TemplatedView:

require(['dojo/_base/declare',
            'dojo/text',
            'dojo/dom-construct'
            ],
    function (declare, text, domConstruct) {

        return declare('dojoSandbox._TemplatedView', null, {

            // Populate this in your sub-class constructor
            controller: null,

            // Populate this in your sub-class constructor
            containerNode: null,

            // Populate this in your sub-class constructor
            template: null,

            constructor: function() {},

            // Called prior to rendering
            onRendering: function(model) { return true; },

            // Called after rendering is complete
            onRendered: function(containerNode) { return true; },

            // Implement this method in your sub-class
            _initialise: function () {

            },

            update: function (model) {

                if(this.onRendering(model)) {

                    domConstruct.empty(this.containerNode);
                    var html = this.render(model);
                    dojo.place(html, this.containerNode, 'last');
                }
                this.onRendered(this.containerNode);

            },

            // Override this method to return your view's html to the update() function
            render: function (model) {

                return this.template.render(model);

            }

        });
    });

I store an instance of my wrapped template in the template property, which is used by the render method whch injects the model into the template and spits out the resulting html. The update function uses dojo.place to insert this html into a specified containerNode.

Next we need to write a model, a view and a controller for our app. The app we’re writing doesn’t do anything useful, just takes input in a form and displays the inputed data. Once again though, the model will contain methods that are generally useful, therefore we create another base class _Model:

require(['dojo'], function (dojo) {
    return dojo.declare('dojoSandbox._Model', null, {

        views: [],

        constructor: function () {

        },

        addView: function (view) {

            this.views.push(view);

        },

        updateViews: function () {

            for (var i = 0; i < this.views.length; i++) {

                this.views[i].update(this);

            }

        }

    });
});

This class contains a property views which is an array of view instances. The updateViews() method iterates through this array, calling each views’ update() method and passing itself (the model) as the argument for the method.

Now this is done we can create a UserModel class that derives from it, and calls it’s base class’s updateViews() method if any set methods are called on its properties:

So the view is responsible for rendering the html for our app. We’ll write a UserModel class which contains all the properties we want to be able to change, and calls base.updateViews() when any of those properties are changed. this class extends our _Model class:

require(['dojo', 'dojoSandbox/_Model'], function (dojo, _Model) {
    return dojo.declare('dojoSandbox.UserModel', [dojoSandbox._Model], {

        firstName: null,
        surname: null,
        age: null,

        constructor: function () {

        },

        setFirstName: function (firstName) {

            this.firstName = firstName;
            this.updateViews();

        },

        setSurname: function (surname) {

            this.surname = surname;
            this.updateViews();

        },

        setAge: function (age) {

            this.age = age;
            this.updateViews();

        }

    });
});

Not really much to say about this, if any of the set methods are called, it calls its base class’s updateViews() method.

We now move onto the controller class. No need for any base classes here as everything in it is specific to our user application. The controller contains a reference to it’s model, which in theory could be shifted into a base class, but in this instance I didn’t think it worth doing due to the simplicity of the app:

require(['dojo'], function (dojo) {

    return dojo.declare('dojoSandbox.UserController', null, {

        model: null,

        constructor: function (model) {

            this.model = model;

        },

        setFirstName: function (firstName) {

            this.model.setFirstName(firstName);

        },

        setSurname: function (surname) {

            this.model.setSurname(surname);

        },

        setAge: function (age) {

            this.model.setAge(age);

        }

    });

});

For this app we are just calling methods in the model.

Now all this is done, we can finally move onto the view. We’ll use our _TemplatedView class as described above and extend it as a UserView class:

require(['dojo/_base/declare',
            'dojo/text',
            'dojo/on',
            'dojo/dom-construct',
            'dojoSandbox/_TemplatedView',
            'dojoSandbox/Templater'
            ],
    function (declare, text, on, domConstruct, _TemplatedView) {

        return declare('dojoSandbox.UserView', [dojoSandbox._TemplatedView], {

            constructor: function (controller, templateString) {

                this.controller = controller;

                if (templateString) {
                    this.template = new dojoSandbox.Templater(templateString);
                } else {
                    this.template = new dojoSandbox.Templater(dojo.cache('templates', 'UserTemplate.html')); // Use default template string
                }

                controller.model.addView(this);

            },

            _initialise: function () {

                var domNode = this.containerNode;
                var controller = this.controller;

                on(domNode, '#firstName:change', function () { controller.setFirstName(this.value); });
                on(domNode, '#surname:change', function () { controller.setSurname(this.value); });
                on(domNode, '#age:change', function () { controller.setAge(this.value); });

            },

            update: function (model) {

                this.inherited(arguments);
                this._initialise();

            },

        });
    });

The constructor takes a controller as a param, and an optional template string. If no template string is provided, we’ll use a default one stored in an html file (I’ll go through this later).

This means that we can instantiate multiple instances of this View class using different templates which therefore render differently. It gives us a bit of added flexibility.

As you can see, we are caching the default template string using dojo.cache. Once the new Templater instance is created, the template is compiled ready for rendering using the injected object (more on this later).

The update() method overrides the same method in our _TemplatedView class, the only thing is adds to this however is a call to our _initialise() method which adds any handlers to the newly rendered template. In the handler code you’ll see that we are just caling the set methods in the controller instance.

Our default template looks like this:


    <label for="firstName">First Name</label>
    <input id="firstName" type="text" value="<%= firstName %>" />

    <label for="surname">Surname</label>
    <input id="surname" type="text" value="<%= surname %>" />

    <label for="age">Age</label>
    <input id="age" type="text" value="<%= age %>" />

By default, our templating engine uses the blocks to output values. If you look at the render() method in our _TemplatedView class, you’ll see that we are passing the model (which in this case will be an instance of UserModel) into the template. So the properties inside the blocks correspond to properties in our UserModel class. Bare in mind that if any of these properties have null values, ‘null’ will be inserted into the template which is not ideal.

Now thats all done, we can wire it all up in a page:

@{
    ViewBag.Title = "Home Page";
}

@section Javascript
{
<script type="text/javascript">// <![CDATA[
require([
            "dojo/parser",
            "dojo/Stateful",
            "dojo/domReady!",
            "dijit/Tooltip",
            "dijit/_TemplatedMixin",
            "dijit/form/Button",
            "dojoSandbox/_TemplatedView",
            "dojoSandbox/UserView",
            "dojoSandbox/UserController",
            "dojoSandbox/UserModel"
        ], function () {

            // Create the model
            var model = new dojoSandbox.UserModel();
            model.firstName = '';
            model.surname = '';
            model.age = '';

            // Create the controller, attaching the model to it
            var controller = new dojoSandbox.UserController(model);

            // Create 3 different templated views, specifying the controller. The controllers model will have the view assigned to it
            var view1 = new dojoSandbox.UserView(controller);
            var view2 = new dojoSandbox.UserView(controller, '



<h1><%= firstName %>&nbsp;<%= surname %>, aged <%= age %></h1>

');
            var view3 = new dojoSandbox.UserView(controller, '<textarea><%= firstName %>\n<%= surname %>\n<%= age %></textarea>');

            // Specify container nodes for each view
            view1.containerNode = dojo.byId("view1Container");
            view2.containerNode = dojo.byId("view2Container");
            view3.containerNode = dojo.byId("view3Container");

            // Refresh/render the views
            model.updateViews();

        });
// ]]></script>
}</pre>
<h2>View 1</h2>
<div id="view1Container"></div>
<h2>View 2</h2>
<div id="view2Container"></div>
<h2>View 3</h2>
<pre>

You’ll then need to add script tags to the head in your master page to load and configure dojo and our other classes:


<script type="text/javascript" src="@Url.Content(&quot;~/Scripts/underscore.js&quot;)"></script><script type="text/javascript">// <![CDATA[
        dojoConfig = {
            baseUrl: '@Url.Content("~/Scripts")',
            isDebug: true,
            tlmSiblingOfDojo: false,
            packages: [
                { name: 'dojo', location: 'dojo' },
                { name: 'dijit', location: 'dijit' },
                { name: 'dojox', location: 'dojox' },
                { name: 'dojoSandbox', location: 'classes' },
            ]
        };

// ]]></script>

<script type="text/javascript" src="@Url.Content(&quot;~/Scripts/dojo/dojo.js&quot;)" data-dojo-config="parseOnLoad: false, async: true, mvc: {debugBindings: true}"></script>

So the project structure looks like this:

Although I use asp.net MVC for this example, obviously it applies to any type of project and is easily adaptable. As you can see, first we create the model and set its properties, then we create the controller, inserting our model in the constructor. Then we instantiate the views which all use the same controller, but different templates.

All that’s left to do is specify a containerNode for each view. These are elements within our page.

For more complex apps this ‘wiring up’ could be encapsulted in another class with a root container.

I hope this helps anyone who wishes to implement a client-side MVC framework using dojo and templates. The full project can be downloaded here

 
2 Comments

Posted by on August 24, 2012 in dojo, javascript, jquery, underscore.js

 

Manipulating the value passed for ‘id’ prior to a jeditable request

I had a proper headache with this today. I (very) occasionally use the jeditable plugin to provide in-place editing on some fields. However, one thing I don’t particularly like about jeditable (it rocks in general) is the way it sends the id of the element that fired it’s event as the value for whatever settings.id is set to. For example, if you have a list of items on the page, each with an in-place editable span, you will need to add some unique reference to each jeditable request so you can retrieve the correct element from the database, change it to whatever the user has entered, and save it. Using jeditable you would need to specify your, say, span, as follows:

<span class="inplace" id="2334">Blah</span>

The problem with this is if you have another list of elements on the same page which also have in-place editable elements. There is therefore a chance that you will render two spans on the same page with the same id. This may cause problems, and it generally isn’t very nice. You should really be ensuring that your editable span has a unique id by using a prefix in it’s id attribute, for example:

<span class="inplace" id="Comment_2334">Blah</span>

You’ve now created a new problem because of the way jeditable works. It will send the following data in the request:

{ id: 'Comment_2334', value: 'Blah' }

Which means that if, like me, you use asp.net MVC, and you use model binding in your action method:

public ActionResult SaveComment(long id, string value)

You will get a parse error when jeditable makes it’s request because it can’t parse “Comment_2334” as a long for the id parameter. You need to alter the id prior to the request being made. I searched high and low for a solution to this, and eventually concocted my own. The following will alter the id prior to the request being made, therefore not breaking model binding and using html elements with unique ids:

$('.inplace').each(function() {
    var clickedElem = this;
    $(clickedElem).editable('/Forum/SaveComment', {
        type: 'text',
        indicator: 'Saving',
        tooltip: 'Click here to edit',
        onblur: 'submit',
        select: true,
        submitdata: { id: clickedElem.id.substring(8) // Alter the id prior to the request being made - basically, omit the Comment_ prefix
    });
});

I really hope this saves someone a lot of time and stress.

 
1 Comment

Posted by on November 22, 2011 in in place editing, javascript, jeditable, jquery

 

Strings and numbers in javascript – a hall of mirrors

One of my colleagues came across an interesting idiosyncracy when coding in javascript today. Consider the following script:

<script type="text/javascript">
    alert("1" - 1);
    alert("1" + 1);
</script>

What would you think that the first alert would display? For starters it would be best to throw an error (in my opinion anyway), but in reality, “1” is convert to an int and decremented by 1, which is fine.

The second alert, however, is a different story. Would you expect it to convert “1” to an int and add 1, in a simlar fashion to the first alert? No. In actual fact the int on the right-hand side of the expression is converted to a string and concaternated onto the “1”, resulting in “11”. Bizarre. This is because of ‘ambiguities in the + operator when dealing with strings’ I’m told.

I imagine this has already confused the hell out of a lot of web developers. However, it’s unlikely that it will be changed, because it would screw up so many web sites.

 
1 Comment

Posted by on October 26, 2011 in Uncategorized