To Remember – Math.floor

youHit to Math.floor(Math.random() * 2). This sets youHit to a random number that’s either 0 (which JavaScript reads as false) or 1 (which JavaScript reads as true).

Source Codecademy

Tips – CSS Selectors and HTML Branches

As i mentioned in a previous post, I’m learning HTML/Javascript at the moment via Codecademy and will post stuff I have learnt, so others who follow/Google can learn. These are just snippets, but the site is a great learning tool.

So CSS Selectors – CSS is a very powerful way of styling and positioning your HTML elements. The syntax is simple, you use the HTML element as the selector! Good example is if you want all your list elements to have a red background color:


Full code can be found here on JSFiddle.


li {
 background-color: red;

So the above example will highlight any list (li) element red, What if you want to more selective of what you want as red, say for example just any ordered (ol) list (li) elements red? Easy:


Full code can be found here on JSFiddle.


ol li {
 background-color: red;

So the above example will highlight any list (li) element that is child of a parent ordered list (ol) elements. This small example shows branching works within HTML documents and how CSS selectors traverses the tree using the simple parent/sibling relationships. This is very powerful. And as mentioned in a previous post, you can be more specific by giving a more specific branching.


Full code can be found here on JSFiddle.



ol li {
    background-color: red;
div ol li {
    background-color: purple;

Images courtesy of Codecademy.




Tips – Javascript Arrays – Refactoring to Filter and Map.

When learning a new language or implementing something new, I tend to “get it working” first which usually doesn’t include elegant code, unless I have written Libraries or extension methods previously to fit the solution. One of these was using Arrays in Javascript. Basically i needed to find the Active User, which was for a client side collection of users for an Admin. So my “get it working” code is the legal (but definitely not regal code), which is a simple function that returns a array of usernames, of people who are Active (i.e. login and use the site):


JSFiddle is here.

function getActiveUsers(people) {

    var activeUsers = [];
    var ii = 0;
    for (var i = 0; i < people.length; i++) {

        if (people[i].isActive == true) {
            activeUsers[ii] = people[i].userName;
    }    return activeUsers;

Anyway, as I’m learning Javascript presently, I have been reading about prototyping in Javascript and especially about some existing functionality that resides with the Array global object (under Array.prototype). Specially I’m talking about:



NB: As those Links note, the Array.prototype property was only introduced within the ECMAScript spec 5.1 (ECMA-262) Edition. This will mean adding some Polyfil code (also provided in the links above) if you wish to use this within old browsers.

Anyway, using these two new methods I was able to go back over my previously “get it working” code above, refactor it and use some of the nicely provided filter and map methods:

JSFiddle is here.

function getUserName(user) {
  return user.userName;

function isActive(user) {
  return user.isActive;

function notActive(user) {
  return !isActive(user);

function getActiveUsers(user){
  return user.filter(isActive).map(getUserName);

function getNonActiveUsers(user) {
    return user.filter(notActive).map(getUserName);

So now I call into this new getActiveUsers which passes the callback function isActive, which basically only gives me back items from the array where the property user.IsActive is true. The chained map function passes the callback function of getUserName to retrieve the userName only. I have also created the opposite functions as well – i.e. Non-Active users. Both JSFiddles show the code in action, but i goes to show that a little reading, research and thought can help improve code readability and re-usability a great deal.

Repository and Unit Of Work Design Pattern– ASP.NET MVC

Hello! There are two design patterns that I’m going to speak about today, which have been covered loads online and in various books, but I’m going to cover them quickly here:


Repository Pattern


Quite simply this is a pattern to separate all the data access logic from your application into separate container classes. It is good practise to create Repositories for each Domain area of your application and separate data access concerns, like CRUD operations within these. For e.g. I have the following Domains within my application Accountable (A personal Accounts App):


  • LedgerUser – User details
  • LedgerPeriod – Date from/to for each Accounting period defined by the LedgerUser
  • LedgerTransaction – Ledger Transactions that occur each Ledger Period.
  • Many more….

‘I’m not going to go into massive detail, but each Repository of each domain would have the following methods which are generally found in data access:


  • Create – Create new records
  • Update – Update existing records
  • Delete – Delete existing records
  • Find – Find records

Do design your Data Source correctly then apply the Repository classes to these. So this should make you think There is a lot of duplicate code here…..”  What do we do in these cases? We write some generic Interfaces to impose some rules on how our Repositories should behave. Please raise your classes (get it…?!) to IRepository:


public interface IRepository<TEntity> 
    void Create(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
    IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> FindAll();
    TEntity FindById(Guid id);




See we have used IQueryable so that we can use other awesome chained LINQ methods (like OrderBy).


So this all lovely, but now onto the nitty gritty, taking that interface and applying it to a concrete example. Because I’m using EF a lot at the moment, i have written a EntityFrameworkRepository example using DbContext and Dbset:


    public class EntityFrameworkRepository<T> : IRepository<T> 
        where T : class, IRepositoryEntity
        internal DbContext context;
        internal DbSet<T> dbSet;

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="context"></param>
        public EntityFrameworkRepository(DbContext context)
            this.context = context;
            this.dbSet = context.Set<T>();

        public void Create(T entity)

        public void Update(T entity)
            context.Entry(entity).State = EntityState.Modified;

        public void Delete (T entity)
            if (context.Entry(entity).State == EntityState.Detached)


        public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
            return dbSet.Where(predicate);

        public T FindById(Guid id)
            return dbSet.Single(o => == id);

        public IQueryable<T> FindAll()
            return dbSet;



As you can see this class also implements IRepositoryEntity, which is an idea I stole off the Pluralsight video I watched, whereby in our IRepository interface where have a FindById method. This is presuming that the Entity in question using id within its design, which all my Entities do, so I’m safe to enforce this:



public interface IRepositoryEntity

    Guid id { get; }





Unit of Work



This is all nice and lovely but where is the data persistence? If you look closely and without just copy & pasting these examples, you will see in the Repository interfaces and concrete implementations, there are “commit” or “save” methods. Why? Well we can abstract this further into a Unit Of Work pattern which will:

  • Handle persistence
  • Share the context within Repositories

This will allow one context to be used without the Repositories having to know about each other or their respective Dbcontext’s. Now because we are good programmers we should first design the interface, IUnitOfWork:

public interface IUnitOfWork : IDisposable

    void Save();



Is that it?! Well yes. What i would like to do in the future is have a GenericCollectionRepository within the Unit Of Work concrete implementations, but i will refactor that in at a later date. So following the pattern of EF, this is the EntityFrameworkUnitOfWork:


public class EntityFrameworkUnitOfWork : IUnitOfWork
        private AccountsContext context = new AccountsContext();
        internal IRepository<LedgerAccount> account;
        internal IRepository<LedgerUser> user;
        internal IRepository<UserType> userType;
        internal IRepository<Image> image;
        internal IRepository<SystemReference> systemReference;
        internal IRepository<LedgerService> ledgerService;


        public IRepository<LedgerAccount> Account
                if (account == null)
                    account = new 
EntityFrameworkRepository<LedgerAccount>(context); } return account; } } public IRepository<LedgerUser> User { get { if (user == null) { user = new EntityFrameworkRepository<LedgerUser>(context); } return user; } } public IRepository<UserType> UserType { get { if (userType == null) { userType = new EntityFrameworkRepository<UserType>(context); } return userType; } } public IRepository<Image> Image { get { if (image == null) { image = new EntityFrameworkRepository<Image>(context); } return image; } } public IRepository<SystemReference> SystemReference { get { if (systemReference == null) { systemReference = new
EntityFrameworkRepository<SystemReference>(context); } return systemReference; } } public IRepository<LedgerService> LedgerService { get { if (ledgerService == null) { ledgerService = new
EntityFrameworkRepository<LedgerService>(context); } return ledgerService; } } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } }

The beautify of this approach is the reduction in business logic within your Controller of your MVC Application and reducing "controller bloat”.


Here is an example of the both patterns working in harmony:



public class LedgerUserController : Controller
       private EntityFrameworkUnitOfWork unitOfWork = 
new EntityFrameworkUnitOfWork(); // // GET: /LedgerUser/Details/5 public ActionResult Details(Guid id) { LedgerUserViewModel viewModel = new LedgerUserViewModel(); UserType userType = new UserType(); try { viewModel.LedgerUser = unitOfWork.User.FindById(id); viewModel.UserType = unitOfWork.UserType.FindAll() .SingleOrDefault
(u => == viewModel.LedgerUser.UserTypeId) .Description; viewModel.UniqueKey =; return View(viewModel); } catch (ArgumentNullException ex) { Console.WriteLine("ArgumentNullException " + ex.ToString()); } catch (InvalidOperationException ex) { Console.WriteLine("InvalidOperationException " + ex.ToString()); } return RedirectToAction("Index", "Home"); } }


All my controller is doing is what is was designed to, setting up the views data ready for rendering.


I know the code on these sites isnt the best, but i want to create a github repo of it soon. Watch this space! Smile





















Enhanced by Zemanta

[AJAX] IE and its stupidity–Part 100255454577 – Ajax Caching

This is a note to anyone who uses Ajax and Http GET requests – turn off cache for each request otherwise IE wont refresh and display the latest response. Good example is in JQuery:

  type: 'get',
  url: url,
  cache: false,
  success: function(result) {

This nice little method allows you to pass a parameter called cache which you need to set to false.

Another method in JScript is to provide dummy URL parameter to fool the old dog into refreshing:

var url = '/accountstest/SiteAdmin/Dashboard' + "?dummy=" + new Date().getTime();

Chrome and Firefox do not have this problem.

Reading AJAX For Dummies

Reading AJAX For Dummies (Photo credit: daveynin)

Enhanced by Zemanta

[MVC3] ViewModel Binding To Controller–POST Methods

Now we should be writing strongly typed Views based on our Models. Now in some cases you may want to use the ViewModel pattern, which allows you to create a View based on:


a) One Model and some additional properties

b) Two or more combined Models

c) Two or more combined Models plus some additional properties.

These ViewModel classes would sit in a folder structure, you guessed it, ViewModels in your Visual Studio Project.An example would be my RegisterViewModel i have created:



public class RegisterViewModel {
    public RegisterModel RegisterModel { get; set; }
    public string UniqueKey { get; set; }
    public bool Thumbnail { get; set; }




So this is quite straight forward really. I have a RegisterModel which is the MVC default Membership model for handling when a new user Registers. I have a property called UniqueKey which will hold the of a created user, and a Boolean field Thumbnail which will be set to true if he want thumbnail images or false if we don’t.

So this is nice a simple then. So what this means that in our GET Action controller for register we can setup the required values. In this instance we only set the Thumbnail property:


// GET: /Account/Register public ActionResult Register()
    var viewModel = new RegisterViewModel {
        Thumbnail = true };

    return View(viewModel);



Then in our Review View, we need to declare our ViewModel instead of our RegisterModel, plus all our Model fields and the additional properties are parsed:


@model MvcImage.ViewModels.RegisterViewModel @using MvcImage.Models
@using Bradaz.OpenSource.MVC
@using Bradaz.OpenSource.MVC.HTMLHelpers

@{     ViewBag.Title = "Register";
} @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
    <div> <fieldset> <legend>Account Information</legend> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.UserName)
            </div> <div class="editor-field"> @Html.TextBoxFor(model => model.RegisterModel.UserName)
                @Html.ValidationMessageFor(model => model.RegisterModel.UserName)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.Email)
            </div> <div class="editor-field"> @Html.TextBoxFor(model => model.RegisterModel.Email)
                @Html.ValidationMessageFor(model => model.RegisterModel.Email)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.Password)
            </div> <div class="editor-field"> @Html.PasswordFor(model => model.RegisterModel.Password)
                @Html.ValidationMessageFor(model => model.RegisterModel.Password)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.ConfirmPassword)
            </div> <div class="editor-field"> @Html.PasswordFor(model => model.RegisterModel.ConfirmPassword)
                @Html.ValidationMessageFor(model => model.RegisterModel.ConfirmPassword)
            </div> <div class="editor-label"> @Html.Label("Avatar")
            </div> <div class="editor-field"> @Html.UploadImageFor(model => model.UniqueKey,thumbnail:true)
            </div> <div class="editor-field"> @Html.HiddenFor(model => model.Thumbnail)
            </div> <p> <input type="submit" value="Register" /> </p> </fieldset> </div> }


