How to set up a NuGet project

I’ve been exploring the NuGet package concept lately. I think it is a pretty slick way to keep functionality separated as well as dependencies.

So, I thought I try to make a canvas javascript game. However, I haven’t decided where it will “live” (MVC4 applicaton? that might be much to much. NancyFx? That could do it). In the future I might want to opt in some SignalR features.

So my idea is to create the core of the game as one NuGet package, then create a second package with the SignalR implementation. That package then has a dependency to the core package. My web application then reference to the signalr package and that way get everything it need right away. All updates will be handled with NuGet.

To make things smoother, I decided that every build with Release configuration should produce a new, uniquely versioned package. In order to get that working, I had to take a few steps:

Auto increment Build Version

How this should be done properly is a topic in itself. try google auto increase assemblyversion c# to take part of the discussion. I did not want to give this too much thought, so I followed the comment in the AssemblyInfo.cs:

// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

Worth noting is that you want to remove [assembly: AssemblyFileVersion("")] from your file. This makes the Assemby File Version the same as the Assembly Version, which I think is ok.

Write powershell script

Powershell is pretty powerful. It is build on top of .NET, so there is all reasons to get familiar with it. Besides, if I where to chose between powershell and, say, MsBuild… well, that’s a pretty easy thing. For the time being, the my ps script is a oneliner, but who knows – it might grow over time:

    $Configuration = "Release")
& echo "Starting to package the nuget package" 
& nuget pack ../Pitfall.Nuget/Pitfall.Nuget.csproj -Prop Configuration=$Configuration -OutputDirectory ../Pitfall.Nuget/nuget-packages

A few things are worth noting:

  • param is the set of input parameters. When in the powershell terminal you get intelisence of available flags. Release is the default value if you don’t specify
  • I’m keepin my build script outside the project folder, in a sub folder to the solution, therefore I want to specify OutputDirectory, since it will otherwise build to wherever the script is executed (e.g. my script directory).
  • Before the first time running this script, I executed nuget spec, to create an manifesto file used in the packaging process.

Hook the script to project build

I don’t know why Microsoft decided to make this so cumbersome. So I need to edit the .csproj file, which in itself is an XML file that describes the project, what files to include if release, build targets etc. In order to edit the file, right click and Unload project and then right click and select Edit project file.

Where close to the end, there is a comment with to targets, BeforeBuild and AfterBuild. What I did was uncomment the AfterBuild target an added this line:

<Exec Command="powershell.exe -NonInteractive -executionpolicy Unrestricted -command &quot;&amp; {../scripts/create.nuget.ps1}&quot;" Condition="$(Configuration) == 'Release'" />

Again, there are a few gottchas:

  • quotes (“) and ampersand (&) is not allowed, therefore we need to use &quot; and &amp;.
  • By default, the script environment has a execution policy that are Restricted, meaning you are not allowed to run script. Hence the -executionpolicy flag
  • The Condition attribute tells MsBuild that only do this if we’re using Release configuration

Setting up a local NuGet repositoiry

Under Tools > Library Package Manager > Package Manager Settings, go to Package Sources and click the plus. You probably want one directory to which you build all your nuget packages — add that directory and you should be done.

Now, when you open the package manager, you will see at the menu to the left that there is a new source, “Local” (or whatever you have named it). And there is your package. Click and install.



Access Internals from different assemblies

It is always good to reflect what access modifier that should be used when and where. In my current hobby project I found myself exposing really dangerous methods, like


Why? Well, I wanted to test this method, and the unit test of course lays in a different assembly.

May I remind everyone, that it is not necessary! What you want to do is use the InternalsVisibleTo attribute.

In the AssemblyInfo.cs for project that has methods you want to test, just add something like this:

[assembly: InternalsVisibleTo("MyApplication.Core.Tests")]

Thank you a lot for that, Microsoft!

Working with jQuery and Html Templates

When working with javascript frameworks such as Mustasch.js you usually want to have you html templates in your html-file or in a html template file (you definitly don’t want it as a string somewhere in your javascripts). I had an validation error message template that I wanted to populate with validation messages:

<script type="text/template" id="validation-alert-content">
        <button type="button" data-dismiss="alert">×</button>
        <p>Default Error</p>

The server side validation was called with ajax. Depending on the response, I wanted to customize the content of my alert, e.g. change the Default Error text.

Strangely enough, when I did this:

