Updating one to many relationship tables using Entity Framework 6

Problem Statement

Consider the following diagram, where there is one to many relationship between the Employee and Assest table. Here 1 Employee can have M Assests.

enter image description here

Lets say an Employee has 2 assests namely –

OldList NewList
Home Home
Bike Car

So there are 3 things to be done when updating this data using the Entity Framework

  1. Look for items present in the newlist and missing in the oldlist, these items are to be added. The item “Car” in this example.
  2. Look for items present in the oldlist and missing in the newlist, these items are to be removed. The item “Bike” in this example.
  3. And finally the items that are present in both the list. The item “Home” in this example, is to be untouched.


The following code uses ExceptBy extension method to compare two lists and return based on the key passed to it.

public void UpdateEmployeeAssests(int employeeId, List<EmpAssets> updatedAssests)
    using (var context = new SampleDbEntities())
        List<EmpAssets> oldAssests = context.EmpAssets.Where(x => x.EmployeeId == employeeId).ToList();

        List<EmpAssets> addedAssests = updatedAssests.ExceptBy(oldAssests, x => x.CityId).ToList();
        List<EmpAssets> deletedAssests = oldAssests.ExceptBy(updatedAssests, x => x.CityId).ToList();

        deletedAssests.ForEach( x => context.Entry(x).State = EntityState.Deleted);
        addedAssests.ForEach(x => context.Entry(x).State = EntityState.Added);



Validation summary with custom message for each field in Angular JS

It is a common requirement to list down all the validation errors of a form in one place, however when using Angular, this gets a little tricky to do it the “Angular Way”.

1. Showing validation summary of the form

    <li ng-repeat="(key, errors) in form1.$error track by $index"> <strong>{{ key }}</strong> errors
            <li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>

Screenshot : This can be demoed here – http://plnkr.co/edit/05oDTf?p=preview

enter image description here

2. Showing Errors next to input fields

<form name="userForm" ng-submit="submitForm()" novalidate>
 <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
   <input type="text" name="name" class="form-control" ng-model="user.name" required>
   <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>

3. Disabling the form submit button, if any of the form input fields are invalid.

<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>


Injecting into Custom Validation or Authorization Attributes in ASP.NET MVC

Dependency Injection can be done when using Custom Validation or Authorization attributes in ASP.NET MVC. This can be achieved Ninject’s Property injection.

Here is an example of property injection. For a property to be injected it must be annotated with [Inject].

public class ZipCodeAttribute : ValidationAttribute
    public IZipCodeService ZipCodeService { get; set; }

    public override bool IsValid(object value)
        if (value == null)
            return true;

        if ((value is string) && string.IsNullOrEmpty((string)value))
            return true;

        var zipCode = Convert.ToInt32(value);
        return this.ZipCodeService.IsValidZipCode(zipCode);

More on “Injection of validators” can be read here.

How to get a list of all users when using ASP.NET Membership ?

ASP.NET Membership helps you manage user authentication for your websites. Its supports facilities to create user, assign roles, reset password and almost everything under the user management domain.

Its a common requirement to list down all the users using the ASP.NET Membership provider. Though ASP.NET Membership has a inbuilt MembershipProvider‘s MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords); method where you can pass pageIndex, pageSize using which paging also can be handled.

However I found an another way to get this list, without having to play with the pageIndex and pageSize options on this StackOverflow thread.

var users = Membership.GetAllUsers();

var userList = new List<MembershipUser>();
foreach (MembershipUser user in users) 

Injecting dependencies into WebViewPages / Razor View in ASP.NET MVC

Even before you start reading this post, I am sure many of you ll would have already had discussions on this like

“Why would you need to access services on your view?”


“Why would you want to inject dependencies into your view?”

and even

“Shouldn’t your View be plain and dumb and be used only to render HTML from a model?”

But anyways here is something that should help you, should you want to inject dependencies in your views.

For example’s sake let’s consider you have a ‘PermissionService’ which has a method IsModuleAllowedForUser(Guid userId, string moduleName) which decides if the module is allowed for the user and only then renders it. Now I want to access this service method from my view.


namespace Demo.Service.Core
    public class PermissionService : IPermissionService
        public bool IsModuleAllowedForUser(Guid userId, string moduleName)
            // blah

Here’s a way to do it.

To start with we’ll need to create a class which will inherit from the WebViewPage class. I have injected the IPermissionService using property inject with Ninject.


using System.Web.Mvc;
using Ninject;

namespace Demo.Web.Core
    public abstract class MyInjectedWebViewPage : WebViewPage
        public IPermissionService PermissionManager { get; set; }

