/page/2

Single Knockout binding handler for two observables

Let’s say we have model with two observables:

  1. foo
  2. bar

What we need is a single Knockout binding handler. This handler will display value of both observables in a single field.

It will also attach click event handler so when we click field, both observables will be updated with random value.

What’s important, displaying value is expensive in our scenario so when both fields are updated in sequence, only single refresh should occur instead of two sequential refreshes.

It appears that above is relatively easy to do in KnockoutJS. For starters, below is some HTML and model for demo application.

<input type="text" data-bind="value: foo"/>

<input type="text" data-bind="value: bar"/>

<input type="text" data-bind="both: { first: foo, second: bar }"/>

var model = {
  foo: ko.observable('Foo'),
  bar: ko.observable('Bar')
};

As you can see, our binding handler uses { first: someObservable, second: someObservable } syntax.

This is how it looks like:

var counter = 0;

var refresh = function(element, valueAccessor) {
  var value = valueAccessor();
  counter++;
  element.value = counter + ' ' + ko.unwrap(value.first) +
    ' ' + ko.unwrap(value.second);
};

ko.bindingHandlers.both = {
  init: function(element, valueAccessor) {
    element.onclick = function() {
      var value = valueAccessor();
      value.first('Foo' + new Date().getMilliseconds().toString(3));
      value.second('Bar' + new Date().getMilliseconds().toString(3));
    };
    refresh(element, valueAccessor);
  },
  update: function(element, valueAccessor) {
    ko.computed(function () {
      var value = valueAccessor();
      return ko.unwrap(value.first) + ko.unwrap(value.second);
    })
    .extend({ rateLimit: 1 })
    .subscribe(function() {
      refresh(element, valueAccessor);
    });
  }
};

Primo, there is init function in which we are just attaching onclick handler where we are setting two values in model. Very simple stuff. Also in this init function, we are displaying initial value using refresh external function. This is external function because we will need it later elsewhere. What’s interesting about refresh is that it increments counter every time it is called so we can see that we are calling it only when necessary and no more (remember, we are assuming that displaying value is expensive).

Secundo, there is update function. In this function we are taking advantage of computed observables with rateLimit extender. What this extender does is it limits rate of informing interested parties about computed value change. Setting limit to one millisecond is just right when we are concerned about sequential changes. The value returned from computed observable doesn’t really matter, as long as it is different for different input values. When this value changes, attached subscriber starts working and all it does is to invoke refresh function you already know. Pretty simple, huh?

Do you want to JSFiddle it? Have fun with Knockout!

Mocking RequireJS modules in unit tests in Jasmine and TypeScript

If you read very useful blog Mocking RequireJS modules in unit tests you will learn how to do this in QUnit and JavaScript. Here for a change is how to do this in Jasmine and TypeScript:

describe('Controller', () => {
  beforeEach(() => {
    requirejs.undef('Controller');
    requirejs.config({ 
      map: { 
        '*': {
          'Model': 'ModelMock'
        }
      }
    });
    define('ModelMock', () => ModelMock); // ModelMock is a class
  });

  afterEach(() => {
    requirejs.undef('ModelMock');
    requirejs.config({ 
      map: { 
        '*': {
          'Model': 'Model'
        }
      }
    });
    requirejs.undef('Controller');
  });

  it('does something', () => {
    var Controller;
    require(['Controller'], (required) => Controller = required);
    waitsFor(() => Controller, 'Controller');
    runs(() => {
      var sut = new Controller();
      // test sut normally
    });
  });
});

Why you should be using CasperJS (for integration testing)

WatiN and Selenium work in the same way. Maybe WatiN is doing it better as I know some people prefer it. But CasperJS is different. Let me explain.

  • WatiN can automate IE or Firefox.
  • Selenium can automate IE, Firefox, Chrome etc. but also so-called “headless” browser PhantomJS (WebKit / formerly Chrome).
  • CasperJS can only automate “headless” browsers: PhantomJS and SlimerJS (Gecko / Firefox).

Advantage of using “headless” browser is that there is simply less things that can go wrong because we are bypassing browser “decorations” and using just its engine. It’s just taking advantage that web application doesn’t have to be tested as desktop application because it can only run in browser. Both WatiN and Selenium test web application as desktop application. CasperJS tests it as web application.

WatiN and Selenium are here for a while and were born in times when things as PhantomJS or SlimerJS weren’t possible but you should use best thing available now.

Difference between try/finally and using in C#

I used to think of using as of nice shortcut for try/finally. But, unlike try/finally, using protects the variable being inside using() from not being disposed by being overwritten. This is easier than it sounds. Just guess output of this program:

