Improving Model Validation for Entity Framework Core 2.0

If you’ve done .NET programming against a SQL data store for any length of time, you’ve likely run into the following error:

String or binary data would be truncated. The statement has been terminated.

This is an unfortunately common scenario for me and it feels like there is no easy way (at least that I’m aware of) to identify which column/property is the culprit.  I also recently just started working with Entity Framework (I had always preferred not using an ORM prior to this) and figured this would be handled by the framework.   After a bit of digging, I found this in the Ef Core documentation:

Entity Framework does not do any validation of maximum length before passing data to the provider. It is up to the provider or data store to validate if appropriate. For example, when targeting SQL Server, exceeding the maximum length will result in an exception as the data type of the underlying column will not allow excess data to be stored.

Even if I use the [MaxLength(#)] or [Required] attributes, Entity Framework does not look at these prior to submitting changes to the database.  So it looks like it’s up to the developer to solve for this given EF Core is a cross-platform framework capable of working with multiple data stores, each with their own rules.  As a result, I created the extension method below to perform my own validation:

public static async Task<int> SaveChangesWithValidationAsync(this DbContext context)
	var recordsToValidate = context.ChangeTracker.Entries();
	foreach(var recordToValidate in recordsToValidate)
		var entity = recordToValidate.Entity;
		var validationContext = new ValidationContext(entity);
		var results = new List<ValidationResult>();
		if (!Validator.TryValidateObject(entity, validationContext, results, true)) // Need to set all properties, otherwise it just checks required.
			var messages = results.Select(r => r.ErrorMessage).ToList().Aggregate((message, nextMessage) => message + ", " + nextMessage);
			throw new ApplicationException($"Unable to save changes for {entity.GetType().FullName} due to error(s): {messages}");
	return await context.SaveChangesAsync();

Note:  We could also implement IValidatableObject on our model classes and perform more unique validation inside the Validate method and have it covered by this extension method as well.

This method can then be called from within your code as follows:

public class Person 
  public string Name { get; set; }
  public string Title { get; set; }
var person = new Person() { Title = "This title is longer than 50 characters and will throw an exception" };
await context.SaveChangesWithValidationAsync();

Create Your Own .NET Core Templates in 4 Easy Steps

Do you ever develop prototypes, or starter projects/accelerators, that you’d like to use again in the future? A good way to do that is by creating custom templates for dotnet. Once completed, anytime you want to create a new project of that type in the future, you can use key in “dotnet new ” and you’re off, complete with correct namespaces. You can even do conditional checks, or variable replacements.

1. To start, clone or download the MyGameStartup project which will make following along easy. There is nothing special about this, it’s just for the purposes of showing how you can bundle multiple projects, and do some variable replacements. Note: You’ll need .NET Core 2.1 SDK for this at a minimum. Once open, you’ll see a solution file, and a few simple projects with some basic Entity Framework Core behavior.

2. Note that in the downloaded project, there is a folder labeled “.template.config” with a file inside it labeled “template.json”. Let’s review the contents of that file. Feel free to update this file with values you plan to use for your own project type, but you can leave these if you want to just continue with the demo.

I’ve added comments to the file so it is easy to understand, along with a link to the official documentation. There are more features than I am covering here if you wish to add them. A few noteworthy settings in the file are the “shortName” property. This is the trigger for your project, i.e. ‘dotnet new mygamestartup’. Also, if you see the section labeled “symbols”, and then cross-reference this with the projects ‘appsettings.json’ file, you’ll see the connection string’s database will be replaced with the “–db” parameter once we run it.

3. Ready to add this new project type to your available list? I’ll also show you how to remove it if you no longer plan to use this one. Run the following command, from the same folder as the downloaded .sln file and .template.config folder: “dotnet new -i .”. The dot here refers simply to the current directory. You could have also specified the path, but this is easier. If successful, you should see a list of project types, along with your project type added.

New project added screenshot from ConEmu terminal

Woohoo! You now have your own custom accelerator template you can use for other projects. Side note: This screenshot is from the ConEmu terminal which I use. You can download it here.

An important note also on this step. Running the “dotnet new -i .” command will bundle the current folder. I may not have discovered the setting yet, but keep in mind this skips empty folders. So if your wwwroot folder was empty, you will see this is not created after installing. I added a site.css to my version to avoid this.

4. We’re moving along quickly now. Next step… fire up a new project with our new template! Navigate the directory you’d like your project to be a folder within, such as “C:\Users\myusername\source\repos” and then issue the command, “dotnet new mygamestartup –db MyCustomStartupDB -n MyCustomName“. The database name will be set in the connection string in appsettings.json and a folder will be created named MyCustomName. Your projects namespace will also be MyCustomName. Note: If you get an error about a lock, be sure your Visual Studio instance with “MyGameStartup” project you downloaded in step 1 is closed. You may need to remove the MyCustomName folder and try again.

Follow the steps in the README to create the database with the name you specified, and also steps on how to run the Entity Framework Core Update-Database command properly. After that, you’re done! You just created a new project from a template you previously created.

Optional: To Uninstall the project, you can use the “dotnet new -u” command to list the currently installed projects. You should see your “MyGameStartup” project listed here. You can simply remove it with the command “dotnet new -u “Path-To-Folder” such as shown below.

Next Steps: A few steps I haven’t taken yet, but may in the future, is to add the following features to my template:

  • Create a nuget package to easily distribute your new package.
  • Add a new ‘symbol’ to the template.json which has datatype ‘choice’. A choice symbol will allow the user to pick from several options when creating your template.
  • Modifiers can be used to conditionally output certain code or not. You may wish to optionally include authentication as an example. More details here.

Exploring Video Games With the New IHttpClientFactory In .NET Core 2.1

REST services are everywhere. It’s tough to find an application that doesn’t leverage an externally hosted REST service in some way. Prior to .NET Core 2.1, a common library that was used to perform REST requests was RestSharp. I love RestSharp, but let’s explore the new alternative IHttpClientFactory that became available as part of .NET Core 2.1.

In this demo, we’re going to cover a bunch of awesome features:

  • Simple dependency injection
  • Named instances
  • Typed clients
  • Message handlers

In addition, for this service, we’re going to leverage the Internet Game Database API to pull in some data about Nintendo Switch games. As an aside, if you don’t already own a Nintendo Switch, it’s a fantastic device for the family, for travel, or just for fun. If you want to follow along with the code, you’ll need to create a free account here. Once you have your API key, you’ll want to be sure to include that in the code. There is a host of functionality available with this API, and you could use it to start building your video game collection, embed information about games in your apps, and much more.

You may also wish to download the source code for this. It is available on Github here.

Basic Usage

To start, let’s open Visual Studio 2017 and create an ‘Empty’ project denoting ASP.NET Core 2.1 as the framework.

Once we’re up and running, let’s add a few lines to our Startup.cs class. It should look like this when we’re done. Specifically, note the new services.AddHttpClient(); extension method on IServiceCollection which is exposed in 2.1.

Next, let’s create a GameController and a Game class for the purposes of deserialization. Notice how we inject the IHttpClientFactory into the controller constructor? We then use the CreateClient() method of the factory inside the controller action to create a basic instance. A noteworthy feature for IHttpClientFactory is that it maintains a pool of reusable clients, each with a lifetime of 2 minutes by default. This keeps the overhead involved with connectivity and instantiation at a more manageable level by default which is great for our overall performance and scalability.

Named Instances

In the above code, we are defining the HttpClient inside the controller class, but it’s also possible to have a “named” instance of the HttpClient. We could re-write our line from our Startup.cs class above to use this code instead:

Then, inside our controller, we would inject the IHttpClientFactory the same way, but we would change the CreateClient() method to use our named instance.

Typed Clients

Cool stuff so far, right? Let’s take it one more step further: typed clients. Let’s add the interface and class below to our application. Note how we have a private HttpClient as part of our IgdbClient object which exposes developer friendly names for each of the API endpoints we can consume in our application. Note: There are plenty more fields available in this API, including artwork, screenshots, and more but we are just keeping it simple for the demo.

Finally, let’s modify our Startup class to inject our configured client for our application, and also modify our GameController class so that it exposes these two new methods for testing purposes. We’re configuring the Startup class to inject our application specific configuration (so we can distribute this class to other applications which each have their own API key, and we’re also injecting IgdbClient this into the controller.

Message Handlers

The last feature we’re going to discuss is message handlers. Handlers can be attached to clients to monitor messages as they go in, or messages as they go out. You could perform logging for messages or duration, request validation, and more. Handlers can be chained as middleware as well. We’re going to keep it simple for our demo, and simply verify that the user-key which is required for the API is specified for the request before it goes out for our application. Let’s add the following class to our app:

Let’s also modify our Startup class, specifically the ConfigureServices method so that the following appears after we registered our IgdbClient.

Now, if we try to call the /game/id or /game/popular endpoints without having specified our user-key, this will result in a 400 Bad Request error before it is even attempted to be sent to the Igdb API. This potentially saves us API usage limits and cost as well as improves our performance by failing before the attempt is made.


Adding AppSettings.json Configuration to a .NET Core Console Application

This post will walk you through the steps necessary to add a strongly typed appsettings.json configuration file to your console application. I’ll dispense with the formalities of writing a detailed introduction on why you would be interested in doing this and jump right into the steps involved.

Note: This post assumes .NET Core 2.1, but I believe any 2.x version will work.

1. Add the following NuGet packages to your console application:

2. Right-click your console application, and select “Unload project“. Once the project has been unloaded, right click the project and select “Edit <your_console_project_name>.csproj“.

3. Add the following just below the <TargetFramework> element:
(note: you should replace this guid with your own)

4. Add the following to a <ItemGroup> with other CliToolReference elements, or add your own:

5. Right-click your console application and select the “Reload project” option.

6. Open the developer command prompt and navigate to the directory with your console application, then run:

Note: This will create a secrets.json file located at: %APPDATA%\Microsoft\UserSecrets\<SecretId_From_Step_3>\secrets.json
Edit the newly created file and change the contents to:

7. Create a new JSON configuration file for your console application and name it appsettings.json. Set the following to the contents of the file to the JSON below. Important: Be sure to right-click this file and select properties. Change the “Copy to Output Directory” option to “Copy if newer”.

8. Create a class named MySettingsConfig:

9. Add the following code to your Main routine inside Program.cs

If your console shows your settings correctly, congratulations! If you’re missing the AccountName and ConnectionString settings, be sure you followed the step to “Copy to Output Directory” listed in step 7.


Setting Up A React & Web API Development Environment in Visual Studio 2017

Front-end frameworks like React, Angular, and Vue are making big waves in software development. Microsoft makes great tooling for working with JS frameworks like those in the form of Visual Studio Code. There is also a large trove of information and tutorials getting setup inside the VS Code environment. One specific resource I really appreciated was Cory House’s Pluralsight course on setting up a JS development environment.

Unfortunately, at least in my experience, there isn’t much available out there on how to setup a React dev environment using Visual Studio 2017, for those of us who wish to use only a single editor to maintain our .NET applications. My hope is, that the rest of this guide will serve as a useful resource for anyone else who is facing this same impediment to getting started and will end up saving them time.

Some pre-requisites before we get started:

Disabling Package Restore in Visual Studio

Visual Studio tries to take care of a number of things for you when dealing with npm pacakges. Some people prefer this, other’s don’t. I fall into the latter camp. It took me a bit of headache to figure this out, but by default, when you save a packages.config file, Visual Studio attempts to run ‘npm update’ for you automatically when you save the file or open the solution. So, if you are trying to run the command yourself after updating packages.config, then you are going to run into file locks with the /node_modules/ folder.

Thankfully Visual Studio offers you a way to disable the automatic updates when saving packages.config. Navigate to Tools > Options, then to Projects and Solutions > Web Package Management > Package Restore and set the following settings for NPM (below). What this does is prevents npm from being executed every time you open a project, or run a command line ‘npm update’/’npm install’. You can leave these on if you wish, but for me I found the experience better by being able to execute the npm command line syntax myself.

Setting Up The Application

Instead of walking you through line by line of each step you need to follow, please download the sample application from Github. There are a few important areas that I think are worth mentioning.

  • If you changed the package restore settings above, you’ll want to run “npm install” inside each project after cloning.
  • The ‘Empty’ solution assumes the webpack-dev-server for hosting, so when you run ‘npm start’, webpack will host a simple webserver at the port listed in webpack.config.js.
  • The ‘MVC’ solution assumes it will be hosted by IIS Express or the built in webserver. The ‘npm start’ command on this application will actively watch for JS file changes and rebundle them for you. No need to recompile to see your changes unless you something managed by .net.
  • This approach does leverage Babel as the transpiler. If you would like to use TypeScript, you could do that as well.
  • The webpack configuration assumes that the application start/root is /ClientApp/index.js.
  • The webpack configuration also assumes that everything is written to the /wwwroot/ folder as is convention with Core projects in Visual Studio 2017.

I hope you find this post useful. It took me a bit of searching to figure some of this out since most tutorials focus on Visual Studio Code. Feel free to reach me on twitter if you have questions about any of this. Happy programming.


Generate Test Data With Faker.js

Here is a common scenario for you. You’re building an application… any application. It could be your side project, a sales tool, an ecommerce site, a REST api, a video game, a reporting dashboard. Anything. You’re building your app, and you reach a point that you’d like to try it out, to see how it would look to a user. How do you simulate a production scenario with no data to test with? If you’re lucky, you have data from an existing customer you can use, or there is a sample dataset available online. If you’re unlucky, you’re left generating dummy data using garbage inputs (random strings, random numbers, etc) – data that passes the regex, but doesn’t provide a good simulation.

Do you wish there was a library that allowed you to programatically generate test data? Enter Faker.js. Faker.js allows you to generate a variety of data types in an intelligent and structured way. You can generate: Addresses, Products (Ecommerce), Companies, Dates, Images, URLs, and random objects as well (numbers, strings, words, uuid, etc). Click here to see a demo.

If you’d like to consume data from faker in another programming language, such as c#, you could use their hosted microservice at (i.e. A second option would be Bogus, a port of Faker for .net. There are ports available for other languages as well and the API surface is roughly the same in each instance.

I setup a very simple Github repo that demonstrates how to use Faker in a variety of scenarios to help you accomplish your goals. Hopefully you find this utility as useful as I do for prototyping new functionality before it goes into production.


My Favorite Visual Studio Shortcuts and Tips

Hey everyone – I’ve been maintaining a list of little shortcuts to save me time and ease my development efforts and figured they would be worth sharing here. If you have any you would like to share here, please email me and I’ll include them as well.

Visual Studio Keyboard Shortcuts

  • Ctrl+. opens up the ‘Smart Tag’. Use it when you see the red squiggle line to add a missing reference, or implement an interface.
  • Ctrl+K,C will comment either the current line, or any block of code you have highlighted.
  • Ctrl+K,U will uncomment either the current line, or any block of code you have highlighted.
  • Ctrl+, opens smart search to quickly find and jump to a class or method name.
  • Ctrl+I allows you to do an inline search (basically search quickly without dialog box)
  • Shift+Alt+Enter for enter and leave full screen mode.
  • Ctrl+- moves cursor to last known position (helpful to navigate back, Ctrl+Shift+- is forward)

Visual Studio Features

  • Snippets, like ‘prop‘ will inject a property into your code, or ‘foreach‘
  • Custom snippets, click here for a starter list and how-to.
  • Right-click file in Solution Explorer, select Source Control > Annotate. This shows all history of the file and who checked in what line of code.
  • Use ‘Package Manager Console’ to install Nuget packages (Alt+T,N,O). (ex: PM> Install-Package Newtonsoft.Json)
  • Tell debugger to ‘break’ when an exception is thrown even if no breakpoint exists (Ctrl+Alt+E, then check Thrown on CLR).
  • From Visual Studio Command prompt, use this command to get a list of all checked out files (and to who): tf status /collection:http://my-tfs-server:8080/tfs/MyCollection $/pathto/mytfsproject /user:* /recursive

Techniques For Improving Website Performance

Annotated below is a presentation from Nik Molnar, co-founder of the open source debugging and diagnostics tool Glimpse, who demonstrates several different strategies for improving the performance of your web application. This is easily one of the most useful conference presentations I have ever seen and I wanted to share it with everyone. If were curious about how to do any of the following tasks, this presentation will cover those for you. Next to each point is a bookmark for you to jump to that portion of the presentation.

  • Using browser tools to analyze usable content and latency for each request [13:00]
  • How to use HAR files for analyzing performance metrics [14:30]
  • Using the ‘Audits’ tab in Chrome to make recommendations [15:40]
  • Adding Google PageSpeed to the browser tools and how to use it [16:45]
  • Specifying in the web.config how to use compression for static and dynamic files. [17:50]
  • How to enable client side caching with the expires header [19:00]
  • How to use bundling in ASP.NET to bundle and minify CSS and JS files. [19:35]
  • How to use Web Essentials Visual Studio plugin to easily do image sprites [20:40]
  • Using to optimize PNG images with lossy compression [22:00]
  • Using Web Essentials to embed small images as base64 encoded text in CSS [24:22]
  • Using async script attribute and img lazyload attribute to lazy load resources [26:19]
  • Pre-caching client data using dns-prefetch, prefetch, and prerender HTML tags [28:30]
  • Using the RedGate CPU profiler to identify bottleneck code (note: Visual Studio has a simpler built in feature) [35:00]
  • High level thoughts on how to improve server side performance [35:55]
  • Using browser tools like Octane to profile Javascript CPU performance [38:30]
  • High level thoughts on how to improve javascript performance [42:25]
  • Understanding frame rates and the concept of jank [44:05]

Link to the video in it’s entirety
Link to baseball demo site used in presentation


ThatConference 2014

For the past three years, a group of very smart and very generous people, have hosted a wonderful summer camp themed conference in Wisconsin titled ‘That Conference’.   It’s hosted at a giant indoor/outdoor waterpark and convention center, Kalahari Resorts.  The number and quality of the sessions is impressive, and may shock you a bit when you consider the entire ticket cost is currently under $400.

Most of the presentations I attended were put on by Microsoft MVPs, people who are recognized by Microsoft as leaders in the community and have demonstrated a strong ability to teach and inform others about the technology stack.

Each day starts off with a keynote.  Day 1 was Elizabeth Naramore,  who artfully spoke about how destructive FUD (fear, uncertainty, and doubt) can be.  Day 2 was Tim Huckaby, a long time Microsoft collaborator  turned entrepreneur and founder of Interknowlogy, who spoke on the importance of design.  Day 3 was Mike Mcgee, who is the co-founder of Starter League, a rapid learning school hosted in Chicago.  Mike gave us his inspiring story of how he took risks, turned down offers, and maintained a focus on his business until it reached success.

Some of the favorite talks I participated in were:

SDK for your API by Wade Wegner

Understanding OWIN by Keith Dahlby (author of Posh Git)

RavenDB for the .NET Developer by Judah Himango

ORMs – You’re doing it wrong by Jimmy Bogard (founder of Automapper)

Building a Flexible Client API Library by Darrel Miller

Full Stack Web Performance by Nik Molnar (co-founder of Glimpse)

In addition to all the wonderful technical presentations, there were great opportunities to meet other like minded individuals.  There was a meet & greet for early check-in attendees, a happy hour with great food the first night, a full pig roast the second, and plenty of chances to interact and reflect on the final day.

Generous sponsors brought technology for everyone to experiment with.  Omni Resources brought an Oculus DK2 which I thought was amazing, Skyline Technologies made a flappy bird clone that utilized the Kinect to wave your arms to move, another company brought Google Glasses for people to try.   All the sponsors were developer focused, knowledgeable, and polite to the “campers”.

ThatConference will be 8/10/15 to 8/12/15 next year and I already have it noted on my calendar.


Create a push notification system with SignalR and Toastr

Do you have events in your application that you would like to trigger a notification to other users? How about if a user places an order on a website and you want the website administrator to see a notification, or a sale on Apple products is initiated and you want to notify customers?

Note: If you wish to download the code to follow along instead of going step by step, you may download it on Github here.

SignalR is a library for .NET that enables real-time communication. It does this via web-sockets, which is typically available in modern browsers, but also degrades gradually to other methods that are supported by the older browsers. You just need to worry about the SignalR framework not the underlying architecture. Toastr is javascript framework for non-blocking notifications. With just a few lines of code you can get a nice popup system in place.

Let’s walk through the steps, it’s not too difficult.

1. Create a new MVC project in your favorite language, I’ll be using C#. I disable user authentication and name it ‘SignalrToastr’ but you can name it whatever you would like.

2. Open ‘package manager console’ for your application, and install the SignalR package.

3. Create a class file named ‘Startup.cs’ and place it in the root of your application. Give the following contents to your new file. This file is an Owin startup file, which is outside the scope of this discussion, but is worth noting as Owin will become a larger part of ASP.NET vNext. It is a middleware framework that resides outside of IIS. Microsoft also uses Owin for the ‘Individual Accounts’ user manager, so if you left user authentication enabled in step #1, you can simply add the ‘MapSignalR’ line below to the Startup.cs class it created for you.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalrToastr.Startup))]
namespace SignalrToastr
    public class Startup
        public void Configuration(IAppBuilder app)
            // Any connection or hub wire up and configuration should go here

4. Create a folder called ‘Hubs’ and add a file named ‘ContactHub.cs’. Enter the following contents into the file.

using Microsoft.AspNet.SignalR;

namespace SignalrToastr.Hubs
    public class ContactHub : Hub
        public void ContactFormSubmitted(string name, string message)
            // Calls the 'notifyUsers' method on the client side.
            //  Note:  You can change 'All' to target only certain clients.
            //  Note:  Code after 'All' is dynamic, and you can specify whatever name you wish.

SignalR uses ‘Hub’ objects to communicate between the client and the server. We will go over more on what is actually happening here in a later step. For now, you should note that ‘ContactFormSubmitted’ is a method being called on the server, from the client. The client passes this server method two parameters, name and message. This server side method then notifies ‘All’ clients to execute a JS method named ‘notifyUsers’ which takes one parameter, name. Outside the scope of this tutorial is how you can narrow down which clients you want to send the message to.

5. Modify the ASP.NET templated view that comes installed ‘~/Views/Home/Contact.cshtml’ and replace it’s contents entirely with the following:

<form class="form-horizontal">

        <!-- Form Name -->

        <!-- Text input-->
        <div class="control-group">
            <label class="control-label" for="txtName">Name</label>
            <div class="controls">
                <input id="txtName" name="txtName" type="text" class="input-medium">


        <!-- Textarea -->
        <div class="control-group">
            <label class="control-label" for="txtComments">Comments</label>
            <div class="controls">
                <textarea id="txtComments" name="txtComments"></textarea>

        <!-- Button -->
        <div class="control-group">
            <label class="control-label" for="btnSubmit"></label>
            <div class="controls">
                <button id="btnSubmit" name="btnSubmit" class="btn btn-primary">Submit</button>


@section scripts
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    
    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    return false;  // prevent 'form' from submitting.

This creates a simple two field bootstrap form, and also adds our required JS includes to make SignalR work (jquery.signalR-*, and ~/signalr/hubs). It also creates a placeholder for our client callback notifyUsers, and also adds an event handler for our contactFormSubmitted method to push to the server. If you build your solution at this point and open your browser to your projects location for /signalr/hubs/ (i.e. http://localhost:62279/signalr/hubs/) you’ll see some generated JS markup that SignalR created based on your hub. Note how it lower cases your hub name, and methods. This is what the SignalR framework is creating for you automatically based on your Hub classes.

        proxies.contactHub = this.createHubProxy('contactHub'); 
        proxies.contactHub.client = { };
        proxies.contactHub.server = {
            contactFormSubmitted: function (name, message) {
                return proxies.contactHub.invoke.apply(proxies.contactHub, $.merge(["ContactFormSubmitted"], $.makeArray(arguments)));

6. Repeat step #2, but install the Toastr framework.

7. Add the toastr.css file to either the top of Contact.cshtml or to your Layout.cshtml file:

<link href="~/Content/toastr.css" rel="stylesheet" />

8. Modify your scripts section of Contact.cshtml to look as follows. Note how we have added a reference to taostr.js and also placed the call inside our notifyUsers callback method.

 <script src="~/Scripts/toastr.js"></script>
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    

    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {
      'New contact form submitted by ' + name);

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    return false;  // prevent 'form' from submitting.

9. You are done at this point, so let’s try it out. Open two different browsers side-by-side, I’ll be using Chrome and Firefox. This is done to show you how the server is making a callback to ‘All’ clients as shown in step #4. You can narrow this down in the future if you want, to only administrative users for example. If all goes well, you should be able to fill the form out in one browser, and see the popup in both.