NB: I have changed my UploadImageFor HTML Helper to include Thumbnail support. This will be documented separately and released under my Open Source MvcImage Project.

So this all sounds simple right? Well you may get into a bit of a pickle (like me) when handling the POST Register ActionMethod. This would be peoples first attempts, which are both wrong:

Attempt 1

public ActionResult Register(RegisterModel registermodel,
    HttpPostedFileBase imageLoad2)
    ///---Code something }

Attempt 2

public ActionResult Register(RegisterViewModel registerviewmodel,
    HttpPostedFileBase imageLoad2)
    ///---Code something }


These are wrong if you wish to access the additional properties and the ResgiterModel within the RegisterViewModel. Let me explain:


Attempt 1 – You would be able to access the RegisterModel properties but not the Thumbnail property.


Attempt 2 – Your RegisterModel would be null and you wont be able to access the Thumbnail.


After these attempts most people scratch their head, curse, then head over to ASP.NET/FORUMS or stackoverflow for an answer. Well it took me a lot of scratching, googling and forum posting (plus nagging my poor friend Shawson!) to find the answers. The answer lies in how MVC binds the Models. The best place to start is in Fiddler, which is a free application for debugging HTTP and is very useful. Here is a glimpse of the form POST when i hit the Register button on my view:





As you can see our RegisterModel properties are prefixed with “RegisterModel” and our Thumbnail is just Thumbnail. So if you apply the MVC Binding on this, in the two attempts above, in the first attempt, MVC recognises RegisterModel as these have been binded from the HTTP post data, so are available. Thumbnail though isn’t available in the RegisterModel declaration in the class so this is ignored. In the 2nd attempt there is no RegisterViewModel in the POST so the binding will fail, thus nothing is available and you will get null fields.


The answer is the following:

public ActionResult Register(bool Thumbnail, 
[Bind(Prefix = "RegisterModel")]RegisterModel registermodel,
    HttpPostedFileBase imageLoad2)
    ///-Code something }


So here we declare Thumbnail as its own separate parameter and Bind the RegisterModel with a Prefix “RegisterModel” using the BindAttribute.  This allows us toaccess our RegisterViewModel properties AND Models within our controller quite happily.

I hope this helps you when using ViewModels.

Enhanced by Zemanta