Solving setTimeout-problem using QUnit and SinonJS
Recently had a problem testing setTimout-callbacks when using the QUnit javascript testing framework and also adding SinonJS to the mix for faking xmlHttp-requests. Could not get the callback to fire. After a long time trying different examples using QUnit and SinonJS I finally got my facepalm moment and solved it.
When adding the Sinon javascript and sinon-qunit script the QUnit script has a config section that enables useFakeTimers by default, so the clock wouldn’t tick/advance by default.
If you really want to use setTimeout the QUnit way (start/stop-functions), then your tests will have to wait until timeout elapses
A better way is to use sinon’s fake timers. a trivial example:
test("test with useFakeTimers", function () {
this.sandbox.useFakeTimers();
setTimeout(function () {
ok(true, "timeout sucessfully called");
}, 150);
this.sandbox.clock.tick(200);
});
and if you have useFakeTimers = true in your sinon-qunit-javascript you can even remove this.sandbox.useFakeTimers()
note: as of february 2010 the source at github has changed to have useFakeTimers disabled by default.
Serialize .NET objects as camelCase JSON
ASP.NET MVC is amazing how easy it is to serialize from a .NET POCO to JSON and the other way around using the model binder. But one thing I really don’t like is how serializing .NET objects to JSON returns the properties PascalCase.
Net has PascalCase coding convention for properties and JavaScript uses camelCase.
The solution is to use Json.NET to serialize the objects (which will be included by default in Visual Studio 2012).
Continuing on the previous blog post you would then
Install Newtonsoft Json.NET using NuGet.
Modify the controller so instead of returning
return Json(new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior.AllowGet);
you would create a JsonSerializerSettings, Serialize the object with JsonConvert and return the content with content type application/json
public ActionResult Load()
{
var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var json = JsonConvert.SerializeObject(dog, Formatting.Indented, jsonSerializerSettings);
return Content(json, "application/json");
}
which would give you
{
"name": "Rambo",
"age": 5
}
instead of
{
"Name": "Rambo",
"Age": 5
}
return new JsonCamelCaseResult
{
Data = new Dog { Name = "Rambo", Age = 5 },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
Automatic mapping with Knockout.js, the mapping plugin and ASP.NET MVC 3

Expected outcome
- Having a C# Dog class with name and age-properties.
- When the page loads, it automatically loads the dog using jQuery ajax (serialized as json) and creates a knockout viewmodel.
- ViewModel should automatically add properties from the C# model.
- The knockout ViewModel should be able to have extra computed methods for validating form for example.
- The ViewModel should be able to save the dog using ajax.
Installing components
Install Knockout.Mapping using NuGet, this will automatically install Knockout.
Create Model
First, create the dog, a simple C# plain object with two properties: Name and Age
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}
Create MVC Controller
Then create a empty DogController and add a empty Index method. The Load method just creates a simple instance of a dog and returns it as Json, and finally the Save method only accepts post data and just returns a formatted string in Json-format containing the updated Dog
public class DogController : Controller
{
public virtual ActionResult Index()
{
return View();
}
public ActionResult Load()
{
return Json(new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Save(Dog dog)
{
return Json(new { Status = string.Format("Success, saved {0} with age: {1}", dog.Name, dog.Age) });
}
}
Create View
Create empty Index View and add script-references
<script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-mapping-latest.js")" type="text/javascript"></script>
Then you add a form containing the knockout bindings bound to the observables on the ViewModel. Two input boxes data bound to Name and Age, the submit-action to “save”, a function on the JavsScript ViewModel, and finally data-bind the submit button so it’s enabled only if the model is valid.
<form method="POST" data-bind="submit: save">
<div>Name:</div>
<div><input type="text" data-bind="value: Name" /></div>
<div>Age:</div>
<div><input type="text" data-bind="value: Age" /></div>
<div><input type="submit" value="Save" data-bind="enable: isValid()" /></div>
</form>
Create ViewModel
Create a class in JavaScript, taking JSON data to be mapped as parameter, and add isValid as a computed property and finally a save function that posts the JSON-data back to the DogController’s Save method.
var ViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.isValid = ko.computed(function () {
return self.name().length > 0;
});
self.save = function () {
$.ajax({
url: "Knockout2/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(self),
success: function (response) {
alert(response.Status);
}
});
};
};
Load initial data
Finally you add a JavaScript document ready handler that loads the initial data. Place it below the ViewModel.
$(function () {
$.getJSON("Dog/Load", null, function (data) {
ko.applyBindings(new ViewModel(data));
});
});
Conclusion
This is probably not the best way, and of course there are lots of stuff you should do. For example, move javascript references to bottom of page, validate the postback and more. But I tried to keep the example as simple as possible.
Download the project here:
Create Html.DropdownListFor without magic strings
Using magic strings are bad practice. Changes could lead to code compiling but containing lots of errors (appearing during runtime). And refactoring your code is a lot harder if you have to globally search and replace.
Using dropdown lists with ASP.NET MVC has a Html-helper that wants you to use magic strings. Having a Category class:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
And a viewmodel:
public class DropdownViewModel
{
public int CategoryId { get; set; }
public Category[] Categories { get; set; }
}
You would then use the html-helper like this:
public static class ExtensionMethods
{
public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> enumerable, Func<TItem, TValue> value, Func<TItem, string> text, string defaultText = null, string defaultValue = null)
{
var itms = enumerable.Select(f => new SelectListItem { Text = text(f), Value = value(f).ToString() }).ToList();
if (defaultText != null)
itms.Insert(0, new SelectListItem { Text = defaultText, Value = defaultValue ?? "0" });
return itms;
}
}
Now it’s easy to just use lambdas and, this little extension method has a couple of overloads.
Html.DropDownListFor(m => m.CategoryId,
Model.Categories.ToSelectList(f => f.CategoryId, f => f.Name))
Usage is really easy, just use the extension method on the Array you wish to create a dropdown items from.
Now your code is refactor safe
First parameter: Selected item in model
Second parameter: Id/value-item (generic TValue, so you can use for example int’s without calling ToString()
Third parameter: Text to display for each item in dropdown
Fourth parameter(optional): Empty default-text (first item in dropdown), uses value “0″ if fifth parameter isn’t supplied
Fifth parameter(optional): Empty default-value
Creating and intitializing ArrayList in one line
There are multiple ways of creating a ArrayList and adding a couple of items to it.
The usual way to do it:
List<String> normal = new ArrayList<String>();
normal.add("one");
normal.add("two");
normal.add("three");
Or you could use the double braces. The inner pair of braces creates a anonymous innner class
List<String> doubleBraces = new ArrayList<String>() {{
add("one");
add("two");
add("three");
}};
But I prefer to use a small static method that uses generics and varargs to accomplish the same thing.
public class Simple {
public static <T> ArrayList<T> listOf(T... elements) {
ArrayList<T> list = new ArrayList<T>();
for (T element : elements) {
list.add(element);
}
return list;
}
}
And to use it you just write:
List<String> simple = Simple.listOf("one", "two", "three");