in my NinjectWebCommon.cs class I have added bindings for the same


and now in the view I can use the services like as shown below

@inherits MyInjectedWebViewPage

@if(PermissionManager.IsModuleAllowedForUser(Helper.GetUserId(), "precious"))
    <div>My precious div!</div>

Hope this helps :)


  1. ASP.NET MVC 3 Service Location, Part 3: View Engines/View Pages
  2. Can you inject dependencies into a constructor of a custom WebViewPage, using an IOC container?

Using GIT with Visual Studio 2013

Git, has been around for quite some time now. All major repository hosting services like GitHub, Bitbucket and now even Codeplex recommended users to opt for GIT as a recommended/default type of source control system for your project.

I have been avoiding GIT for a very longg time, the only reason being is familiarity and love for SVN :) So when I wanted to created a new project – qask on Codeplex and found that the SVN option was no longer present on codeplex. I decided to (finally) give GIT a try…

enter image description here

You might also want to read this beautiful question & answer on GIT vs SVN : Why is Git better than Subversion?

1. Changing the Source Control plugin

Once you have your project opened, go to ‘Tools > Options’, go to ‘Source Control’ sub menu and select ‘Microsoft Git Provider’ from the source control plugin dropdown and press ‘ok’.

enter image description here

and that’s it.

2. Commit and Sync

Once you have configured as above, your team explorer will look something like this :

enter image description here

you can see your pending changes, and commit with a message using the screen below :

enter image description here

enter image description here

Post every commit you will be given an option to sync, you can sync every time you commit or whenever you want to.

enter image description here

enter image description here

enter image description here

Hope this helps. A more detailed post on Git version control with Visual Studio 2013 is present here, a must read for any newbies to GIT.

Using timeouts in Angular JS

Angular provides $timeout, a wrapper forwindow.setTimeout. To use $timeout you will need to inject it into your controller.


$timeout(fn[, delay][, invokeApply]);


var app = angular.module('myApp', []);

function Ctrl($scope, $timeout) {  
     $scope.message = "Hello";
     $timeout(function(){$scope.message = "Hello after 3 seconds";}, 3000);       

Update : Found this really interesting thread on SO – What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?

Hope this helps :)

PageDown Editor for Angular JS

I have always been fascinated by stackoverflow’s markdown/pagedown editor, So when I needed an text editor for a project(question & answer site) I have been working on lately in my spare time – QASK, I decided to go with a similar editor built for Angular JS.

Though there were many directives available for this, none of them were as complete and easy to use as angular-pagedown

Demo : http://plnkr.co/edit/9PHabp?p=preview

    <script data-require="angular.js@1.2.22" src="angular.js"></script>

    <script src="Markdown.Converter.js"></script>
    <script src="Markdown.Sanitizer.js"></script>
    <script src="Markdown.Editor.js"></script>

    <!-- The directive -->
    <script src="angular-pagedown.js"></script>

    <script src="script.js"></script>

  <body ng-app="myApp">
    <div ng-controller="myController">
      <pagedown-editor content="data.content" 
      <hr />
      <pagedown-viewer content="data.content"></pagedown-viewer>


A little change in css and here’s how my final page looks like :)

enter image description here

Continue reading “PageDown Editor for Angular JS”

C# ExceptBy() extension method.

The following extension method is used to compare values from two list and it returns entities from the first list which is not present in the second list based on the key that is passed to it.

public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other,  Func<T, TKey> getKey)
    return from item in items
           join otherItem in other on getKey(item)
           equals getKey(otherItem) into tempItems
           from temp in tempItems.DefaultIfEmpty()
           where ReferenceEquals(null, temp) || temp.Equals(default(T))
           select item;


Writing a Custom Html Helper for Button in ASP.NET Razor

Html Helpers are used when we want to have a custom html with/without some logic repeated across your application. Today I wanted to have all the buttons shown across the application behave in a particular way depending upon the logged in user, this can easily be done using HtmlHelper.


public static class CustomHtmlHelpers
    public static MvcHtmlString CustomButton(this HtmlHelper htmlHelper, string innerHtml, IDictionary<string, string> htmlAttributes)
        var builder = new TagBuilder("a") {InnerHtml = innerHtml};
        return MvcHtmlString.Create(builder.ToString());

In the IDictionary<string, string> htmlAttributes parameter you can pass all the html attributes you need your button to have, for example: class, href, or any other html attribute for that matter.


@Html.CustomButton("<i class='fa fa-plus'></i>&nbsp; Create Something", new Dictionary<string, string> { { "class", "btn btn-primary" }, { "href", "#create" } })

You might wanna read another related article on Html Helpers.