class Program
{
    static void Main(string[] args)
    {
        Crazy crazy;
        // using
        using (crazy = new Crazy("foo"))
        {
            crazy = new Crazy("bar");
        }
        // try/finally
        crazy = new Crazy("finally foo");
        try
        {
            crazy = new Crazy("finally bar");
        }
        finally
        {
            crazy.Dispose();
        }
    }
}

class Crazy : IDisposable
{
    string name;

    public Crazy(string name) { this.name = name; }

    public void Dispose() { Console.WriteLine(name); }
}

It’s foo ⏎ finally bar and not bar ⏎ finally bar. So try/finally gives more control and more responsibility.

For completes, if crazy would be declared inside using() this program would not compile because of error: Cannot assign to 'crazy' because it is a 'using variable' what is good reason for using using variables when possible.

How to access ASP.NET resource strings from inside JavaScript and TypeScript files

tl;dr version: write T4 template and use require.js with lightweight i18n plugin. Here is except from i18n documentation:

Once your web app gets to a certain size and popularity, localizing the strings in the interface and providing other locale-specific information becomes more useful. However, it can be cumbersome to work out a scheme that scales well for supporting multiple locales.

RequireJS allows you to set up a basic module that has localized information without forcing you to provide all locale-specific information up front. It can be added over time, and only strings/values that change between locales can be defined in the locale-specific file.

i18n bundle support is provided by the i18n.js plugin. It is automatically loaded when a module or dependency specifies the !i18n! prefix (more info below). Download the plugin and put it in the same directory as your app’s main JS file.

It made for a nice introduction so we can go straight to the point.

JavaScript

i18n needs JavaScript files basically containing JSON object wrapped as require.js module. Here is example (again from i18n documentation):

//Contents of my/nls/colors.js
define({
    "root": {
        "red": "red",
        "blue": "blue",
        "green": "green"
    },
    "fr-fr": true
});

It’s easy to generate such a file with T4 template. All you have to do is to find resx files in project (you can for example look only for files matching certain regex to filter certain resources) and group them so localized resx files are grouped under neutral resx files. Then use XmlDocument to read those files (they are very simple) and export strings to JSON-like files as in example above. i18n convention is to put all js files with neutral resources in nls folder (this is acronym for national language support) and create sub-folders for each locale (e.g. nls\fr-fr). You also need to hint i18n in neutral file that e.g. fr-fr translation is available like "fr-fr": true above so i18n knows to look for e.g. my/nls/fr-fr/colors.js file.

I can recommend using T4.TemplateFileManager NuGet to ease T4 work because you would need to generate multiple files from single template. TemplateFileManager makes it relatively easy to produce multiple .js files from single template run as well as to find resx files in project. It does include example to get you started quickly. It’s also useful to look at its source. Another one is T4Toolbox but TemplateFileManager worked well for me.

Having generated js files you can just require neutral js file from your JavaScript as you would do for any other require.js module (although please include !i18n! prefix before path). Example copied from i18n documentation:

//Contents of my/lamps.js
define(["i18n!my/nls/colors"], function(colors) {
    return {
        testMessage: "The name for red in this locale is: " + colors.red
    }
});

The plugin will load neutral and then localized strings according to browser’s language (you can override browser’s language what is shown in i18n documentation) and merge them.

TypeScript

That’s all to it if you are just using JavaScript. But for TypeScript guys, here is more.

Wouldn’t it be nice to have compiler error when you renamed resource in resx but forgot to reflect this in code? Here TypeScript declaration files (d.ts) come handy:

declare module '!i18n!nls/colors' {
    /** Looks up a localized string similar to red */
    var red: string;
    /** Looks up a localized string similar to blue */
    var blue: string;
    /** Looks up a localized string similar to green */
    var green: string;
}

And you’ll even get hints in Visual Studio just like in C# (“Looks up a localized…”).

This is how to require that module in TypeScript:

///<reference path='nls/colors.d.ts' />

var colors = require('!i18n!nls/colors');

As you can see relaxiness of module names in TypeScript declaration files comes very useful when dealing with prefixes such as !i18n!.

Of course generating d.ts files in T4 is easier than in js case as you only need to deal with neutral resources.

Closures in C# vs. closures in JavaScript

While reading listing 3.18 from book “Node.js in Action” I thought that closure in JavaScript is a bit more verbose than closure in C#. Hence the idea to look more closely at both and I will do that in this quick note just to have it side by side.

Here is a simple program in C# which will print numbers in sequence. Instead of printing numbers right away, we will defer this task by keeping printing logic in a list of actions and then execute this list.

var tasks = new List<Action>();
for (var i = 0; i < 2; i++)
{
    Action task = () =>
        Console.WriteLine(i);
    tasks.Add(task);
}
foreach (var task in tasks)
    task();

What will be actually printed is not

0
1

but

2
2

This is because we have only one instance of a loop counter for whole loop evaluation. We will explain it further but the workaround is simple. Assign counter to a temporary variable.

