Programming
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!
Cdh.SimpleRpc
by Chris on Oct.15, 2009, under C#
I’ve got this idea to code some game servers for a series of cooperative games my brother and I used to play as kids. I get similar ideas all the time… how about a game server for this card game or that board game? The problem I run into is pretty much always exactly the same: what communication protocol do I use?
I decided on a list of criteria that this protocol, whatever it is, must meet:
- It must be portable across programming languages and runtimes. If somebody else wants to write a better client using a different environment, that should be straightforward — perhaps not necessarily easy, but at least straightforward.
- It must be relatively efficient on the wire. Protocol chatter should be minimal in comparison to the data being exchanged.
- The object library should be simple and elegant to code against. When writing my game, the last thing I want to worry about is silly protocol details. Just get my message to the other computer please.
And here are the existing protocols I considered:
- .NET remoting. Since I code most in C# these days, it seemed like a logical choice. But it very blatantly breaks criterion 1 when using the binary formatter, and breaks both 1 and 2 when using the SOAP formatter.
- SOAP web service. Criterion 3 is satisfied, until you get to session persistence details. Criterion 1 is satisfied, and criterion 2… not so much.
- XML-RPC. Criterion 1 is met, and 2 is somewhat met. But criterion 3 is not — XML-RPC does not define any mechanism for dealing with persistent sessions. I would have to spend time writing a session manager with expiration and whatnot. No thanks.
And I’m sure I looked at others. The point is, for something as simple as message-passing between a game client and server, there doesn’t appear to be much out there that satisfies my requirements. And this is something I’ve come back to frequently.
Well, after several years of mulling the problem over in my subconscious, I knuckled down and coded. I have a usable library after two days of development. (And we’re talking maybe a few hours per day.) Written in C#, it allows any CIL-based language to write simple message-based client/server programs in very small amounts of code. For a quick example, let’s create a server that will convert strings to uppercase, with tracing back to the client.
First, we need to create an interface library so that the client and server know what each other’s methods are:
using System;
using Cdh.SimpleRpc;
namespace ServiceTest.Interfaces {
public interface IServer {
[RpcMethod] string ToUppercase(string str);
}
public interface IClient {
[RpcMethod] void Trace(string message);
}
}
Now, here is the client:
using System;
using System.IO;
using Cdh.SimpleRpc;
using ServiceTest.Interfaces;
namespace ServiceTest.Client {
public class MainClass {
public static void Main() {
Stream serverStream = ConnectToServer();
var service = new RpcService<IClient, IServer>(new Client(), serverStream);
new Thread(delegate { while(service.Read()); }).Start();
IServer server = service.RemoteServerProxy;
Console.WriteLine("ToUppercase result: " + server.ToUppercase("this is a test"));
serverStream.Close();
}
private Stream ConnectToServer() {
// Here is your code to connect to the server endpoint.
}
}
internal class Client : IClient {
public void Trace(string message) {
Console.WriteLine("Server trace: " + message);
}
}
}
Note that the RpcService object generates a typed object that will transparently proxy calls to the remote service. The server program is almost as simple:
using System;
using System.IO;
using Cdh.SimpleRpc;
using ServiceTest.Interfaces;
namespace ServiceTest.Server {
public class MainClass {
public static void Main() {
Stream clientStream = AcceptConnection();
Server server = new Server();
var service = new RpcService<IServer, IClient>(server, clientStream);
server.client = service.RemoteServerProxy;
while(service.Read());
clientStream.Close();
}
private Stream AcceptConnection() {
// Here is your code to accept a client connection.
}
}
internal class Server : IServer {
public IClient client;
public string ToUppercase(string str) {
client.Trace("Entering ToUppercase");
str = str.ToUpper();
client.Trace("Leaving ToUppercase");
return str;
}
}
}
Ta-da. Some closing notes about this library:
- It should be completely thread-safe, and will allow you to place calls using the proxy objects from multiple threads. The calls will block until a response is returned from the remote service.
- Yes, you can throw exceptions in a service method, and yes, it will cause an exception to be thrown remotely from the proxy object.
- In the future it may be possible to flag service methods that return void as “no response” calls, which will cause the proxy call to return immediately. Of course, you will not be notified if an exception is thrown remotely.
- This API doesn’t do any complex serialization, and will only operate on the primitive types, excluding IntPtr. It will probably allow transmission of arrays at some point, and perhaps allow custom objects too.
Looking back on the list of criteria, this library, even in the early stages of development, easily meets all three. I’ll be hacking on it some more I’m sure, and may even publish the Git repository somewhere, when I’m confident that the code doesn’t totally suck.
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!
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:
The new Gazebo: a Gtk# interface to FICS
by Chris on Apr.17, 2009, under C#, Chess, Linux
I’ve abandoned my idea of creating an AJAX interface for the time being. It is a cool idea but I think I can do much better by writing a proper application.
The Linux FICS interface scene is rather weak. eboard is about the best there is in terms of usability, and it has its share of problems. xboard is there for the minimalists who want their interface to provide a chess board only. When compared with the powerful and extensible interfaces available for Windows it’s rather a shame there’s nothing similar for Linux.
So I’ve decided to take the name I was going to use for my web interface and apply it to a new Linux interface. Building on Mono.Addins, I’ve already got an interface that can be extended in several key ways. Addins can, for example, provide new text highlighting classes or classes that can manipulate the console text buffer in interesting ways.
Using a tip from jonp in #mono, I have now come up with an extensible preferences system that does not suck, based on XLinq. Addins can simply subclass PreferenceContainer, slap on a few attributes, and they have an easy-to-use set of strongly typed preferences that get automatically serialized to XML. Right now only the basic primitive types and strings are supported, but this will be extended later to include things like arrays, lists, and XLinq objects. Thanks to Mono.Addins and some more support classes I wrote, addins can also provide Gtk# widgets that get embedded into the application preferences window. By writing very little code, addin authors can persist their settings and provide the user with a convenient way to change them.
I’m still lacking a chess board though. If anyone likes writing custom widgets and feels comfortable working on this project let me know. The sources will be made public in the coming weeks after I’ve had a chance to polish them and set consistent style guidelines.
Gazebo: An AJAX interface to FICS
by Chris on Mar.23, 2009, under Chess, JavaScript, Web
I’ve been getting back into chess recently, and my favorite online community is the Free Internet Chess Server (FICS). There are a wealth of free and open interfaces available for download, but they all have one thing in common: you have to download them. At my workplace this is a no-no, but over my lunch break it would be nice to get in a few games. If I forget my laptop then I have no way to play.
Enter Gazebo. I started this project last Friday night, so it’s only been about two days. Still, what I have right now is rather impressive for that amount of time. At face value, the current version is not very representative of the time that’s gone into the project so far, and for a very good reason.
The HTTP protocol used by web servers was not engineered around the idea that you’d establish a long-lasting connection with the server. It’s better suited for quick request-response cycles. Because of this, the PHP web service has no good way to maintain a connection to FICS.
The solution I came up with for this problem is simple, yet very involved. A daemon script (yes, written in PHP…) listens on a UNIX socket for connections from the PHP web service script. If a new FICS session is requested, it creates a new session and returns some authentication parameters to the web service. On every request to the service, another connection to the daemon is made over the UNIX socket, the session attached to with the authentication parameters, and some action taken, like “write this to the network socket” or “tell me when you get new data from the network socket” or even “close the network socket and destroy the session.” The daemon essentially acts as a super-proxy that persists the network sockets and enables access to all of them from one UNIX socket.
Yes, it’s kinda ugly. But it also works incredibly well. There is still some tuning to be done, but behold the awesomeness of what is essentially in-browser, color-coded telnet:
Issues with Crockford’s JavaScript conventions
by Chris on Mar.10, 2009, under JavaScript
I’ve been reading up on Douglas Crockford’s Code Conventions for the JavaScript Programming Language and I agree with most of them, but I definitely have a bone to pick with one of them: “All variables/functions should be declared before they are used.”
This sounds good in theory, and is probably a good programming practice. However, in JavaScript we frequently use callbacks to implement asynchronous calls, due to the fact that JavaScript is single-threaded. Code like this is common:
function BeginProcess(data) {
// process data
DoDataProcess({
'data': data,
'onComplete': EndProcess
});
}
function EndProcess() {
alert('The process is done');
}
Think AJAX in particular. This kind of thing is commonplace. However, declaring things before we use them means we have two options. We can either swap the functions around, or we can declare var EndProcess; at the top of the script. The latter reminds me too much of C, where you have to declare function prototypes ahead of time if you want to write them in any order you want. The former is just incredibly confusing. Consider how that would look:
function EndProcess() {
alert('The process is done');
}
function BeginProcess(data) {
// process data
DoDataProcess({
'data': data,
'onComplete': EndProcess
});
}
This is horrible. The natural code flow is broken. You now have to start at the last function and read it, then go up to read the next part. This is the same reason that top-posting sucks and bottom-posting makes sense. If those functions were both longer than a screen, you have to scroll to the bottom of the script, then up to the function header. Then read down to find “EndProcess” and say “what’s that?” Then scroll up to find EndHeader, then back down to read it. The human mind has not been conditioned to read this way.
Consider this quote from the linked article on top-posting:
Top-posting makes posts incomprehensible. Firstly: In normal conversations, one does not answer to something that has not yet been said. So it is unclear to reply to the top, whilst the original message is at the bottom. Secondly: In western society a book is normally read from top to bottom. Top-posting forces one to stray from this convention: Reading some at the top, skipping to the bottom to read the question, and going back to the top to continue. This annoyance increases even more than linear with the number of top-posts in the message. If someone replies to a thread and you forgot what the thread was all about, or that thread was incomplete for some reasons, it will be quite tiresome to rapidly understand what the thread was all about, due to bad posting and irrelevant text which has not been removed.
Given a suitably large enough application (like the one I am working on right now) this means that I either need about 200 var statements at the top of my program to indicate every class I am defining, and the same within each class to indicate each private function, or I have to reorder them. Both are unwieldy. One is unnecessarily verbose, while the other is horrible to read and breaks the natural flow of the code. Your initialization function winds up at the very bottom of the script, then you have to work your way up to see what is going on.
Crockford seems like a pretty intelligent guy, but I’ve yet to see any extensive code samples that show how he gets around this problem. Thoughts?
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.
Finished visualization pipeline
by Chris on Jan.21, 2009, under Banshee, C#, OpenVP
Hopefully, anyway.
I spent some time this last week (probably over 15 hours total) giving the Banshee visualization pipeline another overhaul. In the process of doing this I finally filed a bug I found in the spectrum GStreamer element that I’ve been trying to work around for a long time.
Even though Sebastian was able to fix this specific bug, another crept up, which he did fix, but it became apparent to me that using the spectrum element was the wrong approach. I won’t go into too many details, but it made disabling and re-enabling the pipeline incredibly tricky and required a buffer of spectrum slices that had to be synchronized with a mutex since it was being accessed by three threads.
Sebastian gave me some pointers on using libgstfft directly, and this has reduced the amount of code required to do spectrum analysis while making it less laggy and less of a hack.
I’m told this patch (and possibly Banshee.OpenVP) will be going into Banshee 1.6. Sweet.
Mandatory screen shot of the new code and of the new Voiceprint visualization in Banshee.OpenVP:
Update 2009-01-22: I had to revise the patch to fix a segfault caused by a race and to eliminate some timing issues with thawing synchronization. The link to the patch has been updated.