var createAlertWithContent = function(content) {
    var alertContainer = $('#validation-alert-content');
    var myParagraph = alertContainer.find('p');
    return alertContainer.html();

The default error text was displayed. It became obviose that the content alertContent was not an html element, but a string. Therefore


Gave me just an empty array. One solution to the problem was to change type of my template from <script> to <div>. However, I didn’t like the idea of a div at my page that held error message content without nothing being wrong. What is the semantic in that?



Gave me the paragraph that I was looking for. Another problem arouse, that it looks like a few other people have tried to solve. I must say that I do not like the proposed solution, but I figured I rather hide that ugly hack somewhere deep in my javascript, and that way keep the html template beautiful.

Here’s the result:

var createAlertWithContent = function(content) {
    var scriptTemplate = $('#validation-alert-content');
    var alertContainer = $('<div>' + scriptTemplate.html() +'</div>');
    var myParagraph = alertContainer.find('p');
    return alertContainer.html();

How to Model-binding JSON ajax post in Nancy

I’ve been stuck for a few hours trying to understand why NancyFx wouldn’t model-bind my ajax post properly. All primitive datatypes, such as int and string was correctly mapped, but not my array of objects (that only had string properties).

I can’t really say that i “figured it out”, but after some trial and error, this is what worked for me.

The NancyModule, which looks pretty much as it is expected to:

Post["/add"] = p =>
                                  MyViewModel model = this.Bind();     
                                   return "Done!";

And the magic part is the two last props, contentType and dataType. I have not verified it, but I guess that without those another model parser is being used?

        url: '/add',
        type: 'POST',
        data: normalModel,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',

Another part of todays lesson (that resulted in my first StackOverflow post ever) is that there is a difference between JS object and JSON, where the latter one has citation signs on the property name like this

{ "foo" : "bar" }

where JS objects only look like this:

{foo : "bar"}

Serialize Razor Viewmodel to JSON object in NancyFx

I’ve really taken a liking to NancyFx, the lightweight web framework for .net. In addition to a nice graphical profile ( :) ), short startup time, minimum effort for a “Hello world” response it also uses a REST-approach and minimum amount of configuration.

Being familiar with Razor view engine, I desided to use the Nancy Nuget package for it. So far, so good.

For some parts of my view, I’m using Knockout.js for redering components that I need to manipulate on client side. Instead of adding another request and useg AJAX for getting a JSON representation of my viewmodel, I wanted to take my POCO Razor Model and convert it into JSON.

I found Nancy.Json.JavaScriptSerializer in the Nancy assembly, that I thought would be just right for the job. My Razor syntax looked something like this

        var MyViewModel = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

However, no matter what I tried to do, I ended up with the nice looking, but after a while oh so irritating error message:

Razor Compilation Error

 The type or namespace name 'Json' does not exist in the namespace 'Nancy' (are you missing an assembly reference?)

The solution to this was not to difficult. There is a RazorConfigurationSection that you could use in Web.config for adding assemblies to the view rendering. Here is what is would look lke:

    <section name="razor" type="Nancy.ViewEngines.Razor.RazorConfigurationSection, Nancy.ViewEngines.Razor" />
  <!-- Adding handlers for Razor Default Namespaces-->
  <razor disableAutoIncludeModelNamespace="false">
      <add assembly="Nancy" />
      <add namespace="Nancy.Json" />

Hitting F5 again and page loaded with my very own viewmodel as a json object.

Typeahead from Twitter Bootstrap data-bound in Knockout.js

After writing about Knockout.js and Twitter Bootstrap‘s Popover and Tooltip, it feels just about right that I continue to rant about how to get the two frameworks to get along. This time, it’s Typehead‘s time to get examined.

In general I like how Twitter Bootstrap works with the data-attributes when describing what I’m expecting from it, such as data-title for the title of a popover, or data-toggle for how the collapse function will disappear/reappear.

For Typeahead, I found it a bit frustrating that the data-source, that is used to populate the typeahead list with options, must be decleared as a list like so:

<input type="text" data-source="
,&quot;Nevada&quot;,&quot;New Hampshire&quot;,&quot;New Jersey&quot;
,&quot;New Mexico&quot;,&quot;New York&quot;,&quot;North Dakota&quot;
,&quot;North Carolina&quot;,&quot;Ohio&quot;,&quot;Oklahoma&quot;
,&quot;Oregon&quot;,&quot;Pennsylvania&quot;,&quot;Rhode Island&quot;
,&quot;South Carolina&quot;,&quot;South Dakota&quot;
,&quot;West Virginia&quot;,&quot;Wisconsin&quot;,&quot;Wyoming&quot;]"
 data-items="4" data-provide="typeahead" style="margin: 0 auto;">
(Example from Twitter Bootstraps).

That kind of code just makes the source very unreadable. Therefore,when I wrote the custom data-binding in Knockout, I added the possibility to describe the datasource as an ko.observableArray/javascript variable/objects property.Here’s what you would write if you had an observable array named colors that you wanted to use as data source for your typeahead:

<input type="text" data-bind="typeahead: colors"/>

Imagine that you had some list that is not part of your model (maybe it is not important to keep track on the list):

var allColors = ["Red", "Green", "Yellow", "Black"];

The databinding is described just the same, but with singel citation signs like this:

 <input type="text" data-bind="typeahead: 'allColors '"/>

