Category Archives: Entity Framework

Fun with @SignalR

This article has grown a little long in the tooth because SignalR has changed significantly since this was written more than a year ago.
I recently co-wrote a new article with Suprotim Agarwal in the DNC Magazine. If you are a .NET Dev I strongly recommend you subscribe to this Free Bi-monthly Magazine. The source code for the article is on Github Repository of DotNetCurry. You can see the sample live here.


For the past several months I have noticed David Fowler, Damien Edwards, Phil Haack and a few other MS Techies I follow on twitter, tweet excitedly about a new framework called SignalR. I didn’t understand the excitement fully and to be honest didn’t try too hard to figure out.

Yesterday Scott Hanselman published this article and re-distributed a link to an article which he wrote end of August, 2011. After going through both, I really wanted to take a closer look at SignalR, and while trying to get his ‘…monkey typing Shakespeare…’ code working I finally had the ‘Ah ha!’ moment.

I just had to come up with this quick and dirty sample to demonstrate a use for SignalR and since I want the bragging rights for it, I am going to throw it up as is without bothering about the niceties of a Nuget package or sample.

UPDATE: I have deployed a working sample of this application at

The Idea

First time I saw Google Wave’s technology demo where they showed multiple people editing/reviewing the document at the same time, it blew me away. I was fascinated by it, but told myself I was too ‘javasciptically challenged’ to design such an Async client side framework.

When my tubelight** finally came on, SignalR was the obvious way to do it. Following is my first rough cut that as of now only syncs content. We’ll get to the fancy colored carets at a later point (hopefully in another article).

**In India one is referred to as a tubelight if something strikes late. Back in the days of non-electronic ballasts for fluorescent lighting, the tubes used to flicker for few seconds before turning on.

Please go through Scott’s articles or SignalR documentation to understand SignalR better. I make no attempts to explain SignalR here (partly because I know precious little and partly it’s such a fantastic framework that you need very little up front to get going).

Head-first into SignalR

To build a scaffolding for SignalR framework you can use plain html with a backend server side SignalR Hub class as Scott demonstrated. But I chose to start off with an ASP.NET MVC 3 project. (Actually my first attempt at ASP.NET MVC 4 using VS 2011 Dev Preview didn’t quite go so well, so I rolled back to the stable releases of ASP.NET MVC 3 on Win 7 using VS 2010).

Setting up a support app as an ASP.NET MVC 3 web project



I called it ‘FunWithSignalR’ and set it up as an Intranet Application

Adding SignalR to your project using Package Manager Console


The package manager console helps you download Nuget packages among other things. If you don’t have it visible you can bring it up from the above menu (in VS 2010)

SignalR is available as a nuget package and all you have to do to include is run the following command in the Package Manager Console

Install-package SignalR

The above command will get all the dependencies you need for SignalR and if your jQuery script files are not up to speed, will get the latest libraries for jQuery too (SignalR client uses jQuery hence the dependency check results in the upgrade). The output will looks something similar to


Update jQuery dependencies in Views\Shared\_Layout.cshtml by pointing to the most recently updated jQuery version. As per above image the latest version for me today is jquery-1.6.4.min.js because that’s the one the package manager installed.

Setup the Code First EF Model

We’ll setup a very simple code first model by adding one Entity called BlogPost in our Model folder.


Add the DbContext for the BlogPost.


Build the solution at this point.

Scaffold the Controller and UI

To use the default scaffold tooling that comes with MVC 3, right click on the Controllers folder and select Add –> Controller.


Select the Template, Model and Data Context values as shown above and click Add.

At this point you will have the scaffolding necessary to Add/Edit/Delete BlogPosts.

Adding the ‘Review’ Action

Open the BlogPostController and Copy paste the Get and Post action methods for the Edit action. Change Edit to Review as shown below.


Copy the Edit.cshtml and paste it in the View folder. Rename it to Review.cshtml

Update the Index.cshtml such that a ‘Review’ link comes up in the Index


Getting SignalR into the game

The Server Side

In your web project create a folder called SignalR (You can call it anything you want, in a real life project this as server side component and could very well reside in a dll of it’s own).

In the SignalR project add a class BlogHub.cs

Add the following code to it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;

namespace FunWithSignalR.SignalR
public class BlogHub : Hub
<summary> /// The method called from SignalR client (JS)
/// </summary>
///String Data
///Session ID: Used in this sample to track users
///A boolean value used in the example indicating
/// if incoming value should be appended or overwritten when sent back to
/// other clients
public void Send(string message, string sessnId, bool append)
Clients.addMessage(message, sessnId, append);

The Client Side

  • Open Review.cshtml and add the following script references


Note: json2.min.js is not packaged with the SignalR nuget. I have packaged it as a part of my code. I got it from Scott’s ‘Shakespeare demo’.

Note 2: /signalr/hubs is dynamically generated at runtime. So don’t worry if it gives a green squidgy right now. It works fine at runtime. Without this reference SignalR client won’t work.

  • Change the Html helper for the Post property from Html.EditorFor(…) to Html.TextAreaFor(…).
  • Add a hidden field to save the session Id in it (this maybe a security hole, need to investigate best practices)

<input id="sessinId" type="hidden" value="@Session.SessionID" />

  • Drop the following script in
