Over the event horizon, toward the singularity

c# project dependancy visualization

Posted on Dec 16, 2007 dotnet programming

Have you ever wanted a way to quickly visualize the overall architecture of a c# solution in the form of some sort of pretty diagram?

Well I had that thought yesterday, and figured that there must be some free tool out there that can take a solution file or directory and build a graph of all the underlying project files and dependancies. However to my dismay I found that there were no such tools (or they were commercial products or were completely over the top for what I wanted) so I decided to roll my own :)

The end result is an app which builds a graph of all the projects and dependancies in a directory (plus its subdirectories) as well as the relative sizes of those projects. In addition the graph is fully moveable by the mouse and all the nodes and points behave with realistic physics (I reused my Tarantula physics engine developed a while back)


The app is written in c# 2.0 and is available in binary or source code form (under the conditions of the MIT license)

Download the source here

Mapping boost::signals to .net events

Posted on Nov 24, 2007 cplusplus programming

A while back I blogged about wrapping native c++ classes inside managed .net classes using c++/cli, and while that blog detailed wrapping up a class with methods and properties I did not go over how to map across boost::signal’s to the .net event model.

Below we have a native c++ class which has the ability to copy files and notify listening classes of it’s progress in doing so.

Unmanaged Class Interface

class FileCopier

	typedef struct {
		long BytesCount;
		long BytesCopied;
		std::string CurrentFile;
	} CopyProgressEvent;

	typedef boost::signal<void (CopyProgressEvent)>

	CopyProgressEventHandler;//progress callback signature

	add a listener to copy progress events
	void AddCopyProgressListener(CopyProgressEventHandler::slot_type listener);

	CopyProgressEventHandler _handler;


The AddCopyProgressListener class accepts a pointer to a suitable callback function that conforms to the signature void(CopyProgressEvent) and adds that callback to the event handler

which can be used to notify all listeners of the event. All well and good so now to wrap it up in .net goodness using c++/cli. We’ll be using the managed wrapper class I wrote in a previous blog entry (here) as the basis for the file copier wrapper.

The full interface for the wrapper class is shown below, in order for this to work we have to duplicate the copyProgressEvent in a managed class and supply our own delegate class and event for managed listeners to subscribe to. The notifyListeners method is what takes an unmanaged copyProgress event, wraps it up in its managed equivalent and passes it off to the event handler

Managed Class Interface

public ref class
ManagedCopyProgressEvent {

	long BytesCount;
	long BytesCopied;
	System::String^ CurrentFile;

public ref class ManagedFileCopier:
	delegate void CopyProgressEventHandler(ManagedCopyProgressEvent^ args);
	event CopyProgressEventHandler^ OnCopyProgress;


public private:
	void NotifyListeners(CopyProgressEvent args);

Okay, so the interface makes sense to any .net classes wanting to subscribe to the copyprogress events, but how are we going to do the behind the scenes routing of the boost::signal event such that notifyListeners gets called at the appropriate times? If we were working with native c++ classes we can happily used boost::bind to turn the notfyListeners member function into a suitable callback for the signals event, however because NotifyListeners is part of a managed class, this approach doesn’t work so we have to take a slightly more roundabout approach.

The notifier proxy

This is where the function below comes in. Its purpose is to provide a valid function for boost::bind to use as a callback, but also to keep a reference to our managed class so that NotifyListeners can be called when a boost::signals event is fired (This should hopefully make more sense when we actually hook all these pieces up in the managed classes constructor)

void NotifyProxy(gcroot<ManagedFileCopier ^> this_,CopyProgressEvent args) 

Putting it all together

The implementation of the constructor is where the notifier proxy gets hooked up to the unmanaged boost signals event. Using boost::bind we use the notifyProxy function and the instance of the managed class to create a callback for the unmanaged boost::signal.

ManagedFileCopier::ManagedFileCopier() : ManagedEntityBase(new FileCopier(),true) 

The implementation of the NotifyListeners method is pretty straightforward, we create a new instance of a managedCopyProgressEvent then copy the unmanagd attributes over before passing the object as an argument to the .net OnCopyProgress event.

void ManagedFileCopier::NotifyListeners(CopyProgressEvent args)
	ManagedCopyProgressEvent^ mArgs = gcnew CopyProgressEvent();
	mArgs->BytesCopied = args.BytesCopied;
	mArgs->BytesCount = args.BytesCount;

So there you have it! thats how you can route events from the boost::signals library though to managed .net code. Below is an example of some c# code using the managed class we’ve written.

ManagedFileCopier fc = new ManagedFileCopier();

fc.OnCopyProgress += new ManagedFileCopier.CopyProgressEventHandler(OnCopyProgress);

void OnCopyProgress(ManagedCopyProgressEvent args)

Film extravaganza

Posted on Nov 21, 2007

I don’t just write code you know, In fact from time to time I have been known to take camera in hand and record what one could describe as short films, heres a few I’ve done in the past which I’ve finally got round to uploading to youtube. Enjoy.

The prophet

Map of your head

Interrogation Film II: Hertzogs revenge - Official Trailer

Interrogation Film II: Hertzogs revenge - Opening chase scene

The trip to c++/cli with unexpected results

Posted on Sep 16, 2007 cplusplus programming

I recently had reason to want a virtual file system (i.e a wrapper around the physical file system such that various archive files were enumerated as if they were folders for easy navigation and reading of those files) for use in a C# application. Fortunately I had a piece of code which I had already written… except for one small probelm, the entire thing was written in unmanaged c++.

So armed with the meagre knowledge that there was some way to wrap up native assemblies using some manner of managed c++ ( the latest iteration of which is named c++/cli), I headed off into the scary world of .net/native interop to try and save myself a rewrite of all my code.

c++/cli is the only .net language capable of using managed and unmanaged code in a single assembly, so while being extremely powerful its also extremely complicated as you have a superset of both .net and unmanaged c++ features and all the issues with interoping between them all in a single language. To cut the suspense from this tale, I’ll say that I was able to wrap up my unmanaged code without (too many) problems, this included mapping across getter/setter methods as properties, boost::signal callbacks as .net delegates and events and managing the memory of my unmanaged objects within thier managed wrappers.

So without further ado, here are a few useful peices of code and patterns that I used to make wrapping unmanaged entities easier.

Pattern the first: mapping strings

While primitive types such as int’s and bools can be passed back and forth between managed and unmanaged code with no conversion, c++’s std::string and .net’s string classes need to be mapped explicitly.
Mapping to .net strings from c++ is relatively simple and can be accomplished using the code below

std::string nativeStr;
nativeStr = "hello world";
System::String^ ManagedStr =
gcnew System::String(nativeStr.c_str());

Mapping from c++ back to .NET is a little bit more complicated but can be accomplished with the function below

std::string MarshalString ( System::String^ s)
const char* chars = (const char*)
std::string os = chars;


return os;

Pattern the second, wrapping managed objects

The two classes below provide a simple means to wrap an unmanaged entity within a managed entity. The templated constructor allows you to pass an unmanaged entity to wrap up and whether the managed wrapper is responsible for freeing the memory of the unmanaged entity upon being garbage collected.

adds some useful utility methods to classes that want to
interop between managed and unmanaged code
public ref class EntityBase {
public private:
static std::string MarshalString ( System::String^ s)

const char* chars =
 (const char*)(System::Runtime::InteropServices::

std::string os = chars;

return os;

provides a means to wrap an unmanaged type inside a managed
template <typename T> public ref class ManagedEntityBase:
virtual ~ManagedEntityBase()
if (_ownsNativeEntity) {
 delete _nativeEntity;
public private://equivalent to internal in c#

property T *NativeEntity {
T *get()
 return _nativeEntity;

ManagedEntityBase(T *nativeEntity,bool ownsNativeEntity) {
_nativeEntity = nativeEntity;
_ownsNativeEntity = ownsNativeEntity;

T *_nativeEntity;
bool _ownsNativeEntity;
below is an example of how to use these classes 

<pre class="prettyprint lang-cc linenums">class UnmanagedClass {
virtual ~UnmanagedClass(){}

int Foo() {return 1;}

public ref class ManagedClass:
ManagedEntityBase<UnmanagedClass> {
ManagedEntityBase(new UnmanagedClass(),true) {}
virtual ~ManagedClass(){}

int Foo() { return NativeEntity->Foo(); }

Then after referencing the above c++/cli assembly we can access the managed wrapper in c# with the following

ManagedClass mc = new ManagedClass();
int bar = mc.Foo();

As for mapping boost::signal callbacks to .NET events and delegates, that was a little more tricky and will be the topic of another days post :)

Hasta Luevo.

Regarding silverlight, services and somesuch.

Posted on Jul 16, 2007 silverlight programming

After hearing a lot about Microsoft’s Silverlight recently (that and the possibility of loot to be had via a Silverlight coding competition at work :)), I decided to try my hand at a bit of Silverlight development. Basically the idea was to try and build a small demo app that showed off some really wacky stuff that isn’t really possible (or practical) to implement using existing web based technologies.

I pretty soon settled on the vague idea of interacting with some sort of third party web service in order to test out Silverlight’s ability to leverage existing services and visualise them in strange new ways. Once I’d decided on this I pretty quickly decided to do something with’s e-commerce API as I had had some previous experience using it. At the same time I was also fooling around with creating a game based around swarm intelligence (and since got bored of before finishing) which had me thinking about cells and networks.

Combining these two thoughts gave me the idea of writing an application which could search over Amazon’s catalogue of books and visualise the results as a group of physical nodes. The user would then be able to drill down into the nodes to find books that were similar, where similar nodes would be connected to the original node creating a visual network.

So after coming up with the idea I looked into actually implementing it and to my dismay I found that Silverlight 1.1 was designed only to work with the upcoming Visual studio Orcas, not Visual Studio 2005. However with a bit of jiggery pokery I was able to get it all running fine in Visual Studio 2005 sans the ability to debug (but my programs contain no errors anyway so that was no problem!).

The web service

Silverlight 1.1 has the ability to with asmx web services using JSON, however it (as of the alpha release) allow you to make cross domain web service calls. This meant that in order to query Amazon’s services I would have to write a proxy web service sitting on the same domain that forward the requests on to Amazon then send the results back to the Silverlight client. Though this makes accessing 3rd party services more work, it is relatively painless as there is no difference in writing a Silverlight accessible web service from a standard asmx web service apart from tagging the service class with the [ScriptService] attribute.

Rag-doll physics?

Since I was going to create a visual representation of nodes and links, I thought that the whole app would function much better if everything had a physical tactile feel to it and that the nodes would self arrange in to easily viewable formations, and that meant adding… physics. In the end I decided to model the system as a series of particles which repel one another (meaning that they would arrange themselves nicely on screen) and can optionally be connected by springs (for related nodes).
I implemented this physics model using a simplified Verlet integration scheme (sounds very elaborate but its actually quite straightforward - there’s a good article on implementing it here). This method used to be quite popular in the games industry for simulating cloth and rag-doll effects and was used in titles such as Hitman: codename 47 before the industry moved toward more advanced techniques such as inverse kinematics and constrained-rigid-body approaches.
A handy thing I found while developing the physics engine was that because Silverlight uses the same CLR as the full .net framework I could write the physics engine as a standard .net 2.0 class library and test it using a simple Winforms client (as I couldn’t do any debugging with Silverlight) then when I was happy with it, I could import it straight into my Silverlight solution, and after changing some references from the standard .net assemblies to the silverlight assemblies it ran fine.

Silverlight client

After implementing the web service back-end and the physics model it was time to hook it all up with some Silverlight eye-candy. Due to the fact the I was working with an alpha release, there is very little in the way of user controls available. This means that unfortunately many standard components such as text boxes and buttons have to be made from scratch. In saying this though, Dave Relyea has produced a controls framework (found here) containing many of these standard controls and though I didn’t use his framework I did use some elements of his text-box control when developing my own.

While most of the effects found in WPF are present in Silverlight there are still a few omissions which I found to be a bit annoying, in particular the bitmap effects such as blur are not included in Silverlight which meant that I couldn’t add in all the effects I had originally planned, hopefully these effects will be added in for the final release.

On the plus side, I was impressed by Silverlight’s rendering speed even at this early stage in its development, as I went out of my way to fill the whole screen up with as many shiny gradients and subtle animations as possible (in addition to the physics modelling) and it still ran along at a decent clip and was responsive to user input even on lower spec machines.


Not just eye candy

In addition to the draggable books and physics already in-place I wanted to try and implement something that would at least hint at the fact the having all this rich client functionality allows developers to create experiences that are not only more attractive, but also more responsive and in some ways fundamentally different to what is possible using traditional web technologies. My attempt at this was to implement some gesture based controls into the application such that if you shook a book that was connected to another book it would break the link between them, this made it much easier to keep books you wanted on screen and delete unwanted items in a way that felt natural given the physical representation of the books on-screen. While I didn’t have the opportunity to pursue further gesture based controls, It certainly would have been possible to remove almost all the buttons from the GUI and have an entirely gesture based interface.


While its very debatable whether my application is useful rather than just fun to play around with, I think it does illustrate the point that Silverlight has a lot of potential to create some very interesting and powerful experiences on the web, and while there are certainly some issues present in the current releases, I can only see it getting better from here.

If you want to check it out my app, I’ve got a demo here. If you want to take a look at the source code I’ve got a copy here (updated to run with Silverlight)

Latest tweet

News Archive