Getting the right width and height on you canvas

I learned something today. I was playing around with the <canvas> HTML5 element. When rendering on the canvases you do it by using the canvas’ context:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.fillRect(0,0,10,10) // makes a square at (0,0) with sides 10

the unit that is used when drawing the square is dependent on the width and height property of the canvas.

So,let’s say that you do this:

canvas.width = 100;
canvas.height = 50;

On a canvas element that is styled (using css) to have width equal to height. What you’re getting is a rectangle that is more higher – since you’re filling 10 of the available 50 units (that’s 20%) of height but only 10 of the 100 units for width (10%).

By default, in Chrome, the canvas is 300×150. For the application I’m developing right now I want it to be window.innerHeight x window.innerWidth. I even wrote a converter form my “application units” and actual pixels. Looking back at this, I would have styled the canvas to full screen, then set it’s width and height in accordance to the measures of the game. Well… that’s for next time.

I still had problems getting things to work. It turned out to be a “feature” of jQuery. Look at this:

Confusing JavaScript / jQuery


Create NuGet package for Javascript Library (pt1)

In an earlier post, I wrote about how you should setup the build of a NuGet package. I really liked the simplicity of making the package out of my .csproj file. However, the package I’m working with currently only contains one minified javascript file, and it turned out that if I created the package out of the csproj-file, I got an assembly reference to the project as well.

There are people who never would use Visual Studio to make JavaScript libraries. For me, comming from a .NET background, I’m more than familiar with VS, and with the Jasmine Testrunning Setup I described earlier, I run javascript unit tests just as I have always run nUnit-tests (Ctrl + U + R). In addition I think the intellisence is splendid.

I could of course create a .nuspec file and run the package command on build. But I would run in to problems, since the NuGet update command only works if there is a newer version out there. That would mean manually change the <version> content in the nuspec-file before build in order to be able to update the package in other projects. This is just something that I can’t live with.

After a few hours of work, this was the result:

My NuGet Package, versioned after todays date in my Local Repo

What is worth noting with this picture?

  • The version of the package is 1.YYmmDD.hhMM (that is year month day [dot] hour minute – every time I build with Release Configuration, a new package will be created with an incremented version number to the previous newest version. It also has some sort of time stamp, which I like for this project since I’m not going to work with major and minor versions.
  • It’s from my local repo C:\NuGet\Repo

In my following posts, I will explain how I accomplished this.

10 minute guide to get Visual Studio to combine and minify your javascripts on build

I thought this was going to be a tough nut to crack, but it turned out to be pretty straight forward.

Install JsMin

JsMin is a pretty slick tool. I like it because it is stand alone and small enough to have in your Solutions “tool” folder. So the first step is just to head over, download it and put it somewhere in your solution.

Add post-build event

Right click on your project, select options and go to the tab Build event. You will find a small (too small if you ask me!) textarea; Post-build event command line. You will want to write something like this:

type “$(ProjectDir)\Scripts\Pitfall\*.js” | “$(ProjectDir)..\tools\jsmin” > “$(ProjectDir)\Scripts\pitfall.min.js”

let’s go through the different things that happens in that oh so slick one-liner:

  • type “$(ProjectDir)\Scripts\Pitfall\*.js”: type is a command that displays content in files. In this case, since I have wildcard .js it will give me the content of all the files I have there
  • “$(ProjectDir)..\tools\jsmin” > “$(ProjectDir)\Scripts\pitfall.min.js”: this first finds the directory in which I have places JsMin. Since I used the pipe command (“|”) it will take that as first input. Lastly it outputs the minified file to pitfall.min.js

Given that you don’t have a more complex scenario with dependencies that you don’t want to add into the minified file this is pretty much it. I said it was going to be a ten minute guide. Looking back, it feels more like a 2 minute guid. Good luck :)


Running Jasmine unit test with ReSharper

What would I do without ReSharper? The reason why I’m extra happy about it today is the fact that it integrates so nicely with other test runners, like Jasmine. At first, I looked at other test runners, such as Chutzpah, but I don’t want to run my unit test from a terminal.

So I downloaded Jasmine together with a sample of how it’s used (it had Song.js and Player.js together with a spec). It also contained a html file which I could browse to in order to run my tests.That is not optimal, so to my surprise I saw the little ReSharper test runner symbol next to all the jasmine unit tests

Code snippet from the jasmine sample

There was only one thing left to do in order to get these test running properly:

// Classes to test
/// <reference path="~/Scripts/jasmine-samples/Song.js"/>
/// <reference path="~/Scripts/jasmine-samples/Player.js"/>
// The Jasmine Test Framework
/// <reference path="~/Jasmine/Runner/jasmine.js"/>
/// <reference path="~/Jasmine/Runner/jasmine-html.js"/>
/// <reference path="~/Jasmine/Runner/SpecHelper.js"/>

These XML comments just refers to the files we need to run the test. The reason they weren’t there at the first place is because they were refereed in the sample HTML file.

So now when I run the unit test (Ctrl.+ R works nicely), this is what I get:

Results when running the unit tests

That means I’m all set to start writing my own javascript unit tests

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.



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"}