This blog has moved to Medium

Subscribe via email


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Archive for January 2010

An open source StackOverflow clone by a n00b web dev

Edit – just so you know, since writing this I found Shapado and OSQA, which seem well underway to becoming viable Stack Exchange alternative. I don’t think I will continue developing this project, although it has taught me a great deal nonetheless.

I wanted to share a small learning exercise I underwent recently. I decided to learn how to build a website, and share the experience here. Lacking an original idea at the moment, I decided to create yet another StackOverflow clone – not original, but a good exercise nonetheless. The code for the project is hosted at GitHub, although I don’t have a live showcase up at the moment. Yes, I am aware a google search reveals an existing open source SO clone called Stacked – I thought building one from scratch might teach me more than reading someone else’s code base (I could be wrong, but this is how I wanted to roll).

Day 1

The choice of database engine was easy: The one database I had any experience with was mysql, and being open source, free and easy to work with, I went with it. Next, an ORM library. After some digging, I’ve decided to go with NHibernate + Castle ActiveRecord. ActiveRecord is great for easily mapping simple classes and relations, and NHibernate to complement it in ‘advanced queries’. I don’t get any LINQ magic from these ORMs, which is a pity. I then proceeded to create a solution and some projects, added NUnit as a test framework, and setup Castle MicroKernel as an IOC framework.

I tried to found an open hosted source CI server, but didn’t find anything that worked. Oh well, not essential for now.

Day 2

Before proceeding any further, I had to choose a source control provider. If this were a production project I would probably have gone with SVN hosted on Google Code. However, Ken told me about Git long ago, and I thought this was a good chance to experience it. So, on to GitHub. Opening the project was a no brainer, but finding a decent client was more challenging. I had some fun learning about Git’s private keys, and configuring TortoiseGit (I tried GitExtensions, but it doesn’t support Visual Studio 2010 beta 2 yet). Overall, TortoiseGit gets the job done, after some tweaking and .gitignore files.

Git’s distributed source control model is interesting and worth a try.

I created the User, Question & Vote tables, learned about composite keys in AR, and wrote my first NH query:

GetVoteCount – “SELECT Vote, COUNT(*) FROM ” + VotesTableName + ” WHERE PostId = :postId GROUP BY vote”

I currently don’t have any caching on the vote count – am simply storing the votes as relations between users and questions, and counting them on the fly.

Day 3

I would like to implement full features, not write the entire DAL first and then the application logic. So, it’s time to start learning about web development. At work people are using Monorail, but after reading this question I decided to try out ASP.Net MVC instead. So, I read a basic tutorial and starting coding. Some things I learned:

  1. I finally got the meaning of Global.asax.cs – it’s simply the ‘main’ of the web application.
  2. By default, ASP.Net MVC creates the controllers by itself and does not support IOC. Fixed (remember to setup the Controller’s lifestyle as LifeStyle.PerWebRequest).
  3. Some Asp.Net MVC basics:
    1. Use <%= … %> to write to the output stream (that gets sent as the HTML), and <% %> to simply execute code.
    2. Use Html.RenderAction() to create links to other pages (~= Actions)
    3. Your pages are butt ugly without tweaking the CSS

Day 4

  • I quickly caught myself duplicating code, and turned to learn about Partial Views, which are reusable View pieces.
  • I realized that having my model entities derive from ActiveRecordBase is damn ugly, because it makes my entire application dependant on AR even if I was using repositories to access the data. I switched the repositories to using ActiveRecordMediator instead.
  • The magic that is ReturnUrl – an extra request parameter that controllers use to return you to your original page after you login.
  • An interesting usage for anonymous object creation syntax in C#, to pass query parameters: new { ReturnUrl = “foo”}
  • I decide to create a base class for all my controllers – UserAwareController. This was needed because every controller needs to access the current user, so I put all this logic in the UserAwareController base class.
  • Since every View needs the User to render, I created a Model base class that contains the current user. I’m not sure if this is the best way to go here, but it worked (what are your recommended best practices to store the user data?)
  • I implemented OpenID login using DotNetOpenAuth, and it was quite a breeze. No need to store user credentials, just store his public open id and let other websites handle the authentication for you.

