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;
    }
}

Posted in Development | Tagged | 1 Comment

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!

Posted in Development | Tagged , | 1 Comment

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:

Posted in Development | Tagged | 3 Comments

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.

Posted in Development | Tagged | 1 Comment

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);
Posted in Development | Tagged | Leave a comment

The plans for 2010 – Update

We’re halfway into 2010 already so it’s time for a little update about my plans for this year. Quite a few things have changed since the original post.

Get certificated

I have decided not to go for the MCTS 70-536 – Application Development Foundation and MCTS 70-562 – Microsoft .NET 3.5, ASP.NET Application Development certificates. Why? Because there is a new certificate: the 70-515 Web Applications Development with Microsoft .NET Framework 4 certificate. Since it covers the .NET 4.0 framework and ASP.NET MVC and doesn’t require you to get another certificate first, it is a lot more interesting.

So as soon as there is a book covering the 70-515 exam, I’m going to get started!

Build a demo application in ASP.NET MVC 2

This hasn’t changed. I still plan to build a small sample application and I finally have an idea what that application might be.

Build a demo application with a NoSQL solution

In the original post, I talked about using MongoDB, CouchDB and/or db4o in an application.

I still want to use a NoSQL solution, but instead of using one of the above, I think I will give Raven DB a try. Raven is an open source document database for the .NET/Windows platform. It is developed by the incredible Ayende Rahien. Since it was built with .NET in mind, it should be a lot easier to use than MongoDB, CouchDB and db4o.

Learn some more about continuous integration

I have started to read some more about continuous integration and it seems it can be quite complicated. I think it might be better to start learning/using a basic part of continuous integration first: source control and versioning. I’m not sure whether to use git or Mercurial. Thankfully, Tekpub has video series about them both.

Posted in Development | Tagged | Leave a comment

Busy times

There hasn’t been a lot of activity around here fore the last few weeks, but I have my reasons. Very good reasons even.

On June 02, 2010 I’m getting married and a few days later I’m going to New York for a week. Both of these require a lot of preparation so there hasn’t been much time to write blog posts.

I do have a few draft posts queued up though, so as soon as I’m back from New York I’m going finish them. At least, that’s the plan.

Let’s hope Giant Cloud of Ash from the Eyjafjallajökull doesn’t mess things up.

Posted in General | Leave a comment

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.

Posted in Development | Tagged | 2 Comments

The plans for 2010

There is an update to this post available here: http://www.kristofclaes.be/blog/2010/06/17/the-plans-for-2010-update/.

In the wonderful world of IT there is an such abundancy of things to do and discover that it is often hard to focus on just a few them. Most of the times, that leads to superficially looking into a lot of things while mastering none of them and before you know it, you’ll be the proverbial jack of all trades and master of none.

Because a new year goes hand in hand with New Year’s resolutions, I thought it might be a good idea to make some resolutions in the area of technologies. I’ve taken some time to compile a list of things I believe are quite interesting and want to know more of. It is my intent to check off items on the list during the year and by the beginning of 2011 I should have finished everything. I have tried to keep the list on the small side to have a buffer for one or two extra things I might encounter during the year. If find too many things, they’ll just have to wait for 2011.

This is the list I mean to finish, in no particular order:

The fun part is that certain items can be combined. Let’s say I build a demo application in ASP.NET MVC 2 and use MongoDB for data storage. That’s two items off the list. Why stop there? Why not use dependency injection and integrate all three databases in the application? And why not set up a continuous integration server while developing the application? I must admit maybe that’s a bit too ambitious.

We’ll see where we get!

Posted in Development | Tagged , , , | 1 Comment

Scott Guthrie is coming to Belgium

Scott Guthrie, Corporate Vice President of the Microsoft Developer Division, among other things responsible for ASP.NET, Silverlight and IIS 7, is coming to Belgium on the 4th of December to give a presentation about Visual Studio 2010, .NET 4 and Silverlight 4.

The presentation is free and it will take place in Kinepolis in Brussels. The planning for the day can be found below and registering can done using this link.

13:00 – 13:30 Reception and registration
13:30 – 15:00 Visual Studio 2010 and .NET 4 web development
15:00 – 15:20 Break
15:20 – 16:30 Silverlight
16:30 – 17:00 Q&A
Posted in Development | Tagged , | Leave a comment