I’m a big fan of Twitter’s Bootstrap html/css/javascript framework, and use it on practically all new web projects that I work on. It makes it super easy to quickly knock up a slick-looking web application, and since it’s built on less it’s really easy to customize the look of each site.

That said, the markup is complex enough that when developing sites I typically have the docs open in another tab at all times as a reference point, which lead me to start building little HtmlHelper extensions to create the more complicated elements, such as navbars, forms, etc. These extensions have been bounced around from project to project, and have ended up a little scrappy as they’ve been built as-and-when with no real planning, but they have been hugely useful, so I decided it was finally time to look at rewriting them. Check out the Bootstrap Extensions repo over on GitHub, or have a browse through the documentation (design somewhat inspired by the original bootstrap docs!).

The library is by no means complete, as of writing this I’ve only implemented lists, buttons, button groups + toolbars, navbars and progress bars; but it’s a start, and I intend to cover the majority of the more involved elements. I’ll also look at fine tuning the API to make development as pleasurable as possible.

Update: This project has been included on The Big Badass List of Twitter Bootstrap Resources. Check it out, there’s some brilliant useful stuff on there
<div class='box'>
    <h2 style='-webkit-user-select: none;'>Title</h2>
    <div class='boxSlide'>
        <div class='boxBg'>
            <div class='boxContent'>
                content...
            </div>
        </div>
        <div class='boxFooter'><img src='img/ws_box_footer.png'></div>
    </div>
</div>

Apologies for the above code. I realise it’s not very pleasant to look at, but unfortunately I was working on a website not too long ago which was based off of an online template, and this was the structure I’d been asked to use to add some fancy, styled boxes to a whole bunch of pages so as not to break the existing site’s css.

Now that’s quite a lot of markup for a simple section – please understand I’d be far happier using cleaner and more semantic markup, such as section, article, or even a single div if needsbe – but unfortunately that wasn’t an option. However, even if that was the code that I had to use, it sure as hell wasn’t the code I was going to write. Not over and over and over…

I first wrote a HtmlHelper extension method which would allow me to use the syntax @Html.Section(“header”, “content…”), which was definitely a marked improvement on all that code, and lead to much more readable source.

