March, 2013

Mongoose with TypeScript

Mongoose is a library for node.js that wraps the mongoDB driver. Since I’ve been playing with typescript, I wanted to show a short demo of strongly typing mongoose with unit tests run in nodeunit all using typescript.


First, I have a collection of definition files that represent mongoose types, nodeunit types, and my own document types (in schemaDef.d.ts).


///<reference path="./mongoose.d.ts"/>
///<reference path="./nodeUnit.d.ts"/>
///<reference path="./schemaDef.d.ts"/>

The nodeunit definitions /def/nodeUnit.d.ts

interface ITest{
done(): void;
ok(isGood:Boolean, message?:string):void;
equal(expected:any, actual:any, message?:string);

Here are the basic mongoose definitions in /def/mongoose.d.ts. I can’t guarantee that these types are right, I’m updating them as I go along. I’m inferring the structure from the documentation and personal experimentation. As I encounter new mongoose definitions, I can just add them to the appropriate scope. You can see that I’m also chaining definitions: one definitions functions might return another interface that has … Read more

, ,

Tech talk: Javascript Memory Leaks and JSWhiz

Todays tech talk revolved around the recently published JSWhiz whitepaper from google. The paper discusses common javascript memory leak patterns. It also goes over how those leaks can be created and how google automated detection of them using Closure type annotations.


First Google identified common javascript memory leak patterns, though some of these are described in terms of Closure syntax

