Some time ago, I wrote about using Dropbox as a version control system. I now realise how naive  and short-sighted that thought was. At the time, it was my belief that a dropbox account could be suitable for maintaining version history, and after a fashion, it can be, because using the web client to view your files, you can see previous versions of  the files in your dropbox.

However, there are problems with this approach. Consider that you’ve changed several files, but then you realise that the changes you have made are not good enough, or just don’t work. With svn, or vss (*vomit*), you can undo-checkout to get the previous version back, with dropbox you can roll back to the previous version – one file at a time. There is no branching, no merging, no tagging. Nothing like a traditional SCM tool should have.

Dropbox is after all, essentially just a folder that is backed up “to the cloud”. If we use the right tool, we can take advantage of this properly.

Enter Git

What is Git? Well, surely you must have at least heard of Git by now? If not, I refer you to the wikipedia page about Git. Ok? You’re back?

The key aspect of Git which we can take advantage of is essentially the very nature of Git itself. Every Git clone is a full-repository, containing the full commit history and full revision tracking capability for the project, and it does not rely on network access nor a central server.

Basically, the idea is that you initialise an empty, bare repository inside your dropbox folder, and then somewhere else on your filesystem, perhaps a development folder where you store all your projects, you clone the repo from dropbox, and do all your work on that clone. Then when you call ‘git push origin master’, your changes are pushed into the dropbox repo, ready to be synced up on other computers you use.

Note: This is not a substitue for having a proper hosted Git repository, such as a project on Github, or somewhere else. However, it useful if you are working on something you aren’t ready to put into the public domain, or you haven’t yet decided to purchase an account on a private repository provider.

Setup

Setting it up is fairly simple, but, I am going to assume that you have Dropbox and a dropbox account, Git and (if you are on Windows) GitExtensions, correctly installed already.

Note: I have only tested this on Windows 7, but I wouldn’t expect it to not work on any other system. As always YMMV.

First, create a folder in your dropbox folder to house your projects, e.g. C:\Users\Stuart\Documents\My Dropbox\projects or just store it in the root of your Dropbox, it’s upto you. Don’t forget to include quotes around any path that has a space in, or else it won’t work.


Stuart@LAPTOP ~/Documents/My Dropbox/projects
$ mkdir example

Stuart@LAPTOP ~/Documents/My Dropbox/projects
$ cd example

Stuart@LAPTOP ~/Documents/My Dropboxprojects/example
$ mkdir .git

Stuart@LAPTOP ~/Documents/My Dropbox/projects/example
$ cd .git/

Stuart@LAPTOP ~/Documents/My Dropbox/projects/example/example.git
$ git init --bare
Initialized empty Git repository in c:/Users/Stuart/Documents/My Dropbox/projects/example
/example.git/

Then, in your development folder clone that repo.

Stuart@LAPTOP /c/development/examples
$ git clone -v "C:/Users/Stuart/Documents/My Dropbox/projects/example/.git"
Initialized empty Git repository in c:/development/examples/example/.git/

Stuart@LAPTOP /c/development/examples
$ cd example/

Stuart@LAPTOP /c/development/examples/example (master)
$ touch example.txt

Stuart@STUART-LAPTOP /c/development/examples/example (master)
$ git add example.txt

Stuart@LAPTOP /c/development/examples/example (master)
$ git commit -m "Added example file to initial commit"
[master e9ac78d] Added example file to initial commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 example.txt

Stuart@LAPTOP /c/development/examples/example (master)
$ git push origin master
Counting objects: 3, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 253 bytes, done.
Total 2 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (2/2), done.
To C:/Users/Stuart/Documents/My Dropbox/projects/example/.git
 1e38d4e..e9ac78d  master -> master

Dropbox will sync the files into the cloud. On your other computer, the git repo will sync, then you can clone it, and find that you have all your history for your project as you would expect.

A few months ago I wrote about writing a generic plugin loader/manager in C#, where I offered links to several articles and referenced a rather excellent book about C# which I had used to base my plugin loader on. I hadn’t really given it much thought since then, but according to Google Analytic’s, it’s one of the most hit posts on my blog. Recently I had a request to release the source code.

Now when I first wrote that post, I was hesitant to include any code, and I still am – not because I think there is something new and unique with what I’ve done – but, rather that what I have written is not terribly difficult to write. I do not mean to sound snobbish or arrogant at all, I’m just telling you how it is, all I’ve done is to do a bit of reflection on assemblies in a folder, and load instances of certain interfaces.

Anyway…

The scenario is that you want to provide a way for for 3rd parties to be able to add additional functionality to your application at run time. We need to provide a common way for 3rd parties to be able to register their new functionality into our application, in order that the user can take advantage of the exciting new feature being added to the application.

Straight away, you should be thinking to yourself: Interface!


public interface IPlugin
 {
 /// <summary>
 /// Does what ever It is.
 /// </summary>
 void Do(Action it);
 }

Anyone who now wants to create a plugin for our application must implement our IPlugin interface, as it defines the contract to which our application is bound to, in order to recognise and load plugins. Thus any assembly, that has a class which implements IPlugin is considered by our application to be a plugin which is capable of offering additional functionality.

We can now attempt to load our plugins. We need to have a class which can scan a folder for assemblies, scan those assemblies for types which implement IPlugin, and then create instances of them which our application can use. Loading the assemblies is easy:

public class PluginLoader<T>
{
 private IList<T> pluginsList = new List<T>();
 ...
}

...

public virtual IList<T> LoadPlugins()
 {
 foreach (string file in Directory.GetFiles(this.pluginFolderPath, "*.dll", SearchOption.AllDirectories))
 {
 Assembly assembly = Assembly.LoadFile(file);
 this.LoadObjects(assembly);
 }

 return this.pluginsList;
 }

We create a generic class, so we can use it with any type of plugin, and not just ones which implement IPlugin, then it’s just simple directory recursion to load all the files in the specified folder which have a file extension of .dll. The real magic happens in the LoadObjects() method.

var types = from t in assembly.GetTypes()
 where t.IsClass &&
 (t.GetInterface(typeof(T).Name) != null)
 select t;

 foreach (Type t in types)
 {
 T plugin = (T)assembly.CreateInstance(t.FullName, true);
 this.pluginsList.Add(plugin);
 }

Using LINQ, we extract all the types from the assembly which are classes, which implement the interface which is a typeof(T) – T being the type we specified when we instantiated the class. You could just as easily here specify the type should inherit from some other type, and you could also check to see if a class has some assembly level attribute.

Why would you want to do that? Well, we can use an assembly level attribute to decorate the plugin class with meta-data about the plugin, such as the author, a short description, the name of the plugin, and it’s version.

public virtual KeyValuePair<string, List<KeyValuePair<string, string>>> GetPluginInformation(Type type)
 {
 var attributeInfo = from pa in type.GetCustomAttributes(false)
 where (pa.GetType() == typeof(PluginAttribute))
 select pa;

 foreach (PluginAttribute p in attributeInfo)
 {
 data.Add(new KeyValuePair<string, string>("Author", p.Author));
 data.Add(new KeyValuePair<string, string>("Description", p.Description));
 data.Add(new KeyValuePair<string, string>("Name", p.Name));
 name = p.Name;
 data.Add(new KeyValuePair<string, string>("Type", p.Type.ToString()));
 data.Add(new KeyValuePair<string, string>("Version", p.Version));
 }

 this.attributeInformation = new KeyValuePair<string, List<KeyValuePair<string, string>>>(name, data);

 return this.attributeInformation;
 }

Or you could create a struct to use as a DTO for the plugin meta-data, it’s up to you.

I’ve removed all the comments and exception handling from the code I’ve posted purely just to save space, you’d really want to include that – especially the exception handling. But that’s really all there is to it, you might want to have a property to access the actual plugin list, or return it from a LoadPlugins method, it’s up to you.

You’ll notice I’ve made the methods virtual, you may want to use this class as a base class in another class. For instance I’ve got an additional class which inherits from my plugin loader class which does specific tasks for a particular type of plugin, and another which does different tasks for a different type of plugin.

I have recently started using psake to do some build automation at work, and I’ve found that there is not a great deal of information about how to write a build script using psake available on the internet. It isn’t all that amazingly difficult if truth be told, however there are a couple of ‘gotchas’, and I would like to share what I have learned in the hopes that it benefits someone.

If you have not heard of it, psake is a”…build automation tool written in PowerShell”, started by James Kovacs. With it, you can write build scripts, with which you can automate the build and deployment of your .NET project. Recently the version 1.00 and 2.0 0 version were released. Why two versions? Well, the 1.00 version is primarily for PowerShell 1.0, but psake 1.00 is being “retired”. This article assumes the reader is using psake 2.01 and PowerShell 2.0.

