Computer
When FarmVille == Productivity
by Chris on Jan.27, 2010, under C#, Computer
Update 2010-02-08: Jonathan Pryor has merged many of my extension methods into Cadenza. I’d strongly suggest checking it out.
It’s no secret to my friends that I love to program… even more so as I’ve been developing a FarmVille client in C# and having them test it. (As much as you might hate FarmVille, you must agree that there’s a certain awesome factor in LINQ-to-FarmVille: service.Plow(from i in service.World.Objects.OfType<Plot>() where i.State == "fallow" || i.State == "withered" select i)
Well, among this project and others I consistently find myself writing the same code over and over. I know of many programmers who have developed personal toolkits for the languages they use frequently, but for some reason I’ve been programming for about 13-15 years now and haven’t ever built my own library. This application gave me an excuse to do so, and so I’ve started on the Cdh.Toolkit suite of libraries.
Here is a summary of the classes available:
- Cdh.Toolkit.Collections: Some useful collection types, all designed to be derived.
- ReadOnlyCollection<T>, ReadOnlyDictionary<TKey, TValue>, and ReadOnlyList<T>: Wrappers around the corresponding interface types ICollection<T>, IDictionary<TKey, TValue>, and IList<T>, throwing exceptions on all write attempts. While there is a ReadOnlyCollection<T> as part of the .NET framework, it is not designed to be derived, and the other two classes do not have a counterpart at all.
- SynchronizedCollection<T>, SynchronizedDictionary<TKey, TValue>, and SynchronizedList<T>: Wrappers around the corresponding interfaces. All accesses are synchronized against a ReaderWriterLockSlim, allowing for multiple concurrent read operations. The enumeration behavior can be specified as either lock, which holds a read lock for the duration of the enumeration, or copy, which creates a copy of the collection and enumerates it instead.
- ObservableCollection<T>: A collection that fires events when modified. ObservableDictionary and ObservableList are currently not provided, due to some implementation complexities. However, the interfaces IObservableCollection<T>, IObservableDictionary<TKey, TValue>, and IObservableList<T> and some EventArgs classes are provided to allow developers to implement their own observable collections easily.
- ObservableHashSet<T>: An observable and API-compatible wrapper around HashSet<T>.
- ReadOnlyObservableCollection<T>, ReadOnlyObservableDictionary<TKey, TValue>, and ReadOnlyObservableList<T>: Wrappers around the IObservable* interfaces mentioned above. Events from the wrapped collections are forwarded. This allows one to have a read only observable collection without sacrificing the IObservable* interface, which would happen if such a collection were wrapped in one of the normal read only classes listed above.
- Cdh.Toolkit.Extensions: Extension libraries designed to ease the use of many classes in the .NET framework.
- Collections: Extensions specific to collection classes.
- TValue IDictionary<TKey, TValue>.GetOrDefault(TKey key): Returns default(TValue) if the key is not present in the dictionary.
- TValue IDictionary<TKey, TValue>.GetOrValue(TKey key, TValue fallback): Returns fallback if the key is not present in the dictionary.
- ComponentModel: Extensions specific to the System.ComponentModel namespace.
- void ISynchronizeInvoke.AutoInvoke(Action action): Executes the action delegate on the ISynchronizeInvoke object if required, otherwise does so on the current thread.
- object ISynchronizeInvoke.AutoInvoke(Delegate method, params object[] args): Executes the delegate on the ISynchronizeInvoke object if required, otherwise does so on the current thread, and returns the return value of that method in either case.
- AsyncCallback AsyncCallback.Invoked(ISynchronizeInvoke obj): Returns a wrapper around the AsyncCallback delegate that will invoke it using the AutoInvoke extension above. Useful for async callbacks that need to operate on a Winforms GUI.
- Enumerable: Extensions to enumerable objects.
- IEnumerable<T> IEnumerable<T?>.NotNull() where T : struct: Returns all values from the non-null nullable objects in the sequence.
- void IEnumerable<T>.Walk(): Enumerates the sequence, discarding all values obtained. Useful as an alternative to .ToList() when you need to make sure that a query executes, but do not need to use the result.
- void IEnumerable<T>.CopyInto(IList<T> list): Copies a sequence into a list.
- Events: Extensions that make writing event logic easier. All of these extensions return if the event handler in question is null, making event-firing code simpler and easier to read.
- void EventHandler.Fire(object sender): Uses EventArgs.Empty as the event arguments.
- void EventHandler.Fire(object sender, EventArgs args)
- void EventHandler.Fire(object sender, Func<EventArgs> argsFactory): Calls the factory function only if the event handler is not null. Useful when construction of the event arguments can take a long time.
- void EventHandler<T>.Fire(object sender, T args)
- void EventHandler<T>.Fire(object sender, Func<T> argsFactory): Calls the factory function only if the event handler is not null. Useful when construction of the event arguments can take a long time.
- ReaderWriterLockSlim: Allows these kind of locks to be used in a using() block, which makes code easier to read and maintain. They will also return a no-op IDisposable if a compatible lock is already held by the current thread, which makes non-recursive lock objects simpler to code with. (The return type is actually a value type that implements IDisposable, which means that usage of these methods does not incur any object allocation overhead.)
- IDisposable ReaderWriterLockSlim.Read(): Returns an IDisposable that will release the read lock when disposed. This method returns a no-op IDisposable instead if the current thread already holds a read, upgradeable read, or write lock.
- IDisposable ReaderWriterLockSlim.UpgradeableRead(): Returns an IDisposable that will release the upgradeable read lock when disposed. This method returns a no-op IDisposable instead if the current thread already holds an upgradeable read or write lock.
- IDisposable ReaderWriterLockSlim.Write(): Returns an IDisposable that will release the write lock when disposed. This method returns a no-op IDisposable instead if the current thread already holds a write lock.
- Reflection
- T ICustomAttributeProvider.GetCustomAttribute<T>(bool inherit) where T : Attribute: Returns a typed attribute, or null if there is no attribute of type T.
- IEnumerable<T> ICustomAttributeProvider.GetCustomAttributes<T>(bool inherit) where T : Attribute: Returns a sequence of attributes of type T present on the attribute provider.
- Reflection.Emit
- void ILGenerator.EmitTypeOf(Type type): Emits the IL sequence that will leave the same Type object on the execution stack.
The amount of code is slim, but I’ve found at least one of the classes or extensions invaluable in every project I’ve worked on since starting the toolkit. It’s an interesting case where coding for a game actually winds up improving my productivity working on other software too.
Eventually these libraries will be released under the MIT license, so stay tuned for another blog post with a link to the Git repository.
(And yes, the above list will be converted into real documentation. Someday.)
- Collections: Extensions specific to collection classes.
Covariant IEnumerables, pre-.NET-4.0
by Chris on Nov.05, 2009, under C#, Computer
One of the nice things that .NET 3.5 gives us is LINQ, which gives new life to the often-neglected IEnumerable generic interface. Sequence processing is now a first-class citizen in the C# world, and this is a good thing. However, it can be very tricky to design a usable API around enumerables. Today I present my solution to an annoying (but not showstopping) hurdle.
Consider the case where you have several types implementing an interface. In my case, these types all have a common ancestor, but this is beside the point. We’ll call the interface IFoo, and the classes implementing this interface ThingOne, ThingTwo, and ThingThree.
If I have a method that acts on a series of IFoo objects, it is tempting to accept IEnumerable<IFoo> as an argument. It makes sense, right? Well, sort of. Your users will not like this, because IEnumerable<ThingOne>, IEnumerable<ThingTwo>, and IEnumerable<ThingThree> are not convertible to IEnumerable<IFoo>. While it’s not too annoying, your users will have to cope by invoking Cast<IFoo>() on their enumerables for them to work with your API. This not only adds code overhead (read: more code to maintain) but a minor amount of CPU and memory overhead to create an object that is going to cast objects to an interface that they explicitly implement.
The solution is rather simple, but not very obvious at first glance. Instead of using the signature void OperateOnFoos(IEnumerable<IFoo> foos), use this instead: void OperateOnFoos<T>(IEnumerable<T> foos) where T : IFoo. It is a simple change, and the method will work exactly the same as before, except your users will no longer be required to cast their enumerables to IFoo.
This technique applies just as well to situations where you take an enumerable to a class that is designed to be subclassed.
Now depending on how generics are implemented in your runtime of choice, you’re still probably going to see a small memory hit for each different T you use when calling this method. But it’s not likely to be anywhere near the cost of creating a bunch of cast-enumerables that you really could do without. And that aside, the convenience of not having to Cast<IFoo>() enumerables is totally worth changing one line of code.
.NET 4.0 will likely render this mechanism obsolete with the introduction of covariant interfaces, but in the meantime let’s all do something nice for our users!
Yet another monolithic update
by Chris on Sep.02, 2009, under Computer, Games, OpenVP, Personal
I need to get into the habit of blogging more often. I haven’t even been twittering much lately…
You’ve probably noticed the visual update to my blog by now. I got tired of the default Wordpress theme. I had to tweak this one a bit to get it to behave the way I want, but overall it’s pretty nice. A few weeks ago I added the live chat widget as well, which so far has attracted comments from exactly two people. Come on, I know there’s more of you out there!
My new job is going well. The current project I’m working on is a migration script to fix some datetimes that may have been incorrectly converted to GMT. If you’ve done any programming around timezone conversions, you’ll know it’s a blast! … Ok, it’s not that bad. It’s actually kind of fun, in a weird way.
On the “my projects” front, I’ve converted the OpenVP Subversion repository to two separate Git repositories, and created a third for the metadata pipeline project. Check them out on Gitorious.
I’ve started playing Black & White on my lunch break. The voice acting is a little iffy, but the gameplay is good after you figure out what you’re doing. (Which, ironically, doesn’t happen until you leave the tutorial island.) Oh, and I got the Metroid Prime Trilogy for Wii. I’ve only played the first on GameCube, but absolutely loved it. Can’t wait to tackle the two sequels.
That’s all for now.
Splitting a Git repository
by Chris on Jul.09, 2009, under Computer, Programming
First some backstory…
I had a public and a private Subversion repository on my web server, and when I started a new project I’d import it into one of them. This is nice because I get versioning and history, plus I get implicit synchronization between my various development boxen.
It’s not unusual to have one monolithic Subversion repository for many different projects, mainly because setting up a Subversion repository can take a small bit of work, especially if you are serving it from HTTP. However, Git makes it so easy to create new repositories that there is no excuse not to create per-project repositories, not to mention that you should anyway since Git doesn’t support checking out a subdirectory of a repository. You simply can’t use a monolithic Git repository because you have to clone the whole big tree, even if you only plan on working on one subdirectory.
Since Git is so much more awesome, I plan on converting my Subversion repositories over. But what do I do with the multi-project ones? There’s no built-in mechanism for pulling out just one directory, with history, into a new repository. So I wrote one.
The usage is git-pluck src-repo dest-repo path/to/directory. The script copies the repository at src-repo to a new directory, dest-repo, and then does its magic. It rewrites all of the commits so that all of the files in path/to/directory are moved into the root of the repository, and everything else is deleted. Commits that do not introduce changes to that directory are removed from the history, potentially including the first commit to the repository. Finally, the reflogs and backups are removed and the repository is compacted, leaving you with a small, single-project repository.
This script was written and tested using Git 1.5.6.5. Feedback is welcome!
Comcast modem fun
by Chris on May.15, 2009, under Computer, Linux
Well, the Comcast guy showed up today and dropped off the modem self-installation kit. About two or three hours later and it still wasn’t working quite right.
Here is my setup. The modem is plugged into eth0 on a Linux box, and eth1 runs to a switch. Traffic routed out eth0 is masqueraded (also known as NATed). If the modem and Linux box are turned on then everything works fine. But if I bring eth0 down and back up, then some odd behavior begins. All traffic that originates on the Linux box behaves normally — I can use elinks to browse the web and irssi to chat on IRC without any problems. But any traffic that is masqueraded, meaning that it comes from another computer on my network, does not behave normally. The connection establishes and works for a split second and then is silent.
I’d suspect a routing problem on the Linux box, but tcpdump there confirms everything is working as it should. However, ifconfig reports RX errors on eth0. This makes no sense — traffic originating from the LAN side of the router box triggers receive errors on eth0. Unless I reboot the router and the modem. I have not observed this behavior with any other ISP or uplink switch.
Anyone have any theories?
Git and Banshee.OpenVP fun
by Chris on May.07, 2009, under Banshee, C#, Computer, OpenVP, Programming
Well it’s hacking season again. With GNOME’s switch from Subversion to Git complete, which means Banshee now uses Git too, it gave me an excuse to finally learn it. This was not fun. But having toughed it out, I can definitely say that I love it.
Now that Banshee is using Git, Aaron is starting work on a branch off of the 1.4 series to incorporate my visualization patch. Wielding my new Git tool belt, I was off and hacking. Taking Gabriel’s branch allowing replacement of source widgets, I rebased that from master to stable-vis, fixed the merge conflicts, and started hacking away at Banshee.OpenVP. Unfortunately, not all the pieces I needed were there yet. So I added them and pushed them up to Gitorious. Neat.
Now Banshee.OpenVP looks like this:
Résumé and availability
by Chris on Apr.27, 2009, under Computer, Personal
I will be graduating in two weeks from Anderson University with a B.A. in Computer Science and Mathematics. I’m actively looking for employment in the Anderson/Muncie/Indianapolis, Indiana area. I’ve had several prospects for some months but nothing has come through yet. If you know of any opportunities, or are looking for a dedicated coder familiar with many languages (C, C#, PHP, just to name a few) and both Linux and Windows environments (Linux preferred), drop me a line. My résumé is available in two formats: PDF and HTML. Feel free to ask any questions about my experience or skills. Looking forward to hearing from you!
Update: I’ve disabled comments since I’d rather people email me about opportunities than leave a comment. My email address is on both versions of my résumé.
JavaScript appreciation and more
by Chris on Mar.06, 2009, under Computer, JavaScript, Personal, Programming
I’ve been up to a lot of little things recently but haven’t undertaken any projects big enough to warrant a whole fancy blog post. I figured I might as well summarize what I’ve been up to.
I’m doing a project at school that improves the experience of on-campus tutors and their clients. They’d been using Moodle workshops to allow clients to submit content to tutors, and recording hours manually on timecards. Moodle will still be involved, but the tutors will now interact primarily with a web application I’ve been coding that will track their hours for them, as well as fulfill some clerical roles, such as preventing two tutors from working on the same paper. (Previously this was done more or less manually by updating the workshop submission title. Not a terribly fun way to track that kind of stuff.)
This project has me up to my neck in JavaScript, a language I’ve long held in contempt. However, after reading up on some patterns and watching a talk or two my mind has been completely changed. In fact, I enjoy coding in JavaScript now. I enjoy it a lot. When you know what you are doing (and what to avoid) all the frustration and general icky feelings associated with working in the language disappear. What’s left is an incredibly pure, lightning-fast web application. A maintainable one too. Who knew JavaScript could do that?
Some other semi-random facts:
- I’m getting married in 91 days. (See that counter in the right column? Yup, that one. If you’ve been wondering what that’s counting down to, now you know.)
- I’ve recently revived the RTS gaming genre on my system by reinstalling Age of Empires 3. I don’t recall why I stopped playing, but I shouldn’t have.
- In case anyone wonders why I haven’t been on WoW for a while, it’s because I let my subscription expire. That was over six months ago, I think. Honestly I have not missed it. There are more fun games out there, and they don’t require a monthly fee. Team Fortress 2 is an especially good option if you like class-based games and first-person shooters.
That’s all for now, I guess. Stay tuned for some more developments on Banshee.OpenVP in the coming weeks.
New new display
by Chris on Jan.12, 2009, under Computer, Personal
I got the replacement for my defective laptop display on Saturday and got around to installing it last night. So far everything looks good. There are no defective pixels as far as I can tell and, as a bonus, it’s a matte display instead of the glossy one that came with my laptop. Woot!