Day 5

After allowing users to login and post questions, the next thing I wanted to implement was voting. So far all the code was server-side, but voting requires javascript because when a user votes you don’t want to refresh the page, but rather just change the vote icon. So:

  • I learned about jquery basics and wrote events to handle clicking the voting buttons.
  • Sent the vote information to a dedicated controller using JSON. The way JSON requests translate to controller methods is really seamless.
  • Initially I had an ‘AddVote’ method, but quickly switched to ‘UpdateVote’, which makes more sense.
  • Some css tweaks to make the cursor change to a pointer while on the voting buttons

Day 6

  • I finally had to cache vote count on questions & answers. The total vote count / score of a question has to be indexed, because we’ll have pages that get the ‘hottest posts’, and so keeping the User-Question vote relation is not enough.
  • So far, all my entities were strictly mapped to database rows. Now, I had to create a new ‘rich entity’ that contained a post and the current users’ vote on this post.
  • Finding myself duplicating logic between questions & answers, I create a Post base class and factored the entities and repositories to work on abstract posts.

This is it for now. I hope I didn’t make too many glaring mistakes in the process. As I mentioned, the code is available at GitHub – if you’re interested in helping develop it or have any questions, please let me know.

Cancelor – a java task cancelation service

Lately I need to support task cancellation in a Java process I’m working on. The straightforward options I know to implement this are:

  1. Thread.interrupt() – the caller interrupts the worker thread (either directly or using Future.cancel()). Some say this is an erroneous approach, but I still haven’t figured out why. However, it is buggy on some recent versions on the JDK, and it is a bit fragile (what if the worker threads create worker threads that also need to be canceled?).
  2. Passing some object (AtomicBoolean?) down to every object you would like to support cancellation. These objects will check the value of this boolean, and should stop if it is false. They can pass the boolean to other objects / tasks. While this works, this boolean cannot be injected, and so must be manually passed along the call stack.

If you want the advantages of the second method, but don’t want to break IOC, here’s how:

First, the usage:

The listener object adds a dependency on ICancelor

public class Foo {
  public Foo(ICancelor cancelor) {
    this.cancelor = cancelor;
    ...
}

It then checks the cancellation state every now and then:

if (cancelor.wasTaskCanceled("TakeOverTheWorld"))
   return;

The top-level thread that wishes to cancel a task simply calls

cancelor.cancelTask("TakeOverTheWorld");

And whenever a task is started, you should call

cancelor.resetTask("TakeOverTheWorld");

I’ll admit using strings for task names is a bit ugly, but this is not a terrible price to pay, assuming you have a few core tasks you intend to support. All that remains is the cancellation service itself:

/**
 * A cancellation service.
 */
public interface ICancelor {
    /**
     * Resets a task to "Not canceled" state
     */
    void resetTask(String name);
 
    /**
     * Returns true iff the a cancelTask was called, and no resetTask was called afterwards.
     */
    boolean wasTaskCanceled(String name);
 
    /**
     * Cancel a task
     */
    void cancelTask(String name);
}
 
public class Cancelor implements ICancelor {
  private final ConcurrentHashMap tasks = new ConcurrentHashMap();
 
    public void resetTask(String name) {
        tasks.put(name, true);
    }
 
    public boolean wasTaskCanceled(String name) {
        Boolean value = tasks.get(name);
        return value != null & value;
    }
 
    public void cancelTask(String name) {
        tasks.put(name, false);
    }
}

Because we rely on task names, there is an assumption here that all classes that play in the cancellation game belong to the same task semantically. If a class is a common class that doesn’t belong to a single task or flow, this approach does not work – in fact, I cannot think of an approach that will work in this case with dependency injection. The common class has to accept the cancellation signal somehow, it must either get an boolean explicit and not from the IOC container, or must check its interrupted state (or some other thread-local state) itself. Any smart ideas on how to solve this problem?

ALT.NET Israel Tools #1

Come hear about .Net tools in a “no bullshit” evening (more details here).