Friday, April 23, 2010

ASP.NET MVC vs. Rails3

I recently was contacted to implement an ASP.NET MVC application and I saw this as a great opportunity to compare it with Rails3.
What immediately strikes you when you start with ASP.NET MVC is how similar it is to Rails. No one can steal ideas like Microsoft!

Rails

ASP.NET MVC

Purpose (if not obvious)

/app/models

/Models

/app/controllers

/Controllers

/app/views

/Views

/public/javascript

/Scripts

/public

/Content

/db

/App_Data

Database data, such as migrations, and models.

/test (unit, functional, fixtures, performance)

Separate VS projects

/config

/Global.asax, /Properties, Web.config

Configuration

Project Generation

Both Rails and ASP.NET MVC relies on code generation to get you started, but the methods they use are different.
Rails uses the command line, which is natural since the Rails approach is to not rely on anything but a good programming editor and the command line.

ASP.NET MVC uses Wizards inside Visual Studio, which is also expected since Microsoft has a long history of IDE-centric application building.

Worth noting is that I didn't really want to use VS Unit Test, since I normally prefer NUnit, but after one hour of googling and testing I gave up and went with VS Unit Test anyway.

Environment

When Rails is installed it comes pre-configured with three different environment, development, test and production. It is as easy as writing RAILS_ENV=test to switch from the default development environment to the test environment. In this area Rails really shines. There is nothing similar in ASP.NET MVC.

The Model

Rails Model

Rails comes pre-configured with an ActiveRecord model, if you don't write otherwise. If you want to use something else it is very easy. Supported frameworks are among others, Neo4J, MongoDB, and DataMapper.
To create a model in Rails3 you use a command line generator. The generator generates a model, a migration and tests. And you can, of course, choose what kind of model you wish to generate (-o), as well as what kind of testing framework you want to use (-t). Here I just go with the default:

Rails comes preconfigured with Sqlite3, and you don't have to do anything to configure the default database. Moreover, the configuration is set up to use three different databases, one for each environment.
Rails, performs all database changes through scripts, migrations. This is invaluable when you want to upgrade a database that is in production, or when multiple developers are changing the same database model. The migration scripts allow seamless migrations between the different databases.

# An example of a migrationclass CreateCustomers < ActiveRecord::Migration
# Called when migrating up to this versiondefself.up
create_table :customers do|t|
t.string :name
t.string :email
t.timestamps
endend# Called when migrating down from this versiondefself.down
drop_table :customers
endend

To move between the different versions of the database we use the rake db:migrate command.

ASP.NET MVC Model

ASP.NET MVC is not a full stack framework and it does not come preconfigured with a model. It is possible to choose between many solutions, such as NHibernate, Entity Framework or LINQ-to-SQL. I choose LINQ-to-SQL because I think it is an elegant, lightweight OR-Mapper, that is easy to work with. Too bad, it isn't prioritized by Microsoft.
Unfortunately, there is nothing like migrations in LINQ-to-SQL. So I use the LINQ-to-SQL design tool to design the classes.

You can then create the database from the model. It is also possible to do it the opposite way, to create the database first and then generate the model, but I prefer this way.

As you understand this is not a viable solution for migrating a production database, but it is good enough (almost) for development and testing, since I can allow myself to recreate the database every time. Once I get a larger database, the time it takes to set it up will force me to go with a better way. The lack of migrations hurts.

Query Language

Rails3 uses AREL, Active Record Relations, and LINQ-to-SQL uses LINQ (surprise!). They are both beautiful solutions and remarkably similar. Both solutions create lazy, composable queries, that are not executed until the latest possible time, when a result is needed. In LINQ, you can see Eric Meijer's Haskell shining through like magic, and in AREL, the beauty of Ruby.

One thing that you don't get with LINQ-to-SQL is all the methods that are dynamically created, by need, in Rails, such as find_by_name, find_by_name_and_age, etc.

The Controller

In ASP.NET MVC, it is easy to create a controller, you just right-click on the controllers folder and select Add > Controller. You then get a dialog where you can type in the name of the controller and, optionally, if you like to create default methods for the standard CRUD scenario, just select the checkbox.

As you can see the code generated is simple and clear. That is the benefit of MVC, simpler models, views, and controllers.
The automatic generation of code, that will probably be changed later is commonly known as scaffolding.

Scaffolding is a temporary structure used to support people and material in the construction or repair of buildings and other large structures. --Wikipedia

Scaffolding is not meant to be used as is. It is meant to get you started!
In Rails3 you add controllers with a generator. You have a lot more options, below are just a few of them.

It will create all the default actions and the views that go with them.
The generated code is shown below. Again, you see the similarity between the two solutions. Rails, automatically generates support for both HTML and XML, making it easy to consume the data from other clients.

This is a pattern that can be seen everywhere, when Rails uses Class Macros, a term from Meta-Programming Ruby, ASP.NET MVC uses attributes. And this is appropriate since it usually constitutes meta-data.

Routing

The Routing in both Rails and ASP.NET MVC is incredibly flexible.

Rails Routing

In Rails it is possible to put constraints right in the routing table on just about anything.

In Visual Studio it is possible to scaffold a view based on a model, just as it is in Rails. Rails is, of course, more flexible, allowing me to scaffold all or some actions at once. In Visual Studio, it is only possible to do one at a time.

Partials

In both Rails and ASP.NET MVC, a partial is a file that contains a part of a HTML file. The file is written in ASP in ASP.NET MVC and in Rails it is possible to pick the templating language of your choice. Default is ERB, but HAML is also a popular choice.

<!-- Rails --><%= render 'form'%>

<!-- ASP.NET MVC --><% Html.RenderPartial("Form", Model);%>

In ASP.NET MVC version 2, the preferred way is actually to use two alternate methods to generate the code. They have the advantage that they are type-safe (if that gives you pleasure) and they keep track of nesting.

Conclusion

All in all, ASP.NET MVC with LINQ-to-SQL, is not a bad experience. Eric Meijer and friends have managed to overcome a lot of the hurdles of static typing. They also, let go of it in cases, where dynamic typing is obviously better, such as in the routing and when populating objects from forms. The lambda expressions and the type inference also removes a lot of the boilerplate common in statically typed languages.
Rails is of course a lot more flexible, and faster to work with. The scaffolding is faster and more flexible, the migrations are, as I said before, invaluable when it comes to move between versions.
But, if I'm thrown out of the dynamic Garden of Eden, I'd rather pick my static apples in Redmond, than in California.

> What about debug/release?I don't think debug/release is at all the same as the different environments is Rails.Can you load different libraries, or connect to different databases based on the debug release environment. Can you copy data from the debug to the release database automatically?

> With Dynamic Linq and dynamic keyword.Possibly, but, the examples I looked at uses strings instead of late binding. Could you show me an example?

@strangy:I didn't know about the migratordotnet. I don't like having to compile my migrations though.

@Jared Ortner:Yes, I know the pattern is very old. But it's the way it is used, that makes it obvious to me that, the MS has taken their ideas from Rails. But, I think it is good that they steal or borrow good ideas.

@Simone: Yes, I couldn't get that to work.

@James Brechtel, @Sami:Thanks for the info on NHaml, I didn't know about that.

The two frameworks only look similar if you are comparing bullet points. No one who has used both would ever use ASPMVC again -- unless you like writing tons of plumbing code, but MS developers are immune to feeling that weight anymore.

@Anonymous:I am certainly not comparing bullet points, I am comparing the experience of using the two frameworks. To me this was a nice surprise since ASP.NET MVC is a lot better than I expected. I would still rather use Rails if given the choice. If you want to know my position on static vs. dynamic typing, feel free to read my previous post. Static Typing is the Root of All Evil

This is addressed in ASP.NET 4.0. Now you can have any number of configuration files (they derive from main config file). And of course, you can connect to different databases, load different libraries and so on.

BTW, for pre ASP.NET 4.0 era, there was standard way to achieve this. Web Deployment projects. In this case you have to create modifications to the main config for each your environment.

Debug/release is for optimization of compiled binaries and whether to include debug info. It is not the same as Rails environment settings which tells rails which database to connect to, user credentials, etc.

Dynamic LINQ defeats the purpose of using LINQ and is frowned upon. Even the template examples here are not typical. .NET developers tend to go crazy with anonymous classes and lambda trickery avoiding literal strings to maintain type checking and safe refactoring. I call it the cleverness over clarity syndrome.

The big problem with ASP.NET MVC is you're stuck on the MS platform. Most of the popular ORMs like NHibernate, Subsonic only officially support SQL Server. There is limited support for open source databases. Deploying to Mono is not a option yet. There are some known GC issues which consume lots of memory in Apache.

What about asp.net's DisplayFor[Model]/EditorFor[Model] dynamic scaffolding? Did Ruby has same features for dynamically generation partials like in below link?http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx

@anonymous No, Ruby doesn't have dynamic partial generation built in. It would be very simple to build. Take a look at Ryan Bates nifty_scaffold for an example of generating code from an existing model.

I prefer Rails for web development. Professionally, I'm a C# developer. I have tried out MVC 2 and the Dynamic Data Applications as well.

There is another pain point missing from your article. ActiveRecord (in Rails) and other Ruby ORMs support a concept of built-in validation errors. There is nothing like that built into any of the .NET ORMs. Since there is no standard API, there is no way to have a standard display of errors handled for me. Either the controls have to do their validations or it has to be custom added. The model is where those data validations belong. More work, less speed.

Then little things like no "flash" messages in .NET. Sure, I can code it, but it will be specific to that application. More work, less speed.

All in all, I still greatly prefer Rails for web development over any ASP.NET solution. I've been doing both for over 3 years now. And now I hate ASP.NET.

@sukumar I'm not sure what you are asking, but Rails3 is the newest version of Ruby on Rails which is an alternative and in my opinion a lot better web framework. You can find more information here.http://guides.rails.info/

This is a nice comparison. However, what about Performance and Scalability? Is Ruby on Rails capable to scale - Recently I heard that Twitter was trying to move away from Ruby on Rails because of Performance and Scalability issues.

Regarding scaling rails. There are great screencasts on that subject by Gregg Polack @ http://railslab.newrelic.com/scaling-rails. It is for Rails2, with Rails 3 it is even better, so don't be afraid of scaling issues.

I've been working with C# for few years but middle tiers and WinForms. I've started one project one year ago in ASP.NET MVC, it is much, much better than WebForms, but it was back than half baked solution. It didn't cover full stack from front to backend from scratch. I think of Rails as application framework, but ASP.NET MVC as FrontEnd framework.

I think also that superiority of rails over asp.net mvc comes from power of ruby in 80%, but as of dotNET 4 and dynamic support in C# 4.0 I think that gap will be less.

Several things in here' haven't considered before.Thank you for making this type of awesome publish that is really perfectly written, is going to be mentioning lots of buddies relating to this. Maintain blogging.

Thanks for demonstrating step by step comparison between ASP NET application development vs RR. Both has their own advantages and flaws. Both uses code generation technique but in different way; one sues command line and other uses wizard. But RR can be advantageous as it is very flexible. But it really depends on the person's usage and requirement of the project to opt which technology.

What an amazingly written post… The in-depth research about step by step comparison between ASP NET application development vs RR is really impressive and worth reading!Keep up the awesome work of sharing information so comprehensively.