public static MvcHtmlString Section(this HtmlHelper html, string header, string content) {
   return MvcHtmlString.Create(
              "<div class='box'>" +
                  "<h2 style='-webkit-user-select: none;'>" + title + "</h2>" +
                  "<div class='boxSlide'>" +
                      "<div class='boxBg'>" +
                          "<div class='boxContent'>" +
                              content +
                          "</div>" +
                      "</div>" +
                      "<div class='boxFooter'><img src='img/ws_box_footer.png'></div>" +
                  "</div>" +
              "</div>";
}

Job done. Well, kind of. This worked well for just text-only sections. A section containing multiple paragraphs, images, or other html elements was possible, but looked a mess and was harder to read that the original syntax! It completely ruled out the option of using more complicated contents in a section – ie. if I wanted a section to contain a form. Furthermore, these boxes were nestable – so one box could potentially contain multiple. Since they took an string as content and returned an MvcHtmlString, then in addition to these problems I would have had to keep adding .ToString() to the end of each nested Html.Section().

@using (Html.BeginForm()) { ... }

How many times have we all used the above code? And what does it do? Well that’s easy, it’s an HtmlHelper for creating forms. The interesting thing with BeginForm, however, is that unlike most other HtmlHelpers, this allows for start and end tags, but with any other content nested within the curly braces (or if you prefer, open/close mustaches).

Oh what a coincidence, that sounds almost exactly like what I need to do!

So how does it work? Well fortunately, the solution is brilliantly easy. When you call BeginForm, it first outputs the opening

tag, not by returning an MvcHtmlString, but by writing directly to the view context using HtmlHelper’s htmlHelper.ViewContext.Writer.Write(string). It then returns a class implementing IDisposable (in this instance, an MvcForm), which is passed the view context when instantiated. All this class does is to write out to the view context when it is being disposed of – which as we all know is at the close of the braces.

Therefore, the code needed to allow me the freedom to write my sections as

@using (Html.Section("title here")) {
    ... any content I want! ...
}

is as follows:

public static HtmlSection Section(this HtmlHelper html, string title)
{
    html.ViewContext.Writer.Write(
              "<div class='box'>" +
                  "<h2 style='-webkit-user-select: none;'>" + title + "</h2>" +
                  "<div class='boxSlide'>" +
                      "<div class='boxBg'>" +
                          "<div class='boxContent'>"
        );
    return new HtmlSection(html.ViewContext);
}


public class HtmlSection : IDisposable
{
    private readonly ViewContext _viewContext;

    public HtmlSection(ViewContext viewContext)
    {
        _viewContext = viewContext;
    }

    public void Dispose()
    {
        _viewContext.Writer.Write(
                          "</div>" +
                      "</div>" +
                      "<div class='boxFooter'><img src='img/ws_box_footer.png'></div>" +
                  "</div>" +
              "</div>"
        );
    }
}

Not long ago I blogged about auditing with NHibernate.Envers. I’m using it again in another project but I don’t want to audit all the fields on the entity; furthermore, Envers automatically tries to audit referenced tables, so tables that are not configured to be audited cause an error message: An audited relation from SomeAuditedEntity to a not audited entity NonAuditedEntity! Such mapping is possible, but has to be explicitly defined using [Audited(TargetAuditMode = RelationTargetAuditMode.NotAudited)]. Understandably I expected that adding this attribute to the properties that I didn’t want auditing would prevent this behaviour, but it didn’t. I then added it to the class that I didn’t want auditing, but the message still didn’t go away. A quick google revealed another similar attribute, NotAudited, but this didn’t work either.

Finally after hacking around with my code I stumbled across the solution; the properties to be excluded must be defined in the Envers configuration. Although I think I’d prefer to annotate the fields in the entity class itself, this is the solution that worked for me:

var enversConf = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration();
enversConf.SetRevisionEntity<REVINFO>(e => e.Id, e => e.RevisionDate, new AuditUsernameRevInfoListener());
enversConf.Audit<SomeAuditedEntity>()
          .Exclude(x => x.NonAuditedProperty1)
          .Exclude(x => x.NonAuditedProperty2)
          .ExcludeRelationData(x => x.NonAuditedCollection;
configuration.IntegrateWithEnvers(enversConf);

I recently needed to implement a facility on a web page to download a file that was defined by a reasonably number parameters, stored on the page as JSON. The first thing I tried was to ajax the request, but that failed as the file never downloaded – I retrieved the data, but it essentially just got ‘swallowed’.

Next I tried using JSON.stringify to populate a hidden field with the JSON value and then submit that. The action that I was posting to was defined with the parameters separately, rather than just string, and I wasn’t able to edit it: I had hoped that ASP.NET MVC 3 might have been able to decode the string but it couldn’t, so that approach failed too. (If I’d been able to amend the action then I could have obviously deserialized the string, but I wasn’t allowed [boo!]).

So in the end I wrote a quick method that would populate my form with hidden fields representing the properties of my JSON model, and that ended up working nicely. Really simple, and would obviously have to be tweaked to handle nested JSON, but it got the job done:

function downloadCurrentReport() {
    var newHiddenInputs = "", i;
    for (i = 0; i < model.length; i++) {
        var nameBase = "model[" + i + "].";
        for (var prop in model[i]) {
            newHiddenInputs +=
                    hiddenField(nameBase + prop, model[i][prop]);
        }
    }
    $("#downloadForm").html(newHiddenInputs);
    $("#downloadForm").submit();
}
    
function hiddenField(name, value) {
    return "<input type='hidden' name='" + name + "' value='" + value + "'/>";
}
UPDATE: With the release of SignalR 4.0, some of the information in the article may be out of date

I recently had to implement an ASP.NET MVC application using long polling to handle asynchronous communication not only from client from server (as you might traditionally do using ajax), but also server to client. I began looking into long polling solutions, and soon stumbled across SignalR, which describes itself as an async signaling library for ASP.NET to help build real-time, multi-user interactive web applications, which was pretty much exactly what I needed!

SignalR is a really brilliant solution. It’s one downfall, however, is the lack of documentation. Scott Hanselman wrote a nice post that gives a nice overview, with a code snippet that shows how easy it can be to use SignalR, but unfortunately there isn’t really much else (except for that one snippet, which seemed to appear everywhere!). Looking through the samples is also helpful, but some things I had to puzzle out on my own, and so I wanted to share some of what I learned. I’m not going to bother giving ‘real world’ type examples, simply show the different types of client/server communication SignalR is capable of, the building blocks. Once you know how to send data/call functions client to server, and vice versa, it really isn’t much of a leap to work out how to put it all together…

So there are two ways to use SignalR: you can access it at a low level by overriding it’s PersistentConnection class, which gives you a lot of control over it; or you can let SignalR do all of the heavy lifting for you, by using the high level ‘Hubs’.

SignalR Hubs

It’s so easy to set up a hub in your application. First, use Nuget to grab SignalR and it’s dependencies. In the root of your application, add a class, MyHub.cs that implements the SignalR class Hub. On your page, include jQuery and jquery.signalR, and then:

<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
       $(function() {           var myConnection = $.connection.myHub;           $.connection.hub.start();       });
// ]]></script>

Rather awesomely, this is all you need to do to establish a connection between the client and server, which you can see if you crack open firebug. You’ll also notice that /signalr/hubs doesn’t actually exist in your project, which Resharper won’t like! This is really neat, as the hubs javascript is autogenerated by SignalR. Whilst we might have a connection established, it currently does nothing. Time to add some functionality.

Calling Server-side Functions from the Client

Everything with SignalR is basic, but this is probably the most basic of all. All you need to do is create the method in MyHub.cs, and then in your javascript simply call:

myConnection.voidFunction();

That really is it! If you build the solution and go to the source of /signalr/hubs, you’ll notice that it has been updated to include the new method. To pass some data, simply add values as you would in any other function:

myConnection.voidFunctionWithParams(1, "a string");

The methods don’t have to be void either. Say you have a function Increment:

public int Increment(int input) {
    return input++;
}

You call it simply by:

connection.returnInt(0)
          .done(function (returnedVal) {
              // Handle returned val (in this case, returnedVal = 1)
          });

As well as simple data types, you can also pass json to the server, and SignalR will automatically handle the conversion to objects. For example, if we have define a class MyObject:

public class MyObject {
    public int objId { get; set; }
    public string objVal { get; set; }
}

We can send it to the server like this:

var jsonMyObject = {
    "objId" : 1,
    "objVal" : "some text"
};
connection.receiveObject(jsonMyObject);

The reverse of this is true also, so returned objects from the server will be converted to their json equivalent.

Note: Static Variables

The hub class that you create will be instantiated at every request, so if you declare variables then they will be lost unless you make them static. This is useful for data that you want to persist, but not store in the database, as can be seen in the SignalR chat hub sample, which uses static collections to maintain the list of rooms.

Invoking client-side functions from the Server

So far I’ve only covered requests from client to server, which really is not a lot more useful than Ajax, albeit with some extra niceties such as object casting. The real usefulness of SignalR, however, comes with being able to call javascript functions from the server. I hope you won’t be surprised to learn, this is really easy to do! SignalR maintains a list of client side connections into the hub, rather conveniently named Clients. Client side functions must be defined in the initialisation code, for instance:

$(function() {
    var myConnection = $.connection.myHub;
    myConnection.alertMessage = function(stringParam) {
        alert(stringParam);
    };
    $.connection.hub.start();
});

This code simply creates an alert box that echoes the data passed to it, and is called by using

Clients.alertMessage("test");

Again, you can pass not only simple data types in here but C# objects and SignalR will handle the conversion. Taking this idea a little further we can pass in a list of MyObjects and iterate through them like this:

myConnection.receiveComplex = function(complexList) {
    complexList.each(function(index, complexObject) {
        var id = complexObject.objId;
        var value = complexObject.objVal;
    });
};

Invoking Client-side Functions from out of the Hub

Bouncing data back and forth between is cool, but the final useful thing you can do is to invoke javascript from outside the hub simply by:

var clients = Hub.GetClients();
clients.alertMessage("external test");

And there we have it! Asynchronous server/client messaging made easy!