A quick note here, I should point out the primary example I based my first build script on is Ayende Rahien’s build script for Rhino Mocks.

Our first psake build script

First, I have to make two assumptions:

  1. I have to assume that you have PowerShell installed, if you are running Vista/Windows 7 then it’s installed by default, if you are on XP, then it is a manual install.
  2. You have installed the psake module into Powershell – see the release announcement linked to above for details on how to do this.
Example solution

Example solution

With those assumptions out of the way, we are going to write a build script to automate the building of a simple C# solution, containing a Windows Forms application, and two class library assemblies.

Hopefully this should be simple enough to easily follow along with what is happening in the build script, but complex enough that you can see how sophisticated your build scripts can be.

You can see that I have already taken the liberty of adding an extra file to the solution, “build.ps1″, this is our build script, with which we can command psake to do great things for us.

With our solution setup, we can now write our first build script:

properties {
 $base_dir = Resolve-Path .
 $sln_file = "$base_dir\WindowsFormsApplication.sln"
}

Task default -depends Compile

Task Compile {
 msbuild "$sln_file"
}

Open a command prompt into the directory containing the .sln file, which is where your build.ps1 script
should be, and run this command: invoke-psake .\build.ps1 -taskList Compile

psake Compile task output

psake Compile task output

You should receive some output to the console window like the above.What the script does is to work out where on the file system the script is running, and gets the path to that folder, and builds the path to the specified solution file, and runs msbuild, passing the full path to the solution file as a parameter.

The script as it is has some drawbacks though. In it’s current form, msbuild will only build the default configuration of the solution. What if we want to build a Debug version, or a Release version, or some other configuration we’ve created? Additionally, it doesn’t let us specify a directory to put the built binaries, they just get put in the default locations as specified in the projects contained in the solution – what if we want to put them in a custom location?

If we modify our build script slightly, we can introduce this functionality. Firstly, we need to specify some additional properties:

properties {
 $base_dir = Resolve-Path .
 $build_dir = "$base_dir\build"
 $sln_file = "$base_dir\WindowsFormsApplication.sln"
 $debug_dir = "$build_dir\Debug\\"
 $release_dir = "$build_dir\Release\\";
}

Notice the double backslash, msbuild requires a trailing slash when paths are specified, and it seems to require the additional backslash as well, or else it doesn’t work. With those additional properties in place, we can introduce two new tasks to our build script:

Task Clean {
 remove-item -force -recurse $debug_dir -ErrorAction SilentlyContinue
 remove-item -force -recurse $release_dir -ErrorAction SilentlyContinue
}

Task Init -depends Clean {
 new-item $debug_dir -itemType directory
 new-item $release_dir -itemType directory
}

Powershell’s easy to read syntax should make it easy to follow with what is happening now. In the Clean task, we forcefully and recursively remove any files and the folder from the specified path, and if there are any errors then they are not displayed. Now that we know that those folders are going to be cleaned and created, we can create two further tasks, where we can create Debug and Release versions of our solution:

Task Debug -depends Init {
 msbuild $sln_file "/nologo" "/t:Rebuild" "/p:Configuration=Debug" "/p:OutDir=""$debug_dir"""
}

Task Release -depends Init {
 msbuild $sln_file "/nologo" "/t:Rebuild" "/p:Configuration=Release" "/p:OutDir=""$release_dir"""

Again, the syntax here is relatively straightforward to follow along with, we execute msbuild, passing it the solution file to build, specify not to show the logo (suppressing the output of “copyright microsoft msbuild etc), tell it to execute the rebuild target and to build the Debug configuration, copying the output to the specified debug directory. Notice that that there are no spaces in the paramters that we pass to msbuild. For example, if we passed the parameters like this: “/p:Configuration=Release /p:OutDir=”"$release_dir”"”, then it would fail and we would get a msbuild parse error saying it was invalid.

Build script output for Debug task

Build script output for Debug task

Summary

In a relatively short amount of code, less than 30 lines, we have accomplished quite a lot. We can now issue the command: invoke-psake .\build.ps1 -taskList Debug, and psake will automatically clean the output folders, do a full rebuild of the Debug configuration and copy the output to a custom location on our filesystem. What’s more, the build script we have written is small, compact, easy to read, easy to maintain and easy to build/extend upon in the future.

As this is getting a bit long already, I’m going to cut things short here, however, there are some additional things that you can do as part of the build script that are very nice, such as automatically versioning the assembly before you do the full build. If you take a look at Ayende Rahien’s example from Rhino Mocks, that is covered there.

Also in the new version of psake, there are pre and post conditions and actions that you can add onto your tasks, although I haven’t had the opportunity to use them yet. I’ll try to cover those in a future blog post though.

Love him or hate him, several years ago, Jeff Atwood (of Codinghorror.com infamy and the really rather awesome StackOverflow.com) posted on his blog a recommended reading list for developers. He has since become a sort of mini internet programming celebrity. Since imitation is the greatest form of flattery, I present to you my own list of recommended reading.

Code Complete 2nd Edition

Code Complete 2nd Edition

Code Complete 2nd Edition, by Steve McConnel should be recommended reading on software engineering degrees at Universities the world over. It is a classic book about the software industry. McConnel makes the distinction between average programmers, who are happy to go through the motions of churning out (usually terrible) code and collecting their wages; and above average programmers, who continually seek to improve their base knowledge, actively improving their skills, who write solid, well designed and easily maintainable code. I think this was the book that really changed my mindset about being a programmer, about being proud of the work I do and the programs I write and maintain.

Working Effectively with Legacy Code

Working Effectively with Legacy Code

Working Effectively with Legacy Code, by Michael Feathers is another classic book, and another which I believe should be recommended reading on all University software engineering degrees. The reason I would recommended this book to any aspiring developer is that, more than likely they are going to be working with legacy code. I would say that 95% of the code I work with on a daily basis is legacy code, although that figure is slowly improving, thanks in a large part to the skills and knowledge I’ve gained from this book.  Feathers’ defines legacy code as that which does not have unit tests. I would also add that most legacy code is often poorly designed, with no comments and is usually incredibly difficult to maintain. The book is split into three parts, the first part being about how you can bring about change in your legacy code base (and legacy developers!); the second part is like an FAQ, which links techniques together in a way to address common problems; the third part is a reference of the different dependency breaking techniques that can be employed to get your legacy code under test and under control.

The Art of Unit Testing

The Art of Unit Testing

The Art of Unit Testing, by Roy Osherove, is an excellent book, full of practical advice about unit testing. The book covers everything, from why you want to unit test your code, to how you can unit test code. Even if, as I had, you have written unit tests before, then you can still learn something from this book. Indeed there were several patterns on how to approach particular problems that I’d not even considered before. Also, I had never really gotten my head around using a mock object framework as part of my unit tests, but this book explains and demonstrates in a clear and concise manner, exactly how you can leverage your mock object framework of choice for your benefit. One minor criticism that I have though, is that I feel there is a certain element of bias toward Typemock Isolator – Osherove is a chief architect at Typemock.

Holub on Patterns

Holub on Patterns

Holub on Patterns, by Allen Holub, is another excellent book, about software design.  Design patterns offer an excellent way of not re-inventing the wheel, and Holub offers an entertaining and insightful tour of the majority of the Gang of Four patterns, and offers real world scenarios in which you would use them. The book is very opinionated, but this is not a bad thing, indeed it is refreshing to read as Holub is obviously very passionate about the subject. It certainly opened my eyes into the world of design patterns, as I’m one of these who finds concrete, interesting examples an excellent tool for learning, and I’ve always found the Gang of Four book rather dry.

C# in Depth

C# in Depth

C# In Depth, by Jon Skeet is an excellent book about the C# programming language. If you want to understand something about C#, and I mean really, truly understand why the language does what it does, then I suggest that you read this book. The book is clear and straightforward, with excellent examples. Honestly if most of the people posting C# questions on stackoverflow.com read this book, then I suspect the number of questions would stop increasing at the current rate.

Like many people, I have a vanity domain name, www.stuart-grassie.co.uk. Many moons ago I used to host my blog on there, but for a variety of reasons I bought this domain and switched my blog here. So I put up a basic index page, listing a few interesting factoids about me, and what I do. When I say a “basic” page, I mean basic – black text on a white background, almost as if it was just few words typed into a text file – although there was semantically correct and valid xhtml behind it.

The other day I came across a link, 30 Examples of Extreme Minimalism in web design and it inspired me to do a small make-over on my vanity domain name site. Which I think has turned out fairly ok. Athough that isn’t the point of this blog post.

As there is not a massive amount of information (after all it’s just a “here I am, here’s some information about me, here’s how you can contact me” site, all of it is on one page. I’m using jQuery to hide everything, until the user clicks a link to see the information they want. I used jQuery UI, to use a couple of basic slide in/out effects. The actual effects are “clip” and “blind”, using “toggle” to turn them on/off. All the other content apart from the “frontpage” is hidden.

Initially, I had it working so that you could click a link, and the requested “page” would transition into view, the “frontpage” would transition out of view, then I had a <span><back</span>, which I made react to mouse clicks, using jQuery, and you could then click back to the “frontpage”.

<div id="main">
Maybe you would like to read this <a id="examplelink" href="#example">example</a> page.</div>
<div id="example">
 
This is some example content.</div>
$(document).ready(function(){
    $("#example").hide(); // Hide the example on page load
});
 
// detect when the link is clicked, and toggle the two<div>'s
$(function() {
    $("#examplelink").click(function() {
	$("#example").toggle("clip", {}, 500);
        $("#main").toggle("blind", {}, 500);
	return false;
    });
});

In my excitement to get this learned and done (I’ve never used jQuery before), I’ve lost the original code, but that’s essentially what I had, without the code to detect when the fake back button back is clicked – all it did was to run the toggle again, which returned the user to the “frontpage”. I had to to do it this way, because the browser forward/back doesn’t work.

Clearly, this is not an ideal situation, because it has broken one of the cardinal web design guidelines, by breaking the users browser, by rendering the forward/back buttons inoperable.

I’ll show you what I did next time.

Nearly every application I have ever used has produced some sort of log output, usually to record details of exactly what the application was doing when an error was encountered. To be perfectly truthful, it is not something that I have ever really given very much consideration to in either my own or work applications, there have always been more pressing things to attend to, such as meeting (unrealistic) deadlines, or implementing some interesting new feature. I’ve used log4j before in a work application, mostly because someone else had already done all the configuration.

However, the application that is currently occupying the main focus of my attention at work had (almost) no logging in it what-s0-ever, but given the nature of the application, it can be very difficult to debug exactly what is happening internally using breakpoints. Again, the nature of the application doesn’t really lend itself well to showing MessageBox’s all the over the place.

MessageBox.Show("Log message");
 
// or..
 
Console.WriteLine("Log message");

How many times have you done that, or the equivalent, in an application? If you are like me, then you’ll have done it hundreds of times, probably in the same application. It’s really quick and easy to do, and can be very useful. You just have to remember to take it out of the Release build. What a pain.

A better way

Using a proper logging library (as I have now discovered) allows you much greater freedom. Freedom to not have to (overly) worry about leaving in Log.Debug(“Some message”) all over the code. Freedom to be able to configure what is logged, where it is logged to and how it is displayed. Freedom to receive concrete data on how your application is behaving in the real world, which will enable you to find and fix bugs faster than you would have thought possible.

There are a multitude of logging libraries available:

Now, while it would probably be an interesting exercise to write a small logging library, the world doesn’t need another one, so I immediately discounted that option.

I’ve used System.Diagnostics here and there, and an ex-colleague wrote a small logging library based around using Trace and Debug, but that is getting dangerously close to writing your own logging library, so again that’s out.

The Logging application block from the Enterprise Library just seems too weighty, and too much of a pain to configure (I can probably be proved wrong though), so I discounted that as well.

The object guy’s logging library seems pretty good, but the documentation and examples kind of suck, and it doesn’t look like it’s been updated in a while, so after playing with it a little bit (and not really liking it all that much to be perfectly honest), I discounted that as well, although it does seem to have a lot of fans on Stack Overflow.

NLog has plenty of documentation, and seems pretty straightforward to use, and it too has a lot of fans on Stack Overflow, but again, it’s not been updated in a while, so I discounted that too.

Log4Net to the rescue

Log4Net is part of the Apache Logging Services project, along with Log4j, and Log4Cxx. It is a C# port of Log4j, and works amazingly well. I am not going to write about how to set it up and configure it, as others have done that already, and the documentation is excellent.

I’ve read here and there on some blogs, a few message boards and some email lists, that log4net is difficult and time consuming to set-up, and that it is hard to use. Which is nonsense, because after ten minutes (which included downloading the latest version) I had my first small test application up and running and outputting debug messages to the Output window in Visual Studio. Pretty swish indeed.  I did spend some time reading about the best ways to use log4net, and I still do, but I didn’t find the initial set-up to be inordinately difficult at all.

On the whole, I am impressed with it’s ease of use, I’m now starting to use it in my own personal projects, and it is proving to be invaluable at work.

One of my current long term hobby project is a map/world editor that I’m writing for Andy’s (work in progress) game engine. It is still in a quite rudimentary stage, however, I have gotten an important aspect of the application into a fairly mature state already, and that is the plugin system.

I don’t want to get into too much detail over things that are available via some simple searches on google, so don’t expect too much code. There are some good articles here, here and here, which delve quite deeply into this, and how to develop a plugin framework in general. I developed my plugin framework based on the code in this book, which incidentally is a very good book.

Also, in my own google searches on this subject, a lot of the articles I found are getting to be four years old, in a few instances even older. Not that this automatically makes them invalid as sources of information, it’s just that they may not reflect best practices in modern C#. (Not that I am claiming to be a Jon Skeet-like C# guru). Also, quite a few of the ones I found make use of an XML configuration file to hold a reference to the plugins. I’m not a big fan of this type of thing, I much prefer convention over configuration.

Why Generic?

I’ve written a plugin system for the Editor because I want to provide a way to make it easily extendible in the future, without having to change the core application, to enable it to perform actions that are above and beyond it’s core capabilities. Byond that basic requirement, there are a couple of other reasons to make it a generic plugin framework.

Firstly, I’ve made it generic because I wanted to make a distinction between different types of plugins, such as a type of plugin for resources, and a type of plugin which adds functionality into the application (such as tools, UI widgets etc).

Secondly, and perhaps most important (to me, anyway), is that I’ll never need to write a C# plugin framework again, for any of my personal projects. I’ve had a go at writing a plugin framework before, a few times for none-work projects and once for a project at work, and I finally realised what my problem was – reinventing the wheel each time.

The plugin framework I’ve written ensures that I don’t have to worry about this the next time one of my pet projects needs a plugin system. The Editor will in fact have two types of plugins available, one to extend the types of data sources it can load in resources from, and another to provide additional functionality, like tools.

I’m fairly pleased with the way that it has turned out, and it works quite well in practice.

Update:

I have written another post on this subject with some code examples here: http://temporalcohesion.co.uk/2009/11/02/more-on-the-generic-plugin-manager/

In part 2, I showed you an improved, although still pretty basic problem runner framework for Project Euler. I did leave out some things though, and I’m going to try and explain them now.

Firstly, I haven’t really shown how I use the Problem interface. You can see it in part 1 of this series of posts. In Eclipse, you can create a new class in a package, which should bring up the “New Java Class” dialog. Give the class a name – for Project Euler problems I’ve chosen to name them “One”, “Two”, “Three” etc. You can then add an interface that the class is to implement, click ‘Add’, and type in Problem. You can also choose some methods to stub out, tick ‘public static void main(String[] args)’. Click Ok, and you should get something like this:

package co.uk.temporalcohesion.euler.problems;
 
import co.uk.temporalcohesion.euler.interfaces.Problem;
 
public class One implements Problem {
 
	public String answer() {
		// TODO Auto-generated method stub
		return null;
	}
 
	public int id() {
		// TODO Auto-generated method stub
		return 0;
	}
 
	public double time() {
		// TODO Auto-generated method stub
		return 0;
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
 
	}
 
}

I can hear you asking why am I including then main(String[] args) function if we already have a class that is capable of running the problems (the main Euler class)? Well, what I do to create is to create a Euler object in the problems main method, and get it to run the problem, like this:

        /**
	 * @param args
	 */
	public static void main(String[] args) {
		new Euler().run(1, true);
	}

So the problem class is running itself using the Euler object, which knows how to find the problem, instantiate it and run it. I find doing things this way is easier when working on the problem, as you can simply run the problem as a java application, and it will output the result in a standard format we are expecting to to the console in Eclipse.

Thinking about it, you might be wondering – what’s the point of all this, it seems a little excessive for something that can be done fairly easily? Well – I’ve done it like this because the whole point of me doing the problems on Project Euler, is to practice problem solving and become more comfortable in my use of Java. So I think what I’ve done is pretty valid in that regard.

In Part 1, I showed a basic problem runner framework for Project Euler, however there are a number of ways in which we can improve it. For example:

  • How can we run a specific problem?
  • How can we hide the answer, but still run the problem?
  • How can we avoid manually adding problems to the List of problems?
  • Not really to do with the framework, but how can we automate building everything?

I’ll demonstrate some ways that we can do all that, except for the 4th option, which is handled by Ant.

Improving the framework

The first thing that we can do is to add a utility function that handles showing the answers, this way we only have one place in the code that we need to update when we want to change how the answers are shown.

private void showAnswers(Problem problem){
		System.out.println("Problem: " + problem.id() + ". Answer: "
				+ problem.answer() + ". Time: " + problem.time() + "s");

}

To run a specific problem, we need to overload the run() function to access the problem we want, and show the answer.

public void run(int i) {
		try{
			Problem problem = (Problem) problems.get(i);/* problem list starts at 0 */
 
			if (problem != null) {
				showAnswers(problem);
			}
			else {
				System.out.println("There doesn't appear to be an answer for problem " + i);
			}
 
		} catch (IndexOutOfBoundsException e){
			System.err.println("There doesn't appear to be an answer for problem " + i);
		}
 
	}

As you can see, we get the specified problem out of the list, and use our new showAnswers() function to display the answer.  I’ve tried to include some good error checking – we might try to get a problem that doesn’t exist.

In order to prevent the answer from being shown, we can add a boolean parameter to the run() and showAnswers() functions.

private void showAnswers(Problem problem, boolean showAnswers){
		if(showAnswers){
			System.out.println("Problem: " + problem.id() + ". Answer: "
					+ problem.answer() + ". Time: " + problem.time() + "s");
			}
			else {
				problem.answer(); /* we still need to work out the answer */
				System.out.println("Problem: " + problem.id() + ". Time: " + problem.time() + "s");
			}
	}
 
public void run(boolean showAnswers) {
		for (Problem problem : problems) {
			if (problem != null) {
				showAnswers(problem, showAnswers);
			}
		}
	}

Dont’t forget to change the overloaded run(int i) to run(int i, boolean showAnswers). This way we can control exactly  whether to show the answers when we run all the problems, or to show the answer if we run a specific problem.

One thing remains to do, and that is to correctly parse the command line arguments to control whether the answers are shown or not. We want to handle something like this:

C:\development\euler>java -jar ProjectEuler.jar 42 -noanswer

Where 42 is problem 42, and -noanswer clearly specifies not to show the answer. We’ll also need to handle all combinations of this as well, such as:

C:\development\euler>java -jar ProjectEuler.jar 42

Which should show the answer. I’m not going to show my code for parsing the command line arguements, I’ll leave that as an exercise for the reader, as I believe that it is adequately covered elsewhere on the internet, and in any number of Java books.

The more astute among you will notice that I’ve not mentioned how we are going to avoid manually adding problems to the List of problems. I’ll cover that next time.

Everyone developer should use some form of source control. It’s like an unwritten law, if you don’t use it, then you should – as long as it isn’t sourcesafe.

A few weeks ago, I recently managed to get hold of an invite to Dropbox, which describes itself as “Secure back up, sync and sharing made easy”. I’ve been using it both as a basic form of source control, and because I always tend to forget my usb pendrive, as a portable storage device.

The great thing about Dropbox is that you get 2gb of free storage. So far, I’ve sync’d a few photo’s, some word documents and pdf’s and the Java source for my Project Euler code, and according to the Dropbox client on my laptop, I’ve used 0.1% of 2gb. This is more than enough for me, and more than likely I’ll use it for some more coding projects. I’d like to see how a Visual Studio project takes to being sync’d across different computers.

With Dropbox, you get complete file history, so if you mistakenly remove some code that turns out to be pretty vital… you can get it back using the simple to use web interface. While you can share folders, and allow people to modify shared folders, I’m not too sure that it would work too well for collaborative software development. I think it would be far better to get a proper form of source control running on a server both parties have access to. There are plenty of proper source control providers out there with free options, and I am considering moving my code onto one of those, if I can find one that has a reasonable yearly subscription.

For my current requirements, it suits me just fine. I realise that Dropbox is not intended to be a source control system, however… When the client is able to sync specific folders that you tell it to, it will be perfect.