var tasks = new List<Action>();
for (var i = 0; i < 2; i++)
{
    var j = i;
    Action task = () =>
        Console.WriteLine(j);
    tasks.Add(task);
}
foreach (var task in tasks)
    task();

Now the result is

0
1

If you wonder, with while loop you would still need this temporary variable trick.

var tasks = new List<Action>();
var i = 0;
while (i < 2)
{
    var j = i;
    Action task = () =>
        Console.WriteLine(j);
    tasks.Add(task);
    i++;
}
foreach (var task in tasks)
    task();

The result is

0
1

As you may already know, the situation with foreach loop is simpler. Since C# 5 you don’t need temporary variable. You will get expected closure ‘for free’.

var tasks = new List<Action>();
foreach (var i in Enumerable.Range(0, 2))
{
    Action task = () =>
        Console.WriteLine(i);
    tasks.Add(task);
}
foreach (var task in tasks)
    task();

The result is

0
1

Now lets look at JavaScript version of the first code.

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = function() {
        console.log(i);
    };
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

As the C# version it prints

2
2

Let’s try temporary variable trick

var tasks = [];
for (var i = 0; i < 2; i++) {
    var j = i;
    var task = function() {
        console.log(j);
    };
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

That’s better now it prints

1
1

But that is not ideal. Let’s move assignment to task body.

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = function() {
        var j = i;
        console.log(j);
    };
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

This obviously doesn’t work, we get back the first result

2
2

But what if we encapsulate printing logic in anonymous function that we will return. Isn’t it how closures work in JavaScript?

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = function() {
        var j = i;
        return function() {
            console.log(j);
        };
    };
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]()();

Oops, still no joy.

2
2

This is not exactly how it should be done. Noticed the double ()() in the last line? Are we closing over too late? Let’s try this

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = (function() {
        var j = i;
        return function() {
            console.log(j);
        };
    })();
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

Now it works. Notice the self-executing function. It executes when counter value is still what we want.

0
1

What if we use function argument instead of temporary variable. Should be same thing.

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = (function(i) {
        return function() {
            console.log(i);
        };
    })(i);
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

And it is

0
1

What if we remove this function argument?

var tasks = [];
for (var i = 0; i < 2; i++) {
    var task = (function() {
        return function() {
            console.log(i);
        };
    })();
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

As you can guess, the result is

2
2

Let’s add temporary variable assignment back. But let’s put this assignment before function which returns closure. Will it work?

var tasks = [];
for (var i = 0; i < 2; i++) {
    var j = i;
    var task = (function() {
        return function() {
            console.log(j);
        };
    })();
    tasks.push(task);
}
for (var index in tasks)
    tasks[index]();

No, now it’s

1
1

What if we put this into another anonymous function?

var tasks = [];
for (var i = 0; i < 2; i++)
    (function() {
        var j = i;
        var task = (function() {
            return function() {
                console.log(j);
            };
        })();
        tasks.push(task);
    })();
for (var index in tasks)
    tasks[index]();

So now it works again

0
1

So we can summarize that, in JavaScript, you need to create variable in a function (or have it given as this function’s argument, same thing here) and then return function from this function to have a closure over that variable happen.

Let’s remove the inner anonymous function, one should be enough.

var tasks = [];
for (var i = 0; i < 2; i++)
    (function() {
        var j = i;
        var task = function() {
            console.log(j);
        };
        tasks.push(task);
    })();
for (var index in tasks)
    tasks[index]();

This prints

0
1

This last code seems to be good to show the difference between C# and JavaScript in this matter. Let’s bring C# version again.

var tasks = new List<Action>();
for (var i = 0; i < 2; i++)
{
    var j = i;
    Action task = () =>
        Console.WriteLine(j);
    tasks.Add(task);
}
foreach (var task in tasks)
    task();

As you can see in JavaScript you need that outer function - this is your closure’s environment. In C# you get it ‘for free’ in this case. Furthermore as our code uses loop the temporary variable is required in both languages if you need the current loop value not the last loop evaluation value.

And just for the sake of completeness lets modify the last JavaScript code to replace temporary variable with function argument.

var tasks = [];
for (var i = 0; i < 2; i++)
    (function(i) {
        var task = function() {
            console.log(i);
        };
        tasks.push(task);
    })(i);
for (var index in tasks)
    tasks[index]();

This still prints valid result and is probably the nicest version.

0
1

What if we remove argument from function again?

var tasks = [];
for (var i = 0; i < 2; i++)
    (function() {
        var task = function() {
            console.log(i);
        };
        tasks.push(task);
    })();
for (var index in tasks)
    tasks[index]();

As you may have expected

2
2

Hopefully that wasn’t too boring. Till the next time!

I just discovered this file in my Visual Studio directory. The file is named VPDExpressSplash.bmp. I have just normal Visual Studio 2012 and Windows Phone SDK 8.0 installation so inclusion of this bitmap with &#8220;Microsoft confidential&#8221; text is obviously some sort of mistake in installer build script. I found this file also in $PatchCache$ Windows folder so most likely this came along with patch and not within main product install.

I just discovered this file in my Visual Studio directory. The file is named VPDExpressSplash.bmp. I have just normal Visual Studio 2012 and Windows Phone SDK 8.0 installation so inclusion of this bitmap with “Microsoft confidential” text is obviously some sort of mistake in installer build script. I found this file also in $PatchCache$ Windows folder so most likely this came along with patch and not within main product install.

Durandal Activator and TypeScript - why view is not bounded and how to fix it

This is a quick note so to save you debugging when you notice that your viewmodel is loaded but view is not displayed when you are using Activator.

I was using TypeScript 0.8 which only supported one way of doing AMD’s export and to make this work with what durandal expects, I pulled this Jaben’s gist.

It was working fine and I forgot about all this when I was upgrading to TypeScript 0.9 which supports export = syntax so you don’t need that plugin anymore.

So when I wanted to use durandal’s Activator to get more control I saw that viewmodel was loaded and activated but somehow the view was not bouned nor displayed. This is because extension point which this plugin is using system.resolveObject is not involved in composition when you are using Activator. The exact thing from this plugin which is needed here is to invoke system.setModuleId.

The solution is simple: upgrade to TypeScript 0.9 and write export =.

Durandal composition repeats and repeats and repeats

In Durandal you can use compose binding to compose several views. This is very powerful and works great but today I found (the hard way) something to be aware of. Consider following views:

<div data-bind="css : { 'somestuff' : somestuff }">
    <!-- ko compose: childViewName --><!-- /ko -->
</div>

and

<div data-bind="css : { 'somestuff' : somestuff }, compose: childViewName">
</div>

Will they produce exactly the same output (ignoring comments in output)? Yes.

Will they work in exactly the same way? Unfortunately not. When you are using more compact version (the second one), every time you change somestuff, the child view will be composed again and again even if childViewName is unchanged.

As a matter of fact if you have more properties bound in that element (e.g. somestuff2), the view will be recomposed “for” each and every one changed (because Knockout binds synchronously).

Of course each time you will get brand new view model for child view as well which can be… let’s say ‘problematic’ until you find out why!

PS. This was “observed” in Durandal 2.0 and 2.0.1 and today’s master on GitHub. All with Knockout 2.2.1.

PS2. As @DurandalJS generously replied on Twitter, it’s a Knockout issue, fixed in Knockout 3.0 :-)

TypeScript in Visual Studio 2010 with quick compilation on save - integrated with existing ASP.NET project

Here is a quick recipe.

Download TypeScriptSetup.0.8.2.msi (not never) and install in a way described on this blog so it will install for Visual Studio 2010. Don’t worry if it will not work yet.

Download TypeScriptSetup.0.8.3.msi or newer and install it normally.

Open your existing solution in Visual Studio 2010 and add to it a new TypeScript project (look for it in Other Languages group in new project window). Remove all files from this new project.

Open command prompt and type following (change path according to your setup, I am assuming here that you already have Scripts folder in ASP.NETProject):

mklink /J C:\TypeScriptProject\Scripts C:\ASP.NETProject\Scripts

This will map your existing Scripts folder as “new” Scripts folder in TypeScriptProject.

Open Tools|Options|TypeScript|Project and check Automatically compile TypeScript files which are part of project.

Go to Solution Explorer, check Show All Files, refresh TypeScriptProject, right click on Scripts folder and click Include In Project.

Add new TypeScript file to Scripts folder in TypeScriptProject (look for TypeScript file in Visual C# group in add new item window).

Once you save your TypeScript file it will be automatically compiled into JavaScript file which you may normally use in ASP.NETProject from its Scripts folder (you may include this JS file in project if you wish).

Since TypeScript files are already compiled upon save, you can save some time on solution build by going to Build|Configuration Manager and unchecking Build on TypeScriptProject.

Single Knockout binding handler for two observables
Mocking RequireJS modules in unit tests in Jasmine and TypeScript
Why you should be using CasperJS (for integration testing)
Difference between try/finally and using in C#
How to access ASP.NET resource strings from inside JavaScript and TypeScript files
Closures in C# vs. closures in JavaScript
Durandal Activator and TypeScript - why view is not bounded and how to fix it
Durandal composition repeats and repeats and repeats
TypeScript in Visual Studio 2010 with quick compilation on save - integrated with existing ASP.NET project

About:

Hi! My name is Paweł and on this mini blog you can find my
random ramblings on programming (Delphi, .NET in general)

@pol84_

Following: