Building a photoblog with Nancy and Simple.Data Part 1: Setting up the project

This is the first part in my Building a photoblog with Nancy and Simple.Data series:

  1. Setting up the project
  2. Defining the routes
  3. Rendering some views
  4. Adding the database
  5. Updating Simple.Data
  6. Adding comments
  7. The archives

As an amateur photographer, I’m currently running a photoblog based on WordPress. While that’s working just fine, I have a feeling that WordPress is a bit too over-featured for a simple photoblog. Since I’m not only an amateur photographer but also a professional web developer, I have the perfect excuse to build very own little photoblog!

As a .NET developer, the evident choice would be between ASP.NET WebForms or ASP.NET MVC. If those two would be my only options, I would pick MVC without a doubt, but there are some other, open source, options. One of them is called Nancy and it’s been getting quite a lot of attention lately.

For data access I could go with a nice ORM like NHibernate or Entity Framework, but if WordPress is overkill for a photoblog, then NHibernate and Entity Framework are triple overkill. Instead I’ll go with another open source alternative: Simple.Data.

Both Nancy and Simple.Data claim to be lightweight and easy to work with. In this series of blog posts, I’m going to describe my experiences with them while building my photoblog.

Creating the solution in Visual Studio

As far as I know, the easiest way to get started with Nancy is to create a new empty ASP.NET Web Application. So start Visual Studio, click File > New Project…, select the ASP.NET Empty Web Application template, enter a name for the project (I’m bad with names, so I’ve chosen MyPhotoBlog), make sure that Create directory for solution is checked and click OK.
Create a new project

This gives a nice clean base to start from. Now we need to add references to the necessary Nancy and Simple.Data libraries.

Adding Simple.Data

Adding Simple.Data is easy. All we need is available through NuGet. Just fire up the Package Manager Console, enter Install-Package Simple.Data.SqlCompact40 and press enter. This will add the Simple.Data.SqlCompact40 library, but also the Simple.Data.Core library since that last one is listed as a dependency. You will also notice that some Rx (Reactive Extensions) libraries are added as well. Isn’t NuGet awesome?

Adding Nancy

The different Nancy functionalities are split up in multiple libraries and unfortunately, not all of them are available through NuGet. So to add Nancy, we will download the source from Github, build it manually and copy the required libraries over to our solution.

  1. Go to the Nancy repository on Github and download the source. Of course you can also fork the project pull everything in using Git.
  2. If you have Ruby 1.8.7 or later installed, you can just run the rake command in the Nancy directory. This will run all unit tests, build all projects and put the libraries in a build directory. If you don’t have Ruby installed you can also open the Nancy.sln file in Visual Studio and build everything manually. Either way, you end up with a lot of dll-files.
  3. Open the directory of the photoblog project in Windows Explorer and create a new directory called Libs. Copy these Nancy libraries to the Libs directory: Nancy.dll, Nancy.Hosting.Aspnet.dll and Nancy.ViewEngines.Razor.dll.
    Directory structure
  4. Add the three libraries as a reference to your photoblog project in Visual Studio. Add the Nancy references

Configuring Nancy

Nancy can be configured using some Web.Config settings. To enable the default configuration, which is OK for this project I believe, just modify your Web.Config file so that it looks like this:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <httpHandlers>
            <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>
        </httpHandlers>
    </system.web>

    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <validation validateIntegratedModeConfiguration="false"/>
        <handlers>
            <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>
        </handlers>
    </system.webServer>
</configuration>

That’s all there is to it! Nancy is ready to go!

Adding our first NancyModule

If we would have used ASP.NET MVC, we would now need to setup routing in the Global.asax file, create at least one Controller class with at least one Action method and make sure that the Action method corresponds to a route. Using Nancy, it all becomes a little simpler. A NancyModule class replaces the Controller, and the Action method and route become integrated into that NancyModule.

To end this first post, we’ll create such a NancyModule to verify that everything is working correctly (Simple.Data excluded, well get to that later).

Add a class to the root of your project. I’ve called mine MainModule.

Let the class inherit from NancyModule (located in the Nancy-namespace):

public class MainModule : NancyModule
{
    public MainModule()
    {
    }
}

Now we’ll make sure that the root URL (“/”) returns something to the browser. Adjust the class so that it looks like this:

public class MainModule : NancyModule
{
	public MainModule()
	{
		Get["/"] = parameters =>
		{
			return "<h1>Welcome to My Photoblog!</h1><p>Nothing to see here at the moment.</p>";
		};
	}
}

That’s doing exactly what it looks like: it is telling Nancy to listing to incoming GET-requests corresponding to “/” and telling it to return a string of text to the browser. Don’t believe me? Press CTRL+F5 and be amazed!
It works!

Now let’s add another route. Let’s add one with a parameter! Modify the class so that it looks like this:

public class MainModule : NancyModule
{
	public MainModule()
	{
		Get["/"] = parameters =>
		{
			return "<h1>Welcome to My Photoblog!</h1><p>Nothing to see here at the moment.</p>";
		};

		Get["/photo/{slug}"] = parameters =>
		{
			return String.Format("<h1>I'm sorry</h1><p>We're having some problems finding photo '{0}' for the moment.</p>", parameters.slug);
		};
	}
}

What do you think that this will do? Correct! It tells Nancy to listen for incoming GET-requests starting with “/photo/” followed by anything. Because we have defined it as {slug}, whatever comes behind the “/photo/” part, gets put in the slug property of the parameters variable. See how we pass it to the String.Format() method? It all works dynamically! To see this in action, just surf to “/photo/big-dog” for example. Isn’t that awesome?
That's too bad. I really wanted to see a big dog...

Conclusion

That’s it for the first post of the series. As you have seen it is really really easy to start using Nancy. From what I’ve read, using Simple.Data is equally easy, but we’ll save that for a future post.

In the next post, we’ll think about what we want our photoblog to do and add all the routes we’ll need for that.

Interesting links

Registering a namespace for all Razor views

When you want use your own code generating classes like HtmlHelpers in a Razor view, you can register the namespace at the beginning of the Razor view like this:

@using My.Custom.Namespace

But what when you want to use a certain class in almost all of your views? Well, of course you can manually add the using statement to each view, but there is another way. You can add the namespace in your Web.Config file. The catch here is that you don’t need to add it to the Web.Config file in the root of your project, but to the Web.Config file in the View directory.

Just add it to this part of the file:

<system.web.webPages.razor>
	<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
	<pages pageBaseType="System.Web.Mvc.WebViewPage">
		<namespaces>
			<add namespace="System.Web.Mvc" />
			<add namespace="System.Web.Mvc.Ajax" />
			<add namespace="System.Web.Mvc.Html" />
			<add namespace="System.Web.Routing" />
			<add namespace="My.Custom.Namespace" />
		</namespaces>
	</pages>
</system.web.webPages.razor>

Escaping curly braces in String.Format

Most of you will know that you can use String.Format to insert and format objects into a string. For example:

int distance = 5;
int time = 15;
DateTime when = new DateTime(2011, 3, 7);

string output = String.Format("You have run {0} miles in {1} minutes on {2:dd/MM/yyyy}.",
    distance,
    time,
    when);

Console.WriteLine(ouput);

This will print “You have run 5 miles in 15 minutes on 03/07/2011″.

But what should you do when you need curly braces in your string? Let’s say you want to do this:

string output = String.Format("The delimiter {text} was found {0} times.", 5);
Console.WriteLine(output);

When you try this, it will give you a System.FormatException saying “Input string was not in a correct format”. That’s because of the the {text} in our string. To solve this, the curly braces need to be escaped. But how? Escaping them with a backslash won’t work. The solution is actually very simple: you need to escape curly braces with… curly braces!

To make our example work, we just have to do this:

string output = String.Format("The delimiter {{text}} was found {0} times.", 5);
Console.WriteLine(output);

This will print “The delimiter {text} was found 5 times.”, just like we want it to.

How to identify CMYK images in ASP.NET using C#?

I’m trying to create a small and reusable library to resize and save images in ASP.NET applications. Because some browsers can’t display CMYK images, I thought it would be nice to make my library convert CMYK images to RGB when saving them.

My library currently has an Image class, which is basically a wrapper around the System.Drawing.Bitmap class. The System.Drawing.Bitmap class contains a Flags attribute (actually, this property belongs to the System.Drawing.Image class, the base class of Bitmap). This property returns an integer that represents a bitwise combination of System.Drawing.Imaging.ImageFlags. The ImageFlags enumeration has a ColorSpaceCmyk value. If this value is set in the Flags property of an Image instance, that image should be a CMYK image. Unfortunately, the bitwise combination returned by the Flags is bugged.

I have created three images to test this: cmyk.jpg, rgb.jpg and gray.jpg. These are respectively CMYK, RGB and Grayscale images.

Next, I created a console application with the following tt:

static void Main(string[] args)
{
    Bitmap bmpCMYK = new Bitmap("cmyk.jpg");
    Bitmap bmpRGB = new Bitmap("rgb.jpg");
    Bitmap bmpGray = new Bitmap("gray.jpg");

    Console.WriteLine("\t\tRgb\tCmyk\tGray\tYcbcr\tYcck\tPixelFormat");

    Console.WriteLine("cmyk.jpg\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpCMYK.PixelFormat);

    Console.WriteLine("rgb.jpg\t\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpRGB.PixelFormat);

    Console.WriteLine("gray.jpg\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpGray.PixelFormat);

    bmpCMYK.Dispose();
    bmpRGB.Dispose();
    bmpGray.Dispose();

    Console.ReadLine();
}

private static bool IsSet(Bitmap bitmap, System.Drawing.Imaging.ImageFlags flag)
{
    return (bitmap.Flags & (int)flag) == (int)flag;
}

This doesn’t really do what it’s expected to do:
Results of testing the Flags property

As you can see, both the CMYK and RGB image have ColorSpaceRgb set to true and the ColorSpaceCmyk set to false.

Apparently, this is a known issue. And what’s even worse, whether ColorSpaceCmyk is set to true of false, depends on the operating system the code is run on!

I haven’t been able to find a solution to this problem, so I posted my problem on StackOverflow. Hopefully, I’ll soon get an answer.

Anonymous types and the ItemDataBound event

As you will probably know, when you bind a list of items to a Repeater, you can then convert the DataItem to the type of that item in the ItemDataBound event of the Repeater like this:

public class Person
{
    public string Name { get; set; }
	public string Email { get; set; }
	public int Age { get; set; }
}

public void Page_Load(object sender, EventArgs e)
{
	List<Person> people = new List<Person>
    {
        new Person { Name = "Bob", Email = "bob@example.com", Age = 28 },
        new Person { Name = "John", Email = "john@example.com", Age = 31 },
        new Person { Name = "Phil", Email = "phil@example.com", Age = 24 }
    };
	
    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Person p = e.Item.DataItem as Person;

        string name = p.Name;
        string email = p.Email;
        int age = p.Age;
    }
}

But what when you aren’t databinding to a list of a concrete class but to a list of an anonymous type? Well, before .NET 4.0 you had to that like this:

public void Page_Load(object sender, EventArgs e)
{
	var people = from p in DB.GetPeople()
	             select new { Name = p.Name, Age = p.Age };
				 
    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string name = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Name"));
        int age = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Age"));
    }
}

Using the new .NET 4.0 dynamic type, this can be done a lot easier:

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
		dynamic person = e.Item.DataItem as dynamic;
		
        string name = person.Name;
        int age = person.Age;
    }
}

Some of my extension methods

I’m really starting to appreciate extension methods. They provide an easy way to perform small common tasks you would usually put in static utility classes. Below you can find some I use regularly. The first two are extension methods to DateTime. The last two are for the WebControl class. This is the base class for a lot of, well, WebControls in ASP.NET.

When building a website or a web application, letting users enter a date is a common scenario. Often you have to check if the date is between a minimum and a maximum date. When storing a date entered by a user in MS SQL Server, you actually have to perform such a check, because MS SQL Server can’t store DateTime values smaller than 1/1/1753. To make this easier, I have come up with these two extension methods.