<script type="text/javascript">// <![CDATA[
$(function () {
// Proxy created on the fly
var blog = $.connection.blogHub;
// Declare a function on the blog hub so the server can invoke it
blog.addMessage = function (message, sessnId, append) {

var sessId = $('#sessinId').val();

if (sessId != sessnId) {
if (append) {
else {

// Start the connection

$("#Post").keyup(function (event) {
// Call the send method on the server

var sessId = $("#sessinId").val();
if (event.keyCode >= 65 && event.keyCode <= 122) {
if (event.shiftKey || (event.keyCode == 32)) {

blog.send(String.fromCharCode(event.keyCode), sessId, true);
else {
blog.send(String.fromCharCode(event.keyCode + 32), sessId, true);
else {
blog.send($("#Post").val(), sessId, false);
// ]]></script>

  • If you see closely this is pretty similar to Scott’s 11 lines of code to get a chat client going.

Changes I have made are:

1. Send message to server on KeyUp event of the Post text area, instead of an explicit button push

2. Send more meta information like the current sessionId and if the keystroke means an append action should take place at the client action of an overwrite action should take place at the client option.

Let it Roll

Run the application and navigate to the BlogPost Index


Add a new Post


Click on Review


Press Ctrl+N to start a new browser instance with the same page. Hit F5 so the session id (the text field next to Save button) changes. Arrange the two browsers side by side.

Type in one Post text area and watch the other one change almost simultaneously


As Scott says, Kabooom! brain explodes…..

In Conclusion

To wrap up, we saw how mind numbingly easy it is to use SignalR.

It’s a fantastic abstraction over various techniques available for persistent connections over http. Under the hood it can use websockets or longpolling depending on what’s available.

You can get infinitely creative with it and build fantastic collaborative ASP.NET apps using SignalR backend.

Some day (hopefully) in the near future, I would have overcome my javascript challenges and built a real collaborative editor with all the fancy bells an whistles of Google Docs.

Finally, David Fowler and team, a million thanks for such a fantastic framework. I am loving the ‘just works’ motto Smile. And Scott Hanselman for providing the ‘Aah ha!’ moment, without which I probably would have not given SignalR a look yet.

The Code

The code can be downloaded from here (size 844 KB) (skydrive). It is provided AS IS, with no warranties expressed or implied. You are free to use it without any attribution (but I would love it if you do feed my ego Winking smile).

I have now made the code available on bitbucket Mercurial repository. You can get it from here


The code in bitbucket now uses Google’s diff-match-patch implementation and is hence Apache licensed now.

Tagged , , , ,

Entity Framework and MS Web Stack of Love – First Steps

Things they didn’t show you at MIX keynotes Winking smile

Okay, so you saw the MIX keynotes and were really really impressed with what MVC, EF 4.1 Code First and Scaffolding could do for you and excitedly sat down to try and get your old lumbering enterprise app transformed using the Web Stack of Love. Couple of steps in and you start stumbling around. Visual Studio throws errors, things stop working and you are scratching your head as to where you went wrong! Well happened to me and I got lucky in finding the solutions quickly with help from the community. Here are the details.

Model First or Database First with EF 4.1

As mentioned above the first thing I tried to do was get my old lumbering enterprise app moved to the new MVC platform. Now when you have an enterprise platform you can’t throw it away with the accumulated data of last 5 years. So the easiest way is to go Database first, reverse engineer the database to generate your data model. Below are the steps you would follow

  • Create an ASP.NET MVC Web Application using the new project template
  • Create a generic Class library project
  • Add ADO.NET Entity Data Model file (edmx) to the class library
  • Generate model from DB Connection by connecting to the database. So far so good, no issues.
  • Now you add reference to your database project to the web project, copy the connection string over from the class library’s app.config to web app’s web.config, and build it. Everything builds fine.
  • You right click on the Controller folder and select Add Controller and the MVC tooling wizard comes up. You select your root entity name and ask it to generate the controller, Visual Studio whirrs for a while and bam! Error!

    Microsoft Visual Studio
    Unable to retrieve metadata for ‘Your.Data.Entity’. The type ‘Your.Data.Entity’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

  • So what did you miss. Well EF is all code first so the old style generation of Entities (EF < v4) fail to work. If you read the last line of the error ‘… and does not inherit from EntityObject’ it gives you a hint.
  • What now? Manually edit everything? That would defeat the whole purpose of O-R mapping right? Well solution was provided by Julie Lerman (MS MVP) in her blog here. I’ll summarize here.
  • Go back to EDMX file and open the EDMX designer.
  • Right click and select ‘Add Code Generation Item’.
  • From the ‘Add New Wizard’ select ADO.NET DBContext Generator. You’ll see it gives a (t4 template) name. Change the name if you want to and select Add.


  • You will see under in the class library a node gets added with the t4 template. When you expand the node you have the C# (or VB) classes for your entities.
  • Now build and re-try scaffolding the Controller and things will go through smoothly.

Taming the SQL Compact 4.0 for Model First Development

Here is another workaround for people who want to do Model First Development. Since SQL Compact 4.0 was released out of band from Visual Studio and .NET 4.0 releases, somewhere in the tooling chain something broke. As a result, when you try to add a new Connection using Generate Database Wizard you don’t see SQL Compact 4.0. You see up to 3.5 only. So how do you get 4.0 goodness?

Refer to the selected answer from this thread

The answer is pretty to the point so I won’t repeat it here.

Trouble with Modernizer.js  (ver 1.7.x only on VMs)

If you run your dev environment on a VM (like VM Ware on Mac), IE9 disables hardware rendering and the modernizer.js that ships by default keeps throwing exception ‘Microsoft JScript runtime error: Unexpected call to method or property access’. This happens for every page and become very irritating quickly.
Solution is to go to and download their latest library (2.0.6 at the time of writing this). Remove the 1.7.x reference from your web application and add 2.0.x version. Voila!


That’s about it for now. I’ll put down more of my experiences as I go forward with my EF adventures. When I started this article we had only 4.1 now we have 4.2 CTP out Smile. Fast! Very Fast!

Tagged , , , , , , , , , , , ,
%d bloggers like this: