First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

October 2009 Blog Posts

12 ASP.NET MVC Best Practices

Last week I held two presentations about ASP.NET MVC for the new-born DotNetRomaCeStà user group in Rome. And one of them was about what I consider to be ASP.NET MVC Best Practices. The presentation was in Italian so I decided to translate my slide in English so that everybody can read them.

Controller’s best practices

1 – Delete the AccountController

You will never use it and it’s a super-bad practice to keep demo code in your applications.

2 – Isolate Controllers from the outside World

Dependencies on the HttpContext, on data access classes, configuration, logging, clock, etc… make the application difficult (if not impossible) to test, to evolve and modify.

3 – Use an IoC Container

To make it easy to adhere to Best Practice #2, use an IoC Container to manage all that external dependencies. I use Ninject v2, but there are many around, and it’s easy to build your own if needed.

4 – Say NO to “magic strings”

Never use ViewData[“key”], but always create a ViewModel per each View, and use strongly-typed views ViewPage<ViewModel>.

Magic strings are evil because they will never tell you whether your view is failing due to a misspelling error, while using a strongly-typed model you will get a compile-time error when there is a problem. And as bonus you get Intellisense.

5 – Build your own “personal conventions”

Use ASP.NET MVC as a base for your (or your company’s) reference architecture. Enforce your own conventions having controllers and maybe views inherit from your own base classes rather then the default ones.

6 – Pay attention to the Verbs

Even without going REST (just RESTful) use the best Http Verb for each action. Adopt the PRG Pattern (Post-Redirect-Get): show data with GET, modify data with POST.

Model’s Best Practices

7 – DomainModel != ViewModel

The DomainModel represents the domain, while the ViewModel is designed around the needs of the View, and these two worlds might be (and usually are) different. Furthermore the DomainModel is data plus behaviours, is hierarchical and is made of complex types, while the ViewModel is just a DTO, flat, and made of strings. To remove the tedious and error-prone object-mapping code, you can use AutoMapper. For a nice overview of the various options I recommend you read: ASP.NET MVC View Model Patterns.

8 – Use ActionFilters for “shared” data

This is my solution for the componentization story of ASP.NET MVC, and might need a future post of its own. You don’t want your controllers to retrieve data that is shared among different views. My approach is to use the Action Filters to retrieve the data that needs to be shared across many views, and use partial view to display them.

View’s Best Practices

9 – Do NEVER user code-behind


10 – Write HTML each time you can

I have the option that web developers have to be comfortable writing HTML (and CSS and JavaScript). So they should never use the HtmlHelpers whose only reason of living is hiding the HTML away (like Html.Submit or Html.Button). Again, this is something that might become a future post.

11 - If there is an if, write an HtmlHelper

Views must be dumb (and Controllers skinny and Models fat). If you find yourself writing an “if”, then consider writing an HtmlHelper to hide the conditional statement.

12 – Choose your view engine carefully

The default view engine is the WebFormViewEngine, but IMHO it’s NOT the best one. I prefer to use the Spark ViewEngine, since it seems to me like it’s more suited for an MVC view. What I like about it is that the HTML “dominates the flow and that code should fit seamlessly” and the foreach loops and if statements are defined with “HTML attributes”.

Download the slides and demo

Both the slides and the demo code are available for download. Or watch it here:

Which other Best Practices would you suggest?

The 12 above are what I consider basic practices that everyone building ASP.NET MVC applications should adopt. Do you think there are other must-have practices for developers building ASP.NET MVC applications? Please say it in the comment section below.

One last note: in May Sebastien Lambla had a talk about his ASP.NET MVC Best Practices for the VistaSquad user group in London. His talk was very inspiring and stuck into my mind, and it inspired both my ASP.NET MVC projects and my talk as well. So I want to give credit to Sebastien’s talk for having inspired me, and that talk. If you are interested you can download his slides from the Developers Developers Developers event in Scotland.

10 resources to learn Moq

Last week I described the stack I’ll be using to develop my new ASP.NET MVC project, and I said I was going to use RhinoMocks as mocking framework. Well, it later turned out that some tests were using RhinoMocks but most of them were using Moq and “Il Maestro” decided that the latter would be the mocking framework of choice. I never used it, so I started looking for some documentation online. And here I’m listing the best 11 links about Moq.

As you see there are only 9 links in the list: which other link would you recommend as 10th link?

Tags: ,,

31 Days of Refactoring eBook

This August, Sean Chambers, blogger on Los Techies, wrote an awesome series of posts, called 31 Days of Refactoring, during which he wrote one post per day, describing one refactoring technique.

In August I was on holiday, and I never had time to read the 31 posts, so last week I decided to create a easy to read version of the series, and I assembled a eBook, putting together all the posts, doing some minor edits, and applying some formatting. And I sent it over to Sean so that he could share it with all his readers.

You can read Sean’s announcement or directly download the 31 Days of Refactoring eBook.

Hope you like it.

My ASP.NET MVC stack and why I chose it

In my current project I'm starting to develop a new web application using ASP.NET MVC and given all the environmental conditions, choosing the stack, from the tools to the libraries was not an easy task. I had to come to a few compromise to cope with all the different "forces" involved, so I though it would have been a good idea to share my reasoning and the final decision to show an example how an architect that works in "normal" company (as opposed to HeadSpring and such kind of on-the-edge companies) has to balance between what is the best possible option (but sometimes not feasible) and what is the option that is good enough but feasible.

The facts

In order to understand the decision is important to understand what the application is and how (and by who) it is going to be developed.
Without going into the details, the application is mainly a dashboard that manages and monitors the performances and health of an application server. What it will do is retrieve data from the main application server (either via reading the "main" DB or by calling some web service), visualize them in an easy to read and understand manner, and do some quick maintenance and management of the system like restarting, stopping and changing some of the configuration parameter.
Another important fact is the team that will be developing the application: it will be me and a few junior developers with a 1-2 years of experience of developing in .NET and very little (if not nil) in developing web applications.
And finally, the main application is a mix of Java, .NET and COBOL and the team already has source control and a kind of build server that performs nightly builds and deploys to a test environment.

The stack

Now that I made the environment clear, let's review the stack and why I choose each piece of it. Starting from the tools.


Visual Studio 2008 + Resharper

That was kind of an obvious choice: we are building the software with ASP.NET MVC, the .NET 3.5 and I'll try to introduce the team to a more agile way of developing software, so ReSharper, with all the refactoring tools, will make the life easier.


As I said, the IT of the client already has a source control system in place, and it is Subversion, so we'll go with it.


The client's team is mainly a Java oriented team, so they setup all the build server using java tools: they used Maven to build the projects and used Hudson to schedule the builds. I always used NAnt, MsBuild, TFS and CC.NET but since they already had all this place, I had to go with that. But it turned out to be a good thing: it seems like Hudson is probably the best CI server out there at the moment, and also has a lot of .NET related plugins. So this is turning out to be an opportunity to learn a new thing.

The libraries

Let's see something probably more interesting: the libraries used.


I don't think I'll ever go back to starting a new web project using Webforms (unless forced to). But even without my love for the framework I probably would have chosen ASP.NET MVC anyway. A dashboard is the kind of application ASP.NET MVC shines in: very little editing of data, and a lot of data rendering, visualization and ajax things. For that reasons I decided to stay with the released version 1.0 instead of going with v2 Preview 2: I don't have many pages and I don't need to separated the controllers and views into areas, and I don't have so many editing forms to need the Templated Helpers and the integrated ModelValidation.

Custom Data Repository with Linq2Sql

As said, there is not a lot of editing to do. Furthermore the dashboard is going to connect to a legacy database, designed in a really (and I mean really really) strange way, and unfortunately I've no jurisdiction over it. So custom repository with manual mapping is the way I decided to go. Furthermore the developers in the team are not familiar with an ORM. Actually they are not familiar with IoC, MVC, HTML+Javascript and writing tests neither. I didn't want to flood them with all that many technologies and practices all together. So I thought that ORM was the one I could skip for that project.

Enterprise Library and Unity

I always used Ninject for IoC, and Elmah for the logging, but Avanade is the company that wrote the first version of the Enterprise Library and it's part of the internal development framework. But after all the EnterpriseLibrary is not that bad, and this way I have the chance to play around with Unity and maybe find a way to study the validation application block in order to make a client side validation provider on top of it.


Even if we won't have a lot of entities to deal with, AutoMapper will save us from writing boring mapping code. And will help the team to understand better the importance of having a model specific to each view and to keep the domain model separated by the view model.


WebForm View Engine holds too many connections with the WebForm's world so I don't like using it. Furthermore the developers of the team are not familiar with ASP.NET and very little with HTML/CSS, so I thought that Spark is a better solution since it is pure HTML with little customization compared to WebForm. And finally it will prevent developers from breaking the pattern including server controls with data logic in them.


There was a bit of talking about whether using ASP.NET Ajax or jQuery, but at the end we opted for the latter. The reasons for this decision are various: we are using Spark instead of the WebForms ViewEngine, jQuery has a much bigger "add-on" ecosystem and in particular it has the jqGrid which by itself justifies the adoption of jQuery, and then the guys of the team heard about it and wanted to learn more about it.

jQuery UI

Tabs, datatime pickers, modal dialogs are all part of the Ajax Control Toolkit, but what the jQuery UI has is the unified theme: with just one line of configuration all your UI controls will look the same. And since we choose for jQuery, the ACT has never really been an option.


We have to implement a few grids that need to support sorting and paging: I already used this plugin before, and it's both easy to setup and very powerful. You can browse some samples and the documentation here.


We won't have many complex editing screens, just a one or two, but xVal is really easy to implement and I think it's worth adding it even if there is just one field to validate.


We are not going to do TDD (or maybe we will, let's see how the team goes first) but for sure we will write unit tests and we'll try to test the most important features.


Even if I prefer mbUnit, the rest of the solutions is already using MsTest so, even if it's not my preferred testing framework, we'll go with that.


Fortunately the other tests are already using this great mocking framework, which is also the one I used the most and that I prefer, so all good on this side.

The result

Even with some restrictions, I think we ended with an application stack that is pretty close to what I'd have considered the best possible. Now the fun begins, and we'll see if the team will find MVC, jQuery and Spark easy to learn and to use. I'll keep you posted, and when the project ends I'll write a post sharing what was the experience of the team with the new stack and which problem we encountered.

Shout it kick it on

Twitter is crowdsourcing the translation to Italian, and I’m part of it

This news it’s a few days old, but if you hadn’t heard of it yet, Twitter is going to be available in more languages: not only English and Japanese, but also Italian, French, German and Spanish. The cool thing is that the interface is not being translated by a team of professional translators but by a selected number of users. And I’m happy to have been invited to help the translation of Twitter to Italian (notice the “Translator Badge” at the top right corner of my profile page on Twitter).

There are many considerations that can be done about this project, from different point of view.

The business side

First of all this will help Twitter spread more in non English-speaking countries like Italy. Since Facebook was translated in Italian, the number of Italians on Facebook grew exponentially (there are now 18 millions of Italian on Facebook, 1/3th of all the Italians). So probably the same will happen with Twitter as well.

The social side

Then another interesting thing is that they are exploiting the community of users, using the approach called Crowdsourcing, which is outsourcing the solution of your problem not to an external contractor but to a “crowd”. This concepts is already widely adopted in the online communities. There are many advantages in this approach, the most of important being the fact that many people can collaborate to create the best translation possible, without the usual “weird” translations that we see in localized software.

If you are interested in helping, you can ask to become a volunteer. And you can even volunteer to translate to a different language that it’s not being translated yet, like Farsi or Danish.

Another point of interest is how they shared the effort among the volunteers: they didn’t. Everyone can translate everything and when there will be enough translations, the more frequent will be the official ones. And probably other volunteers will be invited later to help evaluate the best translations.

The tech side

Let’s go to the technology side of things. The application they developed to translate the site is great: it’s not the usual list of placeholders and English sentence, but it is a very nice visual UI, with a textbox that appears inside a tooltip pointing to the text to be translated, on the actual page. There is a nice video on YouTube that shows how Twitter translate works.

It would be cool if they could opensource the translation application to help other developers localize their own apps using the same crowdsourcing approach.

Finally it’s funny to have a look at how Twitter developers organized the strings of text: like all the application we develop to be localizable, there are many “placeholders” for the same text, or sometimes you find hardcoded strings (like “5 minutes ago” where you can translate ago, but not minutes).But I’m pretty sure all these small issue will be addressed in future releases of Twitter.

The linguistic side

Translating from English, especially single terms or short sentences is difficult. Unlike English, many languages have genders, declination of verbs, verbs cannot be transformed in nouns just by adding a –er at the end, or nouns cannot be used also as verbs (like “to message to”). For example “you are followed by” needs to be translated based on the the sex of the user: “sei seguito da” for male and “sei seguita da” for female. And also the term “follower” doesn’t have a counterpart in Italian that doesn’t involve at least 2 words. But we have a great team and are having great discussions, so I’m pretty sure we will come out with a great translation. And if that doesn’t happen, well, you know who to blame for it.

Wrapping up

It’s great to see Twitter exploiting the community to translate it’s UI in different languages, and I’m very proud of being part of this team.

Oops! They did it again, I'm an MVP for another year.

I just came back from a week of vacation in Berlin, and I found out that my MVP award has been renewed for the second year.

I want to keep this post short, so all I'm going to do is say "Thank you" to all the communities that gave me a slot to speak about ASP.NET MVC, to Wrox that let me write a book and to Keyvan for having partnered with me in writing my first book, and to all the friends of UGIALT.NET and ugidotnet.

And then I want to congratulate with all the newly awarded devs of the community, and especially with GianMaria Ricci and Ugo Lattanzi aka Imperugo, which are doing a lot for the Italian .NET community and Ivan Porto Carrero, which started to take part in the Belgian .NET community. They really deserved the MVP award. And then, also a my congratulations go to Sara Chipps.