There are a bunch of samples in the code base, which should help.
Also, I think there are a few plugins, which do something similar (from a code perspective).