Using SignalR

There are already some good walkthroughs about this on the SignalR github site (https://github.com/SignalR/SignalR) so as a warm-up I suggest you take a look at those. Both the low-level API and high-level API are interesting. The main difference is the amount of control you have over the connection and message processing. In the low-level API you have full control over this including being able to override what happens when a client connects, processing of messages, and even disconnection of the client. With the high-level API you for-go this for a much simpler implementation, in this case simpler does not mean less powerful or useful. I think in most cases the high-level API (hubs) will be the right approach and will have plenty of flexibility for what we are trying to accomplish.

In this walk-through I am going to setup a simple application that allows a user action to notify all connected admins. To keep it short and simple this will be done using 2 different pages. Default.aspx will be the client, and Admin.aspx will be the admin page.

To start off we need to create a new web application project (we will use webforms). Once we have a clean project we will use NuGet to install the SignalR package (this actually installs 2 packages, the SignalR.Server package and the SignalR.JS package). Along with the NuGet package we will be using two difference aspx pages; default and admin.

image

Your project should look something like this.

Our next step is to create our Hub. We will do this in a Services folder within the web project. In this folder we are going to add a new class named “AdminHub”. The contents of this class mirror what you have probably seen already.

The idea here is that by inheriting from the Hub class we are creating an endpoint for a client to subscribe to. This class and the methods within it are callable by JavaScript as will see shortly as well as it calling JavaScript methods on all subscribed clients. The method “SendMessage” could be named anything as it just gets wrapped in a JavaScript factory to allow the clients to call it.

Moving on to the JavaScript we will add the following to our Admin.aspx page:

Looking at the JavaScript the first thing we need is the jQuery reference. In this case it is added in the master page but it could be done here. Next is the reference to SignalR.js. This is used by the prototyped JavaScript and does all the heavy lifting. The next script we add is actually a dynamic proxy generator, because we are using webforms and to be sure we have the right path I am using ResolveClientUrl.

Within our JavaScript we put some code in the jQuery start-up block. The first line created a new proxy to the hub we created previously in c#. It is important to note that naming is very important here as this is all convention based. In this case to utilize our hub “AdminHub” we need a JavaScript proxy named “$.connection.adminHub”. The first letter being lowercase is important. Our next step is to create the callback that our hub will fire. Again this is convention based so the names need to match.

The next two methods we have are wiring up of buttons to fire some c# code. These are the methods we defined on the hub and again this is convention based. Camel Case in c# and lower Camel Case in JS. The last line just initiates the clients persistent connection to the hub.

So now lets say we want to send a message to all the clients of this hub but from another page and without connecting to the hub. Well to do that we just get a reference to the hub we want to message and call the JavaScript method we wish to invoke.

In this case we have a standard asp.net button whose click event is wired up in the code behind. In the click event we get a reference to the clients subscribed to the AdminHub and then invoke the addMessage JavaScript method. That is all it takes to invoke JavaScript for connected clients from your code behind.

All in all, this library is extremely useful in a wide variety of cases and it so simple to integrate with that there is really no reason to not start using it. It is still being actively worked on and is open-source. A working demo is also available at http://www.infinitelooping.com/demos/. Demo source code is available upon request.

Don’t forget to check-out SignalR on github (https://github.com/SignalR/SignalR)

A Simple Validated Collection

In an attempt to validate items as they were added to a collection I decided to use the Collection<T> object and override the “setitem” and “insertitem” method as my injection point for validation. As I was doing this I saw an opportunity to create a generic class that utilized the validation attributes provided in .net as well as the built in validation engine.

The idea here is to ensure that all items put into the collection are valid. So to start we create a new class that inherits from Collection<T>.

This will be our injection point, from here what we would want to do is validate “item”. To do that I decided to go with the validation mechanism provided by .net 3.5 and the DataAnnotations class (System.ComponentModel.DataAnnotations). This allows us to describe validation requirements as attributes on our Model/Business Objects.

An example object:

The validators above (specifically Required, StringLength, and RegularExpress) are describing the requirements of the attributed property. So Name is required and must be 30 characters or less and SSN is required and must match the given RegEx.

So now we need to validate it. Back in our insertitem method we can do the following:

Validator.ValidateObject will walk through the annotations and validate them against the object. The first parameter is the object to validate, item in this case. The second parameter is the validationcontext, this tells the validator which items validation context to use. You could potentially use/reuse the validation on a different object but to keep things simple we just pass the item being validated again. The two null parameters in the validation context are for implementing a service provider, this is optional. The last parameter is telling the ValidateObject method to evaluate all the properties of the object.

This method works but a failure in the validation throws a ValidationException. This may or may not work for you depending on your specific requirements. I prefer to take a different approach.

This method is not so brutish as it just populated a list with the validation results and only inserts the item into the collection if the validation passed.

The next step is making the results list available to the consumer. There are a number of ways to do this but for the sake of brevity we will show just one example. What we will do is create a delegate that is called upon validation failure.

public Action<T, List<ValidationResult>> OnValidationFailed;

This is a generic delegate that returns T and a list of validation results. It will be null unless the implementer wires it up. Now InsertItem looks like this:

There is on remaining problem however, if the delegate is not being handled by the implementer the validation results will be swallowed. This is probably bad so we need to throw an exception in this case. The easiest way would be to just run the validation again without using try however this could potentially be expensive. Instead we will unwrap the validation results into a string and throw a new exception.

The above is an extension method on the List<ValidationResults> object and will return a string with all validation results contained.

Last we add the else fall-through case to the InsertItem method:

 

Now this is all useful but the code for the SetItem method is going to look exactly the same except instead of doing base.InsertItem it will be base.SetItem. I looked at this and said to myself I can do better. So I created a new method to handle the validation part and we pass in the success method as a delegate. This allows us to be more DRY and more flexible.

This is very much the same as the code we had in the InsertItem method except with the addition of the successMethod parameters who’s signature matches that of the base.InsertItem and base.SetItem methods. Those methods now look like this:

You may also note that I decided to set TryValidateItem as protected and virtual. This allows implementers to override with their own behavior if desired.

While this may not be the most complicated or elegant bit of code ever I found it useful and hope someone else will too. The full class can be downloaded here(http://bit.ly/QVMhW7).

More NuGet Goodness

Previously I wrote about installing and using NuGet in Visual Studio. While that is great and makes lots of tasks easier, what if we wanted to write our own packages, or even create our own host for packages? Well it is a lot easier that it sounds (even if it sounds easy).

Part 1) Creating your own NuGet Packages

The Following is paraphrased from here. I have focused on the quick creation of a package from a project file as that is the quickest way to create a package. Please be sure to check NuGet for more in-depth coverage regarding this.

The first thing you will need is the NuGet.exe executable file (http://nuget.codeplex.com/releases/view/58939).
Once downloaded you will probably want to update your paths so you can reference it anywhere.

The next step is to make sure your nuget exe is up-to-date (should be if you just downloaded it). To do that all you need to do is run the following from the command line.

NuGet update

This will automatically check your version of the executable against the currently available version and will update it for you if it is out of date.

Next we start with the actual creation of a package. I will focus on creating a package from a VS 2010 class library project but you can actually do a lot more, such as create a package from files, include a powershell script to run upon install (this will do stuff like add references, create folders, etc…), and apply transforms (add relevant elements to the web.config for example).

To create a package we first need to open a command window within the location of our project. The same folder as the “.csproj” is in this case. Once there we will run the following command:

NuGet spec

This will create a file with the extension .nuspec for us. This file is used to describe our package and is just a normal xml file. It also contains some fields that are automatically replaced when the package is created. These fields are denoted by $’s on each end of a keyword.

I have removed the elements that i don’t personally use but feel free to use the icon and legal elements as you see fit. I have also added a summary tag. I don’t know why this is omitted by default but it is what is shown by Visual Studio as the tagline under the packages name. I just default it to the same as the description.

Summary Area Highlighted

Ok but where do those values come from you might be asking. Well there are taken from the project’s assembly info. This is all defined in your projects settings and assemblyInfo.cs file.

You may have noticed the “*” added to the version. This will tell VS to automatically increment the Revision and Build numberings while still allowing you to control the Major and Minor numbers.

Alright so we have our nuspec file and we have a general understanding for what it means, next we will actually create the package. First howerver, if you made any changes to your assemblyinfo or code you will need to rebuild your library within VS. There is a known bug that while NuGet does invoke MSBuild on your project, it does not grab the built components so you will need to make sure it is built before creating your package. To create the package we again drop into the command line and run the following:

NuGet pack .csproj

It will automatically pickup the nuspec file during this process. If all goes well you should see something like this:

So now if you take a look at your folder for the project file you will see a file with the extension .nupkg. Congratulations you have created a package.

Step 2) What do i do with this package file you made me make?

So now we want to host this package some where. While you can just use your local file system for hosting packages(see here) we are going to create a web host.

The majority of this information comes from here.

The first step is to create an empty asp.net web application.

Next, using the nuget “Package Manager Console” type the following command:

Install-Package NuGet.Server

This will install everything you need to start hosting your own packages. A folder will be added to your project called packages. Any packages you want to host go in there. Once there they are automatically added to the feed.

If you run the application you will be greeted with a welcome message from NuGet containing a link to the RSS feed version of the host. You may notice that the URL given is http://localhost:xxxx/nuget/Packages. This is a little misleading at first glance because what VS is looking for when adding a new feed is the XML version of the packages feed. This is accessed at http://localhost:xxxx/nuget.

So now we need to put the package we created earlier into the packages folder and refresh our nuget host web page.

Once our package is up and available all we need to do is add the url to VS (this is ready to be deployed as is if you want your packages to be always available you can host them on a local IIS instance or any IIS host).

Goto Tools->Library Package Manager->Package Manager Settings.

Once the settings screen is open type in a name and the url to your nuget host and click “Add” and then OK and you are done. Congratulations you have created your own NuGet Repository with your first package. This will make sharing and reusing code pieces much easier and much more painless as more and more packages are added to your local/intranet/public repositories.

Some gotchas:

  • When deploying NuGet if you are running in a virtual directory you will need to update your web.config to allow multiple bindings to the nuget URL
  • Currently there is no support for authenticated feeds, this is due to a limitation in the VS plug-in but is currently being worked on and the NuGet team is getting close to adding this support

NuGet First Look

What is NuGet?

NuGet is a visual studio extension that gives you access to a wide variety of plug-ins for your project. For example, if you have a web application but need to log all unhandled exceptions you could roll your own by creating a logging component and log all unhandled exceptions in the Application_Error event in the global.asax, or you could just install elmah (error logging modules and handlers). If you are not familiar with elmah i suggest you check it out. Installing elmah, or any other plug-in code, using NuGet is extremely easy and takes all of the guess work out of using these 3rd party libraries.

OK cool, how do i get started?

The first thing you need to do is add NuGet to visual studio, this can be done via the extension manager in 2010.

In the extension manager the NuGet extension will be one of the top 3 downloads by default.

Click on Download, accept the Terms of Use and install. Once installed you will need to restart VS (you will be prompted). Once visual studio comes back up NuGet will have been installed. You won’t notice any difference immediately however the package manager console should be loaded by default. This is a powershell console with some NuGet extensions built-in. First lets create a new web site.

This will create a default MVC application. MVC is the Model-View-Controller pattern as implemented by Microsoft. We will go in-depth into MVC at a later date. For now, just create Internet application version of it and we will start using NuGet.

Alright so we have an MVC application, but when we browse to /bad/url we get this:

Now thats pretty obvious, but if it were to happen to an end user, we wouldn’t know about it without some sort of logging involved. So lets add some logging using NuGet. First lets open the package manager console:

In the Package Manager Console we need to type in the command to install elmah:

Install-Package elmah

** Note: Because this is a powershell back-end it completely supports all powershell commands (ls, dir, robocopy, ps, etc…) as well as tab-complete which is working as expected with NuGet **

This installs automatically the elmah component and adds the required web.config entries for in-proc storing of exceptions. To verify its working run the project and navigate to a url that doesnt exist on the site (/bad/url), you still get the YSOD but now it is being logged. To see the log navigate to /elmah.axd.

For a quick and dirty persistent log we can add another module elmah.sqlservercompact. Lets install elmah.sqlservercompact through the GUI. On the references folder of your project is a new context menu “Add Library Reference…”. This will bring up the NuGet package manager GUI.

This adds the SQL Server Compact Edition libraries to your project as well as the elmah library that integrates with it. There is no further setup needed on our end as the web.config will already have a reference to the database (which is created on the fly) and all relevant libraries added are set as copy local. As an aside, SQL Server CE 4.0 is free and has been built to work in medium trust hosting environments supporting up to 255 concurrent connections. It is a great free option for low volume web sites and stand alone apps. Because it is built on SQL Server the upgrade path to SQL Express or the full version of SQL is fairly seamless.

There are a plethora of useful plug-ins in the NuGet repository already including:
* Elmah
* EntityFramework 4 w/ Code first
* Ninject
* jQuery (this will keep jQuery local to your project and notify you when updates are available)
* MVCScaffolding (this is an awesome scaffolding plug-in that makes working with MVC even better)
There are more added everyday so be sure to use NuGet and enjoy how much easier your life just got.

Entity Framework 4.1 and Code First First Look

So i spent this weekend taking a look at the latest Entity Framework release and the code first implementation. There are 3 ways to implement the Entity Framework with 4.1. There is database first where your entity model is created from your existing database. Next is model first, where you design the model using the entity model designer (or you can write the xml directly). Lastly is code first which will be the focus of this post.  Code first allows you to use POCOs (plain old CLR objects) to model your entities and ultimately your database.

Getting Started:
First you will need to install NuGet. NuGet is a visual studio extension for VS 2010 that allows for easy installation and consumption of 3rd party libraries such as nHibernate, elmah, and NuGet. This can be installed via the extension manager built into VS 2010 (Tools -> Extenstion Manager…).

Next you will need to create a new project in visual studio.  We will create a simple console application for illustration purposes (File -> New -> Project…). Make sure to select .Net 4.0 as the target framework.  Once done you should see a something like this:

The next step is to add the Entity Framework 4.1 to your project. There are two ways to do this once NuGet is installed.

  1. Command line: There is a Package Manager Console now listed under Tools -> Library Package Manager.
    • This is actually a powershell instance so you have all of the default powershell commands
      • Try ps to see running processes
    • Within this shell you have some NuGet specific commands but the one we are interested in now is Install-Package
      • Install-Package EntityFramework
        • You dont have to type it all out as powershell supports tab-complete
  2. IDE: This extension to visual studio includes an added context menu on the references folder in a project. The context item is “Add Library Package Reference…”.
    • This can also be found under Tools -> Library Package Manager -> Add Library Package Reference

Ok so now we have an empty console application, reference to EF 4.1, and some odd visual studio extension (NuGet is actually really handy and a huge time saver, there will be more about this in another blog post). Next we need to create some sort of code representation of an object or collection of objects. Lets add a new class and call it Car. In this class we will have a few properties (remember this is a POCO class so it will be very simple).

Well that was simple but lets go ahead and create another class in the same file and add an engine.

Now lets add some validation to these by using data annotations. Data annotations are part of the component model that allow you to clearly define and constrain the data the propery accepts. They are under the System.ComponentModel.DataAnnotations namespace.

The annotation will be used automatically when the database is created to create columns of the correct size and nullability.

Ok so there are a couple things going on here. First you will notice the Id property, these will be interpereted by the Code First compiler as primary keys for the table. Each class will end up with its own table. Next you will notice the reference to Engine in the car class is labeled as virtual. This is a special modifier that tells the Code First compiler that this is a navigation property and allows for lazy loading.

So far we haven’t done anything outside of ordinary. We have two simple POCO classes, an empty console app, a reference to EF 4.1 which we still haven’t used, and that package manager. So now lets create a database context. We will go ahead and use the same class file just to keep things simple.

public class MyAppContext: DbContext {

}

We are inheriting from DbContext (in System.Data.Entity). This will become our link to the database. Next we create two automatic properties of type DbSet.

public class MyAppContext: DbContext { 
	public DbSet<Car> Cars { get; set; } 
	public DbSet<Engine> Engines { get; set; }
}

A DbSet is a special class that defines a database object using the type passed in. Now we need to create an instance of the context in our Main method (program.cs).

Here i am creating 3 new cars, adding them to my database context and saving them. Then i pull them back out and read the data. But wait! We never created a connection string or specified a database, what is going on? Well that is the magic of code first. It will automatically create a new database for you on SQLExpress if installed, if not it will use SQL CE.

You can check this if you have SQL Express installed by connecting to it with SSMS and seeing a new database named ConsoleApplication1.MyAppContext (or whatever that namespace/class is that you put the context in). You will also see that Cars ID is a primary key, EngineId is a foreign key(this is automatic if you follow the convention <class>Id), Make and Model are nvarchar(30) and Make is Not Nullable. All of this is automatic through code first. Also you can actually change the DB name by creating a default constructor like this:

public MyAppContext():base("MyCars") {

}

This will create the database with the name MyCars. But if you want to point to an actual database you can do that too by putting the connection string in your app.config/web.config.

** Note: The connection string name must be the same as the name of your context class **

In closing, after a first look at code first I can see this being a timesaver when developing projects. The ability to let the development/code define the model and the store is a big plus for me and I am looking forward to trying this out more in the near future.

Useful links:
http://www.hanselman.com/blog/SimpleCodeFirstWithEntityFramework4MagicUnicornFeatureCTP4.aspx
http://channel9.msdn.com/Shows/HanselminutesOn9/Hanselminutes-on-9-Digging-into-Entity-Framework-4-Code-First-Magic-Unicorn-Edition
http://weblogs.asp.net/scottgu/archive/2010/12/08/announcing-entity-framework-code-first-ctp5-release.aspx

using jQuery AJAX to call web methods

I recently wanted to improve a page on the site I was working on and decided that AJAX would be the best way to accomplish that. My issue is an issue I am sure faces most developers using asp.net. To many postbacks. I had a dropdown that would need to fire a postback to show/hide other elements on the page. Problem is, you could change the dropdown value and tab into another field, start typing and then the page would refresh. So I wanted to remove the postbacks, but retain the functionality and keep it lightweight. Using JQuery to create an AJAX call and callback I was able to get the page to be more responsive and improve the User Experience, all while keeping the network traffic to a minimum.

How I did it:

Step 1) Create a static web method to accept some values and return a custom object (this can be anything that can be serialized).

In this example i have created an ItemSelectedResult class that is decorated with the [Serializable] attribute. It has a bool and a string as automatic properties.

Step 2) Create AJAX Call to created web method.
In this example we are using the JSON library which can be found here(http://www.json.org/js.html).
We specifically leave “jsondata” undefined if null is passed in as the “DataObj” as that is what the web method will expect if there are no parameters.

Step 3) Create a call to the java script method we just
created and pass in the javascript object as well as any call
backs.

You can call this method during any event in javascript and
create objects like this:

var obj = { val1: 1, val2: false};
AJAXCall("Item_Selected", obj, AjaxCallback, AjaxErrorCallback);

Replace val1 and val2 with the names of your parameters on the web method. These are case-sensitive. Also replace “Item_Selected” with the name of your method. This is also case-sensitive.

Step 4) Create your callback method to read the results of your ajax post and manipulate the DOM as desired.

** NOTE: Using .net 4 allows us to set the ClientIDMode of a server control so we can determine the client id without using a server tag. **

<asp:DropDownList ID="ddlCities" runat="server" SkinID="DropDownList150" AutoPostBack="false" ClientIDMode="Static" />

Using ClientIDMode=”Static” forces the html source to use the same ID as the assigned Server ID

HTML Source:

<select name="ctl00$ContentPlaceHolder$ddlJobCode" id="ddlCities" style="width: 156px; height: 18px;" >

Overall I found this to be fast and pretty easy to accomplish and thought I would share if anyone was thinking of adding AJAX to a page.