Entity Framework: Delete Entity by Id – Using Detached Instance

Entity Framework 5, with the Code First approach can do some pretty powerful things without much effort. Create your model classes, and it spins up a brand new and shiny database for you.

But sometimes you do need to tweak a few things in order to achieve what you want. For example, I don’t want to load an entity before I can delete it. What’s the point? Say I have a list of Accounts on a webpage, with a shiny delete button that makes an AJAX call to an MVC controller, (or Backbone model, that hits the web backend). In that situation I’ll only have the Id of the entity, which should be enough to delete it.

Attach, Delete

To delete only by Id, you need to create a dummy instance of your model with the Id you wish to delete.

Account account = new Account { Id = 123 };

Then, with EF5 you will have to attach the entity to its DbSet.


Then mark it as deleted, and save the changes.

this.DbContext.Entry(account).State = EntityState.Deleted;



Backbone.js Compatible Routes for, non-Web API, ASP.NET MVC projects

Backbone.js has become my JavaScript MV* framework of choice (you do use a JavaScript MV* framework, to structure JavaScript, right?). I find myself using ASP.NET MVC for less and less that has something to do with views, and other stuff that belongs on the client.

The server, being ASP.NET MVC, is the new backend now a days. I’m sure that’s how Microsoft sees it as well, with the release of Web API.

cc by-nc-nd Bruno Monginoux www.photo-paysage.com & www.landscape-photo.net

When using models in Backbone, and specifying the urlRoot setting, Backbone will automatically construct URLs to do CRUD operations against your server. It uses RESTful URLs, and regular ASP.NET MVC controllers are not compatible with those out of the box.

Consider this Backbone model and collection:

var Account = Backbone.Model.extend({
	urlRoot: "/accounts"

var AccountCollection = Backbone.Collection.extend({
	model: Account,

	url: "/accounts"

When you save a new Account, Backbone will make a POST request to your server expecting to hit your AccountsController. But with regular MVC controllers (non-Web API, that is) the routing won’t succeed, since the default {controller}/Index action only works with the default, parameter less GET request.

You might think that this controller will work:

public class AccountsController : Controller
	public JsonResult Index()
		List accounts = new List();
		accounts.Add(new Account { Id = 1, Name = "Account 1" });
		accounts.Add(new Account { Id = 2, Name = "Account 2" });
		accounts.Add(new Account { Id = 3, Name = "Account 3" });

		return Json(accounts, JsonRequestBehavior.AllowGet);

	public JsonResult Index(int id)
		return Json(new Account { Id = id, Name = "Account " + id }, JsonRequestBehavior.AllowGet);

	public JsonResult Index(Account model)
		return Json(model);

	public JsonResult Index(int id, Account model)
		return Json(model);

	public ActionResult Index(int id)
		return View();

But as mentioned before, the default Index routes doesn’t work that way. This won’t even build, since the method signature of Get and Delete are the same.

Route constraints to the rescure

Ideally we want our controller to look like the following:

public class AccountsController : Controller
	public JsonResult GetAll()
		List accounts = new List();
		accounts.Add(new Account { Id = 1, Name = "Account 1" });
		accounts.Add(new Account { Id = 2, Name = "Account 2" });
		accounts.Add(new Account { Id = 3, Name = "Account 3" });

		return Json(accounts, JsonRequestBehavior.AllowGet);

	public JsonResult Get(int id)
		return Json(new Account { Id = id, Name = "Account " + id }, JsonRequestBehavior.AllowGet);

	public JsonResult Create(Account model)
		return Json(model);

	public JsonResult Update(int id, Account model)
		return Json(model);

	public ActionResult Delete(int id)
		return View();

So for this to work, we need to point the individual HTTP verbs to their own action. This can be done by adding an HTTP method route constraints, when mapping routes in your RouteConfig (or Global.asax):

routes.MapRoute("Model_GetAll", "{controller}", new { action = "GetAll" }, new { httpMethod = new HttpMethodConstraint("GET") });
routes.MapRoute("Model_GetOne", "{controller}/{id}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint("GET"), id = @"^\d+$" });
routes.MapRoute("Model_Post", "{controller}", new { action = "Create" }, new { httpMethod = new HttpMethodConstraint("POST") });
routes.MapRoute("Model_Put", "{controller}/{id}", new { action = "Update" }, new { httpMethod = new HttpMethodConstraint("PUT") });
routes.MapRoute("Model_Delete", "{controller}/{id}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint("DELETE") });

Now you can code away in Backbone, and always hit the correct MVC controller actions. If you want to avoid this, upgrade your MVC app to MVC 4 and use Web API controllers. They support this out of the box.

How To Hit Back When Your Boss Uses Salary Statistics To Negotiate

You sit in a meeting with your boss, negotiating your salary.

Of course, you’re the awesome developer and feel like you should be paid 10x as much as the guy sitting next to you. You know that smart developers who gets things done are scarce, very scarce!

And yet, your boss is arguing that your salary should be X because that’s the average salary for a developer in your area, based on some crappy statistics he pulled off of a website just before the meeting.

How To Hit Back

With all the confidence you can get, you must counter argue by saying that you are not an average developer. That you think this company needs more than average people to carry out their goals and deliver products that aren’t average either. And  that he must up his game dramatically, if the negotiations should continue.

By the way…

I have a bunch of invites for Stack Overflow Careers, so if you’re interested ping me on Twitter and I’ll invite you.

Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library

Recurly is a full suite recurring payment service that lets you easily create subscription plans, billing cycles, handle customers, revenue etc.

They made payment integration dead easy with their awesome JavaScript library called Recurly.js that you can use to inject a payment form onto any page with a simple piece of JavaScript, a long with a server generated signature.

But .Net as a platform, and C# as a language is not very well supported by Recurly. They don’t event provide a client library for creating those signatures.

I needed a client library and wrote this simple class that I’ve now uploaded to Nu Get. The package is called RecurlyJS, and the source code is on GitHub.


Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes

ActionFilters in ASP.NET MVC are great.

You can now easily share logic between controllers without having to inherit from a base controller, that does the common work.

I have a content heavy application that supports a set of layouts. Each layout is rendered by setting the Layout view dynamically, which I do from an ActionFilter. My ActionFilter is fully tested, but when you delegate work to an ActionFilter, you should write a test that ensures the filter is defined on the action.

Not surprisingly, this is very simple and relies on reflection (Download from Gist: https://gist.github.com/2605628):

/// <summary>
/// Verifies the controller action, contains an attribute of the specified attributeType.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="action">The action method.</param>
/// <param name="attributeType">Type of the attribute to look for.</param>
/// <returns>Returns true if the attribute was present on the action. Otherwise false.</returns>
public static bool VerifyControllerActionAttribute(this Controller controller, Func<ActionResult> action, Type attributeType)
    MethodInfo methodInfo = action.Method;
    object[] attributes = methodInfo.GetCustomAttributes(attributeType, true);
    return attributes.Any(a => a.GetType() == attributeType);

And the usage looks like this:

public void Index_ContainsTemplateLayoutAttribute()
    HomeController controller = new HomeController();
    bool containsAttribute = controller.VerifyControllerActionAttribute(controller.Index, typeof(TemplateLayoutAttribute));

Need an introduction? Watch a video about unit testing ASP.NET and MVC based web apps on Vimeo, published by Typemock.

Make features obvious — forcing usage is even better

When creating software, make your features obvious.

A long time ago, Facebook introduced friendlists – a feature where you can group friends by any name you want.
Along comes Google+, and have a feature called circles that, unlike Facebook’s lists, are very obvious and an integral part of the design and workflow for when adding friends. All over the press, this is the feature they focus on claiming it has an advantage over Facebook. It seems as if they don’t know about the lists feature of Facebook, which makes it very important to focus on the features you need and make them obvious.
People use what they can see, and what they’re forced to use.
It also makes you think about the countless times, when someone says “I hate the bla bla bla” – and most technical minded people just says, “you can turn it off”. This is a typical response, but the problem might be that the defaults are incorrect.

ASP.NET MVC Localize Numeric (data-val-number) Validation

Another buggy experience in ASP.NET MVC. This has to do with validation, more specifically numeric validation. Whenever you have a numeric property on your view models, ASP.NET MVC automatically adds some implicit validation to ensure that whatever entered in fact is a numeric value.

Might be good in most cases, but here’s the problem. The validation mechanism writes the error messages in english. So for any app that targets a non-english audience, this needs to be changes.

But that’s easier said than done. The code in ASP.NET MVC that generates the error message for the implicit numeric validator, looks like this:

private static string MakeErrorString(string displayName) {
  // use CurrentCulture since this message is intended for the site visitor
  return String.Format(CultureInfo.CurrentCulture, MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric, displayName);

To make matter worse, this is a method from an internal, sealed class. They didn’t want you to change this.

The only option is to remove the validator, and get rid of the implicit validation. To be honest, I prefer to take care of validation myself, through data annotations on my view models. I don’t like when too much gets done implicitly. I want to be in control, and I want to know what is going on.

You can remove the validator in Global.asax:

foreach (ModelValidatorProvider prov in ModelValidatorProviders.Providers) {
  if (prov.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider))) {

If you’d like to keep the numeric validation, but be able to override the error message, there’s a great way to roll your own ClientDataTypeModelValidatorProvider that does this the right way.

Things will get better

I was browsing through the source code of ASP.NET MVC 4, and found a changeset that looks like will fix this issue. In short, it will be possible to define your own ResourceClassKey, and the MVC framework will use that before using default error messages. Nice!


10 Ways to (re) Structure JavaScript

Structuring JavaScript can be a job in itself if you don’t look out. I was attending the virtual jQuery Summit 2011, and one of the talks were called ‘Structuring Your DOM-based Application‘ by Garann Means. Her talk really took me back to the days of fighting un-structured JavaScript.

I was working on a code base that had been maintained by a handful of different developers, each with different skills, ideas and disciplin. Web development, and especially JavaScript requires a lot of disciplin in order to keep the code clean and structured, and that just wasn’t the case at that time.

While I was watching Garann’s talk, I constantly thought of all the problems we had and what we eventually did to solve our issues and take control of our JavaScript.

This is is my 10 ideas on ways to (re) structure JavaScript, get it under control, get rid of legacy code and improve the quality of a code base.

1. Move all JavaScript code into js files

While this should be obvious for all of us, it’s just something I constantly see people don’t do. Instead of having these nice js files, JavaScript is thrown into view files.

First of all, this means that the same code is delivered to the client everytime a page is requested. Depending on the amount of JavaScript tucked into the view, this can easily add up to hundreds of kilobytes which slows down your sites load time. With JS files, you can easily cache those files on the client, save bandwidth and increase the speed of your site.

Secondly, it makes the JavaScript much more difficult to maintain. You basically can’t find what you’re looking for, it’s hard to have shared and general purpose functions that you can use from several views and you declare everything in the global scope.

2. Use closures, to avoid working in the global scope

JavaScript’s biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.

Douglas Crockford, http://www.jslint.com/lint.html – (Global Variables paragraph)

To solve this problem, we need to wrap all of our code in closures.

A closure changes the context your code is executed within, to be inside the closure and not in the global scope. This means that all your functions and variables inside your closure is not available for others, outside the closure unless you explicitly expose them.

A closure is often referred to as an Immediately Invoked Function Expression (IFFE), and it is pretty much a function that acts as a wrapper around your code:

(function () {
  // your code here

Read more about closures and IIFE’s here.

3. Improve jQuery selectors

jQuery selectors are very powerful. It’s dead easy to write selectors that gets a bunch of elements in the DOM, and they can easily get pretty advanced.

This can have an impact on the performance of your code. Running in the browser, the efficiency of your code has a direct impact on the user’s experience.

Since getElementsByClassName is not implemented by all browsers, the ones that don’t have it will suffer when you query the DOM by class class name.

That means you can speed up your jQuery selectors by specifying the tag name before the class name:

BAD: $(".price-label")

GOOD: $("span.price-label")

You can also improve performance by limiting the context in which you select. You do that by specifying a second parameter to the selector which could be a container element that you’re working inside:

var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);

4. Cache elements, instead of selecting from the DOM

Using jQuery to select elements from the DOM is expensive. Some selectors are more expensive than others, but if you’re going to use the same element multiple times in a functions, you’re better off storing it in a local variable instead of selecting it every time.

When you select an element like this: $(".price-label") it’s like having a huge swimming pool (the DOM), and telling your little brother (jQuery) to jump in and find all USD coins in there. And if you do the same on the next line of code, he has to jump in again, swim around the pool looking for USD coins.

And if the pool is junked up with loads of coins in other currencies, he has to look at each end everyone of them to determine whether or not it is a USD coin.

Some browser has a native function called getElementsByClassName, as opposed to getElementsByTagName. That does speed up the above example a little, but it is still much more effective to cache the element in a local variable.

It’s just a matter of saving an element to a local variable, and the use that in the rest of you code:

var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);

5. Get rid of HTML in JavaScript

Just like JavaScript should not be added to your HTML pages, HTML should not be generated inside JavaScript by concatenating strings.

Client side template libraries are getting more and more popular, so utilize the <script type=”text/template”></script> and embed your client side view templates there.

Or even better. Pre-compile your client side views into JavaScript using something like HoganJS, place the code in a separate file and embed that. Not only will the footprint be smaller, but you also get caching and you speed things up since they’re already compiled!

6. Upgrade jQuery

This should be a no-brainer. But code-bases get stuck on old versions for a variety of reasons. Maybe you rely on a plugin that doesn’t work with the latest version, or you use lots of deprecated stuff that would take ages to rewrite.

Plugins that are stuck on older version, and are not compatible with future versions must die! You should not hold yourself hostage due to a plugin – get rid of it, fix the error, rewrite the plugin yourself and host it on Github. Never get stuck!

Same for deprecated code. It’s a huge warning signal and you need to react!

In general, stay up to date on the project. New concepts, bug fixes and performance improvements are added all the times. Subscribe to their blog, read the release notes everytime they release a new version to get familiar with the new stuff.

7. Teach your colleagues

It is widely misunderstood, but a lot of developers tend to think of JavaScript as a language you don’t have to learn, in order to write and maintain it. I don’t know of any other language where this is the case, but loads of developers just think of JavaScript as “not real code” that “just lives in the browser”, and more or less “doesn’t matter”.

This is one of the many reasons why JavaScript gets out of control. Too many incompetent developers are writing it, and it’s a tough job to get it under control if you’re the only true JavaScript developer where you work.

First of all, tell your colleagues to watch JavaScript – The Good Parts by Douglas Crockford. This touches on what’s great and what’s bad in JavaScript, and any developer that don’t really know the language will realize that they’re doing a lot of stuff wrong.

If you have to write JavaScript – man up and learn the language.

8. Combine, compress and cache your JavaScript.

In order to increase the performance of any website, minimizing the amount of files the browser needs to download, and minimizing the size of each file is vital.

First of all, install YSlow in your browser and start examining what you have to improve.

If you haven’t optimized for fewer HTTP request, you’ll notice that’s the top thing YSlow tells you to do. Find inspiration and guidance on how to minify and optimize JavaScript and CSS files. It’s easy.

Next up is caching. First thing on this list, suggests that you should move JavaScript into js files. And this is why: Having js files, that is embedded on a page makes it really easy to cache on the client. Most webservers already sends out proper HTTP headers to allow static files, such as JavaScript to be cached on the client.

What you have to make sure, is that you’re able to bust the cache. Either use expiration headers, or add a version indicator to the URL of the file. Next time you deploy, increase that number to make it a new URL.

9. Use a Content Delivery Network – CDN

If you have lots of traffic, from all over the world. You can benefit from hosting your JavaScript files on a Content Delivery Network. With all the new cloud hosting companies out there, this has become exceptionally cheap.

For jQuery and other common libraries, you can also use the CDN hosted files provided by jQuery, Google or Microsoft.

10. Write JavaScript Unit Tests

Some people would probably say this should not be the last thing to do. But I think you need all the low-hanging fruits, that you can accomplish before you start dramatically changing the way you go about writing JavaScript. And unit testing JavaScript is going to do that.

There are several good unit testing libraries for JavaScript. The more popular are QUnit and Jasmine.


There’s a lot of things you can do to re-structure and get control of JavaScript. One thing is for sure. If you do nothing, things will get messy.

This was my take on what can be done, things I’ve done in the past with great success.

What do you think is missing, what have you done that greatly improved the quality of your JavaScript code-base?

JavaScript Bundling Issues When Using Unfinished Closures

We all know it’s a good idea to bundle JavaScript files into as few script includes as possible to minimize HTTP request.

And – we all know you should write your code inside closures, to avoid the biggest problem of JavaScript: its dependence on global variables!

But what happens when those two things don’t work together?

For me, they didn’t play nice with each other today. Whenever I bundled my JavaScript files i got an Uncaught TypeError: undefined is not a function.

Consider this code:

/****** a-file.js ******/
!function($) {
  // Code here

/****** another-file.js ******/
(function ($) {

The error occurred on the first line, inside the closure in another-file.js. Take a look at this jsFiddle.

Since the result of the first closure is true, the above code will evaluate as this:

/****** a-file.js ******/

/****** another-file.js ******/
(function ($) {

The only thing missing, is a semicolon to finish off the first closure (updated, and working jsFiddle):

/****** a-file.js ******/
!function($) {
  // Code here

/****** another-file.js ******/
(function ($) {

Now, this is a trivial thing to get right, if you were only dealing with your own code base. But with loads of plugins, external libraries and such – you can only pray for the best!

In my case, the script that were causing the error was Twitter Bootstrap scripts. They were all missing the semi-colon in version 2.0, the issue was submitted a month ago, and later fixed


ASP.NET MVC 3 Windows Authentication problem – redirects to Account/Login

ASP.NET MVC 3 has its quirkiness here and there. Sometimes it’s a lack of support for something, and other times it’s downright buggy.

An issue I came across recently, is something to do with Windows Authentication. There’s a lot of resource on the web on how to run ASP.NET MVC with Windows Authentication. There’s even a project template, the Intranet site, which ships with MVC 3. It should be a no-brainer!

The issue I came across, prevented ASP.NET from using Windows Authentication. Even though I had set authentication mode to Windows in Web.config:

<authentication mode="Windows" />
  <deny users="?" />

And disabled anonymous authentication on the website in IIS – it always redirected all requests to /Account/Login, as if it was using some sort of default Forms Authentication.

This coursed a server error – the dreaded Yellow Screen of Death, since I didn’t have a login form on my site, I had no controller/action for Account/Login.

Known issue

After searching the web for a while, I came across the release notes on the ASP.NET MVC website. At the bottom, there’s a section called ‘Known issues‘, and one of the last issues reads:

There’s a known issue that causes Forms Authentication to always redirect unauthenticated users to ~/Account/Login, ignoring the forms authentication setting used in Web.config. The workaround is to add the following app setting.

      <add key="autoFormsAuthentication" value="false" />

And much to my disappointment, this didn’t do the trick! Long story short, it turned out that I needed another setting as well, as pointed out in the comment of this Stackoverflow question:

<add key="enableSimpleMembership" value="false"/>

After adding the magic settings to my Web.config, everything worked as it should – and Windows Authentication on ASP.NET MVC is now a no-brainer!