Similarly, if you have an javascript object and you want one if its properties as datasource:

var myComplexObject = {
    animals: ["pig", "pony", "dog", "cat", "cow", "chicken", "fish", "fox"]

You just have to write:

<input type="text" data-bind="typeahead: 'myComplexObject.animals'"/>

Here’s the custom biding code, which can be tested in the fiddle.

ko.bindingHandlers.typeahead = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var typeaheadSource; // <-- this is where our typeahead options will be stored in
        //this is the parameter that you pass from you data-bind expression in the mark-up
        var passedValueFromMarkup = ko.utils.unwrapObservable(valueAccessor());
        if (passedValueFromMarkup instanceof Array) typeaheadSource = passedValueFromMarkup;
        else {
            // if the name contains '.', then we expect it to be a property in an object such as myLists.listOfCards
            var splitedName = passedValueFromMarkup.split('.');
            var result = window[splitedName[0]];
            $.each($(splitedName).slice(1, splitedName.length), function(iteration, name) {
                result = result[name];

            // if we find any array in the JsVariable, then use that as source, otherwise init without any specific source and hope that it is defined from attributes
            if (result != null && result.length > 0) {
                typeaheadSource = result;

        if (typeaheadSource == null) $(element).typeahead();
        else {
                source: typeaheadSource


Popover from Twitter Bootstrap with Knockout.js observable

I explained earlier how to get Twitter Bootstrap‘s neat Tooltip feature to work with Knockout.js observables. For my current project I wanted to be able to edit the value of my observable property from within a Twitter Bootstrap Popover.

My goal was to be able to keep as much of the bootstrap functionality intact(e.g. the data-attributes should work) and also be able to combine tooltip databinding with other knockout bindings. In a nutshell, I wanted to be able to write something like

<span data-placement="bottom" data-title="write new text to update" data-bind="popover: '#editTemplate', text:exampleText"></span>


  • #editTemplate is the Css Selector for a html-template that contains the desired popover content
  • exampleText is, just like when it comes to any other Knockout binding – just a property on the ViewModel.
  • data-placement and data-title are attributes that Twitter Bootstrap uses to render the Popover

I found this to be a bit tricky, since the popover content will typically be appended to the DOM after the ko.applyBindings(viewModel) is called. Therefore, the data-bindings will not be noticed by Knockout and the binding will not take place.

Luckely, it is quite a pleasure to extend Knockout with custom bindings. Here’s the binding that I wrote:

ko.bindingHandlers.popover = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var cssSelectorForPopoverTemplate = ko.utils.unwrapObservable(valueAccessor());
            var popOverTemplate = "<div id='my-knockout-popver'>" + $(cssSelectorForPopoverTemplate).html() + "</div>";
            $(element).popover({ content: popOverTemplate, html:true, trigger: 'manual' });

            $(element).click(function() {
                var thePopover = document.getElementById("my-knockout-popver");
                ko.applyBindings(viewModel, thePopover);

There are a few things that can be made more nicely, like creating the surrounding <div> using jQuery’s wrap(). A limitation with this implementation is that the popover is toggled by click. This can easerly be solved by adding a data-trigger atttriute in the HTML and in the js method look at the element to see if it has that attribute and if so change the click-listener to a hover-listener etc.


The JsFiddel is found here.

Knockout.js – Solvning the problem with “Unable to parse bindings”

A common pattern for a view model with Knockout.js is to have some sort of observableArray and another observable to keep track of a specific (usually selected) element, such as

self.difficultyOptions = ko.observableArray([
        { level: "Easy" }, { level: "Medium" }, { level: "Hard" }
self.difficultySelected = ko.observable();

This, however, will give you a binding error

>Error: Unable to parse bindings.
>Message: TypeError: difficultySelected() is undefined;
>Bindings value: text:difficultySelected().level

It took me some time to figure it out, but this is due to the fact that difficultySelected did not have any initial value. When changing to

self.difficultySelected = ko.observable(self.difficultyOptions()[0]);

everything worked like a charm!

Tooltip from Twitter Bootstrap with Knockout.js observable

Working with Twitter Bootstrap in combination with Knockout.js can be cumbersome, as  they are not out of the box compatible.

So… The other day, I wanted to display some value from my viewmodel on a twitter bootstrap tooltip.

What I wanted to be able to do is something like

<a href="#" data-bind="tooltip: info">this</a>

The best way to get both frameworks to get along nicely is to write custom databindings for Knockout.js, that takes care of the bootstrapping of the bootstraper :)

It turned out that extending Knockout.js is really simple. Without further ado, I give you: the Tooltip Custom Binding:

ko.bindingHandlers.tooltip = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
            title: valueUnwrapped

To get this working, simply add this code somewhere before you databind you model. For a working example, go to this fiddler.