Tuesday, September 29, 2009
Building a site – What am I doing wrong? (3)
Friday, September 25, 2009
Building a site – What am I doing wrong?
Part 1 - Introduction
Disclaimer – sort of...
The stuff I’ll be showing in this series of posts is not necessarily wrong , but it might be “wrong” according to some of the patterns and practices that have emerged over the last couple of years. Acronyms like KISS, DRY, SOLID, YAGNI and so on are on every blogs lips, and I kind of decided to throw them out of the window, and just doing what I thought was logical at the time of programming, and according to my needs and the functionality in the application.
Of course, I’ve read loads of articles, and my programming structure has definitely been influenced by all of them, so it’s not that I’m avoiding the principles, but simply not thinking about them as I write out my application.
The Project
I’ve decided to build a site for sharing pictures among friends (yeah, yeah – it’s already out there, but who cares). I’ll start out pretty simple and see where it ends.
The initial functionality includes
- Logging in/Registering
- Creating groups that you and your friends can share and upload pictures to
- Uploading pictures
- Commenting on groups or pictures
- Giving other users access to your group
The Point
I want to do a bit of overkill in this application, and imagining that it will be scaled out, extended with more functionality, changing the datasource etc, etc. Hence, a lot of the code I’ll be showing will be overkill. I know this.
What would be great would be to get some feedback/thoughts/ideas about what I’m doing right/wrong and why it’s so wrong. I’m also doing this just to try stuff out, and see if I can figure out new and smart ways to resolve problems and implement functionality.
The Technical specs
I’ll be using the following applications and technologies when developing- Visual Studio 2008
- Microsoft SQL Server 2008
- C# .NET 3.5
- MVC
- Linq To SQL
- JQuery
Part 1 – The Database
I’m gonna start off by showing of the databasestructure and explaining a few of my choices.
First of all – a screenshot
The Tables
I’ve gone for a many-to-many relational model, and I’m using Unique Identifiers (GUIDS) as the primary keys in the database. More on this later, when we look at some code.
User
I decided to include only the stuff I need for logging in here, so Email and Password is all I need
UserProfile
I’ll probably expand this table as we go on, but it will basically be an extension of the User-table, keeping all sorts of profile-information for each user
Group
The group will be what is containing the pictures, but the definition is so far limited to a name
Comment
Simply a table containing the comments for whatever is commented on
Image
The actual information about the uploaded image
TimeStamp
This will be available to all tables, since I’m probably gonna need timestamps for all kinds of entities.
Relation
This is the reason for the Unique identifiers.
This table will keep all the relations between any entities. As you will see later, I’m managing the relations through code, so no relations in the database
Yes, I know, many of you will probably scream in agony right now, but that’s what I want. I would like you to tell me why I definitely shouldn’t choose this approach.
Part 2 – The DataAccess layer
LinqToSql
Even though I love the ease of using Linq to chat with my Db, I don’t like having my application tightly coupled to the database, so I’ve decided to have my own Entities defined, and mapping to them through repositories.
By doing this I should have the opportunity to change my datasource some time in the future. I should also be able to switch to some other ORM like NHibernate or similar.
The Repository
I’m going for a pretty tedious model here and decided to go with a structure that Rob Conery used in his early videos in the MVC Storefront video-series. The main difference is that I’ve declared a generic Repository Interface that all my repositories will implement.

I will show you the IEntity interface shortly, but first a few notes about this interface.
This is what I need for CRUD (Create, Read, Update and Delete)
- The Save-method will either create a new object in the database, or update an existing one
- The Get-method returns an IQueryable of my mapped class, so no actual querying is done until the recordset is accessed.
- The Delete-method will simply delete the object from the database
The
I’ll get back to implementation later on.
The IEntity
I’ve decided that all of my internal mapped objects need to implement the interface IEntity. Hopefully, you’ll understand the reason for this approach when you see the implementation. But this is where the patterns starts falling out :)

As you can see, I’m putting logic in my class, totally ignoring the S in SOLID (Single responsibility). But as you’ll see, I find that this provides me with a very fluent way of programming. I have a couple of ideas to sort this out, but I’ll talk more about that when we get to implementations. I’ve also included constraints on my generics.
- All my objects have an Id, so I put that in the IEntity in order to manage relations in a generic matter
- Save, will actually call the save-method in the repositories (I’m definitely in need of some advice here, so keep reading)
- Delete does the same as Save, but deletes the object
- Remove
will remove a relation to another object - Add
will add a relation to another object
DacBase
Finally I wrote an abstract class DacBase

The reason for this class is simply to hold fields and properties that are common to all objects of type IEntity. As you see, this is where I use my TimeStamps from the database (I minimized the Save()-method due to space. All it really does is save the information to the database)
The IRepository
What’s important in this class is the Relations protected field. This acts as the binder between my related objects.
As you can see, this is completely generic, not having to think about what kind of object we’re relating. This is because the Guid Id is in the IEntity interface, and the IRepository accepts IEntity as T. This all really adds up nicely in the implementation of the objects.
The Relation-class is also important in this setting:

Ufortunatly, in this version of the code I’m cheating, and accessing the Linq Datacontext directly, but I’ll fix that. I’ve also implemented the IEnumerable interface, to get list-functionality on the object. You’ll see why a little later.
Repository static class
Now this is a dirty class - yes I know. So please suggest ways to improve this!

But it basically returns the correct repository based on the type of the class asking for it.
Implementation
So let’s take a look at an implementation of one of my dataclasses. I Chose the User-class as an example.

As you might see, I’m totally disregarding SRP (Single Responsibility) here, and adding both Save, delete and so on in the dataclass.
Now you’ve seen the basics of my setup, and I’d like your feedback.
Just to show you an example of code to access for instance a comment and its related items:

What’s happening:
- Gets the user with email (username) me@test.com
- Gets all the groups related to the user
- Gets the first group
- Gets the comments for the group
- Gets the first comment
- Gets the author of the comment
- Adds a new comment to the first image in the group
It might be just me, but I think that’s a pretty easy way to work with my data.
Stay tunes. I’ll be continuing writing out this series. In the next part I’ll probably go a little more into how I use this when I start building the MVC-part of the application.
Tuesday, February 24, 2009
Fun with extension-methods
I noticed the blog Ruby inspired C# Extension Methods for natural DateTime operations on DotNetKicks earlier today, and felt like trying to write this on my own, and also extend it to show off a couple of other posibilities by using extension-methods in .NET 3.5.
Before I go on, I'd like to give credit to the original poster, and point out that it was spavkov that initially submitted the story. I just wanted to extend it a bit, and show off some code :)
The Extension-methods
An extension method is simply a method put in a static class, and it's purpose is to extend the functionality of some existing class, much like the ToString() or ToInt32() methods that we use all the time. In .NET 3.5 we get the opportunity to extend our own classes, as well as the existing classes of the framework with our own extension-methods. Sweet! :)
An example of some extension method could be
public static string Foo(this string s)
{
return s + "Bar";
}
Notice the this string s parameter, as this is key in extension-methods. It points back to the caller of the method.
In the mentioned example we could go something like:
string s = "Foo";
s = s.Foo();
and our string s would now read "FooBar";
Simple as that.
Readability
One of the main advantages I like with extensionmethods is what it does to readability, and ease of code-mainenance. So in the next example I'll show quickly how to implement extensions for DateTime and Booleans to make some weird but fun extension-methods.
Making the 1.Days() method
To create this extension-method we need to initially identify what type we are extending. 1 is an integer, so it feels right to make an extension-method that extends int.
Here we go:
public static TimeSpan Days(this int i)
{
return TimeSpan.FromDays(i);
}
Complicated? Nope! And now I can write
DateTime twoDaysAhead = DateTime.Now + 2.Days();
Now, I wont copy the original post, so I'll go right ahead with my own crazy idea. Extending Boolean.
true.If?
If anyone ends up reading this post, I will most definitely be flamed for the following example, but I think it's pretty fun and gives a nice
example on how you can use extensions to link several expressions together to form readable code.
Let start by implementing the If() extensionmethod:
public static Boolean If(this Boolean b, Boolean expression)
{
if (expression)
return b;
else
return !b;
}
What this does, is refer back to the caller (this Boolean b), and also take some Boolean expression, returning back b if the expression evaluates to true. Otherwise switch b around, and return that.
Why?
Because now I can write something like:
Boolean myFooBarTest = true.If("Foo" == "Bar");
Now, we could write for instance:
Boolean myFooBarTest = true.If((("Foo" == "Bar") && ("Foo" != "Foo")) || ("Bar" == "Bar"));
but again, I'd like to introduce two more extensions in order to make this line even more readable:
public static Boolean And(this Boolean b, Boolean expression)
{
return b && expression;
}
public static Boolean Or(this Boolean b, Boolean expression)
{
return b || expression;
}
This enables me to rewrite the above line to:
Boolean myFooBarTest = true.If("Foo" == "Bar").And("Foo" != "Foo").Or("Bar" == "Bar");
The end
And that's basically what I wanted to show you. Linking several expressions by using extension methods.
Thanks for reading!