namespace System
{
    public static class ExtensionMethods
    {
        public static bool IsBetween(this DateTime date, DateTime firstDate, DateTime secondDate)
        {
            return (date >= firstDate && date <= secondDate) || (date <= firstDate && date >= secondDate);
        }

        public static bool IsValidSqlDateTime(this DateTime date)
        {
            return date.IsBetween((DateTime)System.Data.SqlTypes.SqlDateTime.MinValue, (DateTime)System.Data.SqlTypes.SqlDateTime.MaxValue);
        }
    }
}

These can be used like this:

DateTime dateToCheck = new DateTime(1492, 10, 12);
DateTime firstDate = new DateTime(1400, 1, 1);
DateTime secondDate = DateTime.Now;

bool isWithinRange = dateToCheck.IsBetween(firstDate, secondDate);
bool isValidSqlDateTime = dateToCheck.IsValidSqlDateTime();

The next two extension methods concern the WebControl class. A few examples of controls that inherit from this class are HyperLink, TextBox, Label and Panel. The WebControl base class provides all these controls with the CssClass property. You can assign a string to this property and that string will be rendered as the class attribute of the HTML tag. Now, a lot of the times when you use the CssClass property, you’re not assigning just one class. You’ll often be assigning multiple classes and in a lot of cases you’ll be assigning different classes based on certain conditions. This is not that handy when you have also assigned a default class in the ASP.NET markup:

<asp:Label ID="MyLabel" runat="server" CssClass="defaultClass" />

Let’s say you want to add different classes to that based on whether the current user is logged in or not. To do that, you would have to repeat the defaultClass like this:

if (userIsLoggedIn)
{
    MyLabel.CssClass = "defaultClass loggedIn";
}
else
{
    MyLabel.CssClass = "defaultClass anonymous";
}

I don’t really like that. That’s why I wrote these extension methods.

namespace System.Web.UI.WebControls
{
    public static class ExtensionMethods
    {
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            control.CssClass += " " + cssClass;
        }

        public static void RemoveCssClass(this WebControl control, string cssClass)
        {
            var classes = from c in control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                          where !c.Equals(cssClass, StringComparison.OrdinalIgnoreCase)
                          select c;

            control.CssClass = String.Join(" ", classes);
        }
    }
}

You can use them like this:

if (userIsLoggedIn)
{
    MyLabel.AddCssClass("loggedIn");
}
else
{
    MyLabel.AddCssClass("anonymous");
}

if (specialCase)
{
    MyLabel.RemoveCssClass("defaultClass");
}

I hope this is useful to you!

First look at EF Magic Unicorn

Magic Unicorn

A few days ago, Microsoft released CTP4 of the Entity Framework Feature. In his blog post demonstrating the new features of the EF CTP4, Scott Hanselman proposed a better name than the official “Microsoft ADO.NET Entity Framework Feature 4″: “EF Magic Unicorn Edition”. I quite like that name, so I’ll use it from now on.

The biggest addition the Entity Framework is the ability to use a code-first approach. This means that you just write your basic (POCO) classes representing your model and let the EF Magic Unicorn take care of all the rest. No fiddling around with designers or XML bindings. Instead you can just concentrate on your code!

I thought this looked rather cool, so I decided to give it a go and it only took me a few minutes to get a working example.

Creating a new ASP.NET MVC 2 project

Let’s start with creating a new blank ASP.NET MVC 2 project. Because I want to see how EF Magic Unicorn handles many-to-many associations and self-referencing associations, we’ll to use something very common: posts and categories. A post can belong to multiple categories and a categories can also have multiple posts. A category can also have a parent category and multiple child categories.

Adding the model classes

Now that we have our blank project and we know what we want to test, let’s add two classes to the Models folder:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public DateTime PublishDate { get; set; }

    public virtual ICollection<Category> Categories { get; set; }

    public Post()
    {
        Categories = new List<Category>();
    }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }

    public virtual Category ParentCategory { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<Category> ChildCategories { get; set; }

    public Category()
    {
        ChildCategories = new Lis<Category>();
    }
}

Adding a reference to the Magic Unicorn

We need to download the EF Magic Unicorn. You can grab the installer here. When you run the executable, you can specify where you want to install the Magic Unicorn. Remember that location.

When the installation is complete, choose to add a reference to your ASP.NET MVC 2 project, browse to the Magic Unicorn installation directory and select the Microsoft.Data.Entity.CTP.dll file.

Creating the DbContext

Now that we have our classes in place, we somehow need to tell the Magic Unicorn about them. This also turns out to be very easy indeed. All we need to do is add a class that inherits from the DbContext class (this is new in EF Magic Unicorn) and add a generic DbSet collection (also new in EF Magic Unicorn) for each model class.

using System.Data.Entity;

public class MagicUnicornContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Category> Categories { get; set; }
}

Adding a connectionstring

At this point, we still haven’t created a database. And we won’t need to! We just have to tell the trusty Magic Unicorn where it can create one for us. To do that, we only have to add a connectionstring to the Web.Config with the same name as our DbContext: MagicUnicornContext.

<add name="MagicUnicornContext"
     connectionString="Data Source=AITWS13\sqlexpress;Initial Catalog=MagicUnicorn;Integrated Security=True;Pooling=False"
     providerName="System.Data.SqlClient" />

Adding a controller to test everything

Now we can add a controller to see if everything works. Just add a controller called HomeController, and inside the Index() action method, you can add the following code:

public ActionResult Index()
{
    // Create a new Category
    var parentCategory = new Models.Category
    {
        Name = "Parent category"
    };

    // Create a new Category and set the first one as its parent
    var firstChildCategory = new Models.Category
    {
        Name = "Child category 1",
        ParentCategory = parentCategory
    };

    // Create a new Category and set the first one as its parent
    var secondChildCategory = new Models.Category
    {
        Name = "Child category 2",
        ParentCategory = parentCategory
    };

    // Add the second and third Category to the ChildCategories of the first Category
    parentCategory.ChildCategories.Add(firstChildCategory);
    parentCategory.ChildCategories.Add(secondChildCategory);

    // Create a new Post
    var post = new Models.Post
    {
        Title = "New post",
        Text = "The contents of the first post",
        PublishDate = DateTime.Now,
    };

    // Add the third Category to the list of Categories of the Post
    post.Categories.Add(secondChildCategory);

    // Create an instance of our context
    Models.MagicUnicornContext muc = new Models.MagicUnicornContext();

    // Add the Post and the Categories
    muc.Posts.Add(post);
    muc.Categories.Add(parentCategory);
    muc.Categories.Add(firstChildCategory);
    muc.Categories.Add(secondChildCategory);

    // Save everything
    muc.SaveChanges();

    return View();
}

What we do here is create a new post and three new categories. The first category becomes the parent of the other two categories. The second child category also gets added to list of categories of the post. Next we create a new instance of our MagicUnicornContext, we add the post and the categories to the context and call SaveChanges() on it.

Running it

After giving everything a final check and adding a default view, you can hit Ctrl-F5 and if all goes well, a blank browser window will apprear. It should be empty because our default view is still empty. So that means that no errors have occured!

Check the database

Now we only have to see if the Magic Unicorn actually created our database. You can fire up SQL Server Management Studio, or use the Server Explorer in Visual Studio, connect to your SQL Server and check out the databases. There should be database called MagicUnicorn that wasn’t there before!
Database diagram
When you open the tables, you will see that the Post, the three Categories and the links between were added as well.

Further reading

For more detailed guides about the EF Magic Unicorn, you can have a look at these excellent articles:

Is formatting strings in a View evil?

Yesterday, I ran into an interesting post by Chris Brandsma about his personal rules when dealing with Views in ASP.NET MVC. While he sure has some valid points, I don’t agree with everything he says in that post. Apparently, I’m not the only one since Jeff Putz beat me to it and made a post on his blog about the same doubts that I have about Chris’ ideas.

The first thing I don’t agree with is that Views shouldn’t do any formatting or parsing. According to Chris, DateTime values should be formatted by the ViewModel and passed to the View as strings. The problem I have with this way of working is: where do you draw the line? Does that mean you also have to let the ViewModel format decimal values representing a price and pass that to the View as a string? Ultimately, it implies that a ViewModel should only have strings for properties. As Jeff points out, this would also mean HtmlHelpers are to be avoided as well. I don’t think there’s anything wrong with letting the View format a DateTime value. Making calculations is something else of course.

The second thing I don’t agree with is that the ViewModel should also pass in the CSS classes of the HTML elements. For me, that’s at least one bridge too far. I agree that you shouldn’t put business logic in the View, but putting markup elements in the ViewModel shouldn’t be done either.

Of course, these are just my virtual two cents on the subject.

Order on multiple fields with LINQ

This is one of the things I tend to forget when I need to order a list on multiple fields using LINQ. I often start with chaining OrderBy() methods, only to realize that that doesn’t work. When you do that, only the last OrderBy() is taken into account.

What you need to do is start with an OrderBy() (or OrderByDescending()) and then chain ThenBy() (or ThenByDescending()) methods. It actually makes some sense and it is certainly easier to read. I bet I’m not the only one forgetting this.

List<Fruit> fruits = new List<Fruit>
{
	new Fruit { Name="Apple", Color="Red" },
	new Fruit { Name="Apple", Color="Yellow" },
	new Fruit { Name="Plum", Color="Purple" },
	new Fruit { Name="Strawberry", Color="Red" },
	new Fruit { Name="Banana", Color="Yellow" },
	new Fruit { Name="Apple", Color="Green" },
	new Fruit { Name="Orange", Color="Orange"},
	new Fruit { Name="Tangerine", Color="Orange" },
	new Fruit { Name="Lemon", Color="Yellow" }
};

// This one is only ordered by Name
var sorted = fruits.OrderBy(f => f.Name);

// This one is only ordered by Color, not by Name
var sorted2 = fruits.OrderBy(f => f.Name).OrderBy(f => f.Color);

// This one is ordered by Name and then by Color
var sorted3 = fruits.OrderBy(f => f.Name).ThenBy(f => f.Color);

Game of Life in Javascript

Background

A while ago, I discovered Jonh Conway’s Game of Life. Game of Life is a cellular automaton invented by the British mathematician John Horton Conway in 1970.

A cellular automaton is an array (of one or more dimensions) of cells in which each cell has a finite number of conditions. An example of a finite number of conditions is “on” and “off”, or “empty”, “half full” and “full”.

A set rules determines, based on the current condition of the cells and each cell’s neighbours, what the next condition of each cell will be.

By applying these rules repeatedly, certain patterns or movements come to exist. Depending on the rules, these movements can closely resemble what happens spontaneously in nature.

Conway’s Game of Life is an example of such a cellular automaton. The cells can either be dead or alive and within the automaton, the following rules apply:

  1. Every living cell with less than two living neighbours dies as if by underpopulation
  2. Every living cell with more than three living neighbours dies as if by overpopulation
  3. Every living cell with exactly two or three living neighbours continues to live
  4. Every dead cell with exactly three living cells comes back to life

By applying these rules multiple times per second, the cells will switch state and this can, depending on the formations of living cells, lead to interesting movements.

I thought this was so intersting that I decided to build my own implementation of Conway’s Game of Live. Using Javascript.

My implementation

Because Conway’s Game of Life takes place inside a two dimensional grid of cells, it seemed logical to use a <table> for this. In my first version I tried to get everything working without using any extra variables in Javascript by keeping everything inside attributes of the <td>’s. This worked, the performance was so horrible that I had to find another way.

In my second (and current) version, I ended up creating three classes in Javascript:

  • A class Cell that, of course, represents a cell.
  • A class GameOfLifeRenderer that is responsible for creating a <table> with a certain amount of cells. The condition of the cells is saved in a two dimensional array of the type Cell.
  • A class GameOfLifeLogic that implements the rules of the game.

The logics work like this:

  1. Loop over the two dimensional array of Cells and calculate the amount of living neighbours for each cell.
  2. Determine for each cell what its next condition will be.
  3. Loop over the two dimensional array a second time. If the current condition of a cell if different from its next condition, change the current condition and give the <td> the correct color.

Here you can find my version of Conway’s Game of Life I have also provided a browser friendly version of my Javascript code.