  • Create without dispose EventHandler – “Closure objects of type EventHandler provide a simple mechanism to group all events and listeners associated with an object together. This allows for easy removal of listeners when the events being listened to can no longer fire. Unfortunately this is also one of the main sources of leaks
  • Setting member to null without removing event listeners. “In JavaScript setting a variable to null is the idiomatic way of providing a hint to the garbage collector that the memory allocated by an
Read more


Merging two immutable dictionaries in F#

If you ever need to merge two immutable dictionaries (maps) that may share the same key, here is how I did it

let mapMerge group1 group2 appender = 
    group1 |> Seq.fold(fun (acc:Map<'a,'b>) (KeyValue(key, values)) -> 
                      match acc.TryFind key with
                                        | Some items -> Map.add key (appender values items) acc
                                        | None -> Map.add key values acc) group2

// for example, assume map1 and map2 are dictionaries of type
// Map<string, seq<string>>
// then the appender deals with how to merge duplicate keys
let joinMaps = mapMerge map1 map2 Seq.append

It doesn’t matter which group you treat as the source and which group you treat as the seed since you are creating a new dictionary out of the two. By pre-seeding the fold with one of the dictionaries you know that the accumulator will already have some of the values you want. The map will iterate over the second dictionary (used … Read more


When to abort a thread

When is it OK to abort a thread is a question that comes up every so often. Usually everyone jumps on the bandwagon that you should never ever do a thread abort, but I don’t agree. Certainly there are times when it’s valid and if you understand what you are doing then it’s ok to use.

The reasoning behind never using thread abort is because calling abort on a thread issues an asynchronous exception, meaning that exceptions could happen where you think there never should be exceptions such as dispose methods or finally blocks. This post describes what happens with thread abort and I found it to be a good read.

But, I still don’t think you should never use thread abort. The big issue is what if you don’t have access to the code that is running in the thread? If a 3rd party library is blocking your app … Read more

, ,

Implementing partial functions

This next section I had a lot of fun with, and originally I didn’t plan on implementing it at all. The only reason I did it is because I had a stroke of genius while in the shower one morning. Today, I’m going to talk about how I supported partial functions in my toy programming language.

First let’s look at what a partial function looks like in my language. I took an F# approach where any function whose argument count is less than the declared count becomes a new function (even though F# functions are curried by default but mine are not). For example, in ML type notation you could have a function of type

'a -> 'b -> 'c 

Which means that it takes something of type a and type b as arguments, and returns a type c. If we pass this function only a 'a then it’ll return … Read more


Tech talk: Service stack

Today’s tech talk the team and I talked about ServiceStack. I’ve heard a lot of hype about it but never really understood what it did or was about. Today, unfortunately, didn’t really clear any of that up.

We watched the ServiceStack powerpoint on their site and went to their github to look at the examples. What I got out of all of that is that ServiceStack is trying to simplify the creation of service oriented architectures (SOA) by providing a complete stack architecture for you to use (an ORM, backing cache/NoSql, routes, serialization, etc).

The confusion, however, lays in the fact that most other solutions are doing nearly the same thing. MVC has routes and web-api’s with GET/POST/PUT/DELETE methods. WCF exposes transport independent RPC. Node.js has routes with auto fill parameters. Everyone is using JSON serialization. Redis is common as a caching layer. A bunch of ORM’s already exist … Read more

Fixing “Calling LoadLibraryEx on ISAPI filter v4.0.30319 aspnet_filter.dll failed”

Calling LoadLibraryEx on ISAPI filter "C:\Windows\Microsoft.NET\Framework\v4.0.30319\\aspnet_filter.dll" failed

I ran into this adding a new site to my 64 bit machine, and because I haven’t had my morning coffee, I forgot to set “enable 32 bit applications” in the app pool.

If your code is built for 32 bit only (maybe you use mixed mode dll’s somewhere or call into native and can’t be 64 bit for whatever reason), make sure the app pool of your application is set to 32 bit mode. Otherwise, you get the very descriptive error shown above.

iis32bit.Read more


Adding static typing and scope references, part 3: solving forward references

In an earlier post I gave a brief overview of the scope builder and its jobs. There I mentioned that supporting forward references required some extra work. In this post I’ll talk more about how I solved forward references.

Here is what I mean by forward references. func is declared after it’s being referenced

string item = func();

string func(){
    return "yes";

print item;

If we iterate over the program only once from the top down using our visitor pattern based scope builder, when we try and resolve the func method invocation symbol we’ll get an error (it hasn’t been defined yet).

Remember that when things are declared (such as methods, classes, or variables) we create a symbol (with a type) in the current scope tree. Later, when we are referencing them, we need to resolve that symbol. Resolution both validates that we can properly see the symbol and … Read more


Just another brainfuck interpreter


Honestly, why not?

The entry point

Not much to tell:

static void Main(string[] args)
    var parser = new Parser("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");

    var instructions = parser.Instructions;

    var interpreter = new Interpreter(instructions);


The container classes

Some data classes and enums:

public enum Tokens

    public class Instruction
        public Tokens Token { get; set; }

        public override string ToString()
            return Token.ToString();

    class While : Instruction
        public While()
            Token = Tokens.While; 

        public List<Instruction> Instructions { get; set; } 

A helper function

A function to translate a character token into a known token

private Tokens GetToken(char input)
    switch (input)
        case '+':
            return Tokens.Incr;
        case '-':
            return Tokens.Decr;;
        case '<':
            return Tokens.MoveBack;
        case '>':
            return Tokens.MoveFwd;
        case '.':
            return Tokens.Print;
        case ',':
            return Tokens.Input;
        case '[':
            return Tokens.WhileStart;
        case ']':
            return Tokens.WhileEnd;
Read more

, ,

Add scheduled task and run even if on battery power

Just wanted to share a little helpful snippet in case anyone needs it. To add a scheduled task and make sure it starts even when on battery power do this:

using (var taskService = new TaskService())
    TaskDefinition task = taskService.NewTask();

    var action = new ExecAction
        Path = "test.exe",
        Arguments = "",
        WorkingDirectory = ""

    task.RegistrationInfo.Description = "Test";

    var trigger = new TimeTrigger(DateTime.Now);
    trigger.Repetition.Interval = TimeSpan.FromMinutes(5);


    task.Settings.DisallowStartIfOnBatteries = false;
    task.Settings.StopIfGoingOnBatteries = false;

    // Register the task in the root folder
    taskService.RootFolder.RegisterTaskDefinition("test", task, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount, null);

TaskService is part of Microsoft.Win32.TaskScheduler.

By default when you create a new task DisallowStartIfOnBatteries and StartIfGoingOnBatteries are true, so that’s something to keep in mind if you are writing code that can be deployed on a laptop and you must have your scheduled task continue to run.

Quick side note, I personally think negative property names are … Read more


Previous Posts