Kigg - Building a Digg Clone with ASP.NET MVC Part - 1

Published: 2/20/2008
By: Kazi Manzur Rashid

Learn how to develop a Digg-like application with ASP.NET MVC, LINQ to SQL and ASP.NET AJAX.

Introduction

For the last few days, I have been trying to get my hands dirty with the new ASP.NET MVC framework. I saw many discussions on some of the advanced topics like IoC Container/DI, View Engine, Controller factory and so on, but I could not find a simple application to harness the power of the new ASP.NET MVC framework. Certainly, knowing these things is an added benefit but it is not mandatory to develop applications with the ASP.NET MVC Framework. In this article - from the DotNetSlackers team - I will present a basic version of Digg / DotNetKicks kind of application developed with the ASP.NET MVC framework. You will find the whole application running at the following link:

[Live Demo]

Note: The article and code are based on the first preview release of the ASP.NET 3.5 Extensions. We will be updating it as per the new release.

Prerequisites

A brief Introduction to the ASP.NET MVC Framework by Scott Guthrie:

An excellent Screencast by Scott Hanselman.

Overview

The MVC (Model-View-Controller) is a popular pattern to develop UI-centric applications based on a simple concept: divide the implementation into three logical components:

The ASP.NET MVC Framework is an implementation of the MVC pattern, and has built-in support for developing web applications. Let's take a quick look at these three components.

Figure 1: The MVC Framework

images/mvc.jpg

The ASP.NET MVC Framework is an alternate and better way to develop web applications, comparing to the regular web form model. It provides us with:

Request Flow

In regular ASP.NET web form applications, URLs are usually mapped to physical disk files. When a URL is requested, the code of the associated file gets executed, which generates the HTML. However, in the ASP.NET MVC Framework the URLs are tied with the Controllers rather than the disk file. The component that is responsible to map the URL with the Controller is the Routing Handler. When the application starts, it is required to register the URL Routing Rules, which the Routing Handler uses to map the controller when the request arrives. Let's take a quick view of how a request is carried in different layers of the ASP.NET MVC Framework:

Figure 2: The Request Flow

images/request.jpg

Default Conventions

There are few default conventions that we have to know before moving forward.

First, when matching the Controller for the incoming request, the framework uses a pattern UrlPathController to match the Controller. For example, if the request is for http://www.example.com/Home, it will match the HomeController for that request. Once the request reaches the Controller, the Controller executes a specified action from the URL sub-path, or it executes the default action if the action is missing in the URL. The default action for a Controller is specified when the URL Routing Rules are declared in the application start event handler. The actions are declared in the Controller class as methods. For example, if the request is for http://www.example.com/Home/Index, it will automatically execute the Index method of the HomeController; and if the URL contains more sub-paths, it will pass each sub-path as a parameter value of that method.

Next, when creating an ASP.NET MVC Project in Visual Studio, it automatically creates Controllers, Models and Views folders. It is recommended to create the Controllers, Models and Views in the corresponding folders. However, if you are developing a large application you can choose to implement the Model in one or more different projects, but the Controllers and Views must be present in the MVC Project. For each Controller, there should be a folder under the Views with the same name. For example, if we have a Controller named HomeController, there should be folder named Home under the Views folder. If a single view is used by more than one Controller, it should be placed under the Shared folder of the Views. The shared folder can also contain shared User Controls, Stylesheets, JavaScript files and so on.

Philosophy and Functionalities of Kigg

Let us discuss the philosophy of Digg/DotNetKicks kinds of applications before moving to the implementation part. Both of these applications are completely community driven. Members find an interesting Internet resource, they submit it to the application and it appears instantly in the upcoming story queue. Other members can vote it, and once it reaches a certain number of votes, it appears in the front page.

The application will be able to:

Controllers and Actions Defined

When evaluating the Controller Actions, a good technique is to give the action a name similar to its functionality. The following code shows the action methods of the StoryController:

And the following code snippet shows the action methods of UserController:

Note that the Action methods are declared as public and Marked with the ControllerAction attribute. In future versions of ASP.NET MVC the attribute will no longer be needed. Publicly declared method will automatically become the action methods.

Routing Rules Defined

Once the signatures of the Controllers are defined, it is time to declare the URL Routing Rules that will map the URLs to these Controllers' action methods. As mentioned earlier, the Routing Rules must be registered in the application start event handler, in the Global.asax file. When defining the Routing Rules, one thing you have to remember is keeping the most specific rule at the top. It is similar to the try/catch block rule of exception handling, where we put the more general exception at the bottom and specific exceptions at the top. If you open the Global.asax file of this application, you will find that we have explicitly created two methods to register these rules and call these methods in the application start event. The reasons behind creating these methods - instead of registering them in the application start event - are that we do not want to clutter our rules with both newer and older versions of IIS. When hosting an MVC application in IIS7 the URLs are extension-less, which is really cool, but in older versions of IIS the URLs are served with a .mvc extension. So to support both older and newer versions of IIS we need to add the same URL, one with the extension for the older version and another without extension for the newer version of IIS. Here, we are checking the web.config for the hosting IIS version and registering only the rules for that version. Another benefit of having explicit methods for registering the rules is Unit Testing, which we will check in a few moments. The following code shows the Routing Rules Declarations:

As you can see, we are registering the most specific rules like User/Login, User/Signup, Story/Detail, Story/Category first and least specific rules like Story/[action], [controller]/[action] later. When mentioning the variables in the URL format we are using [] to denote the variable. There are two fixed variable names in the MVC framework: [controller] and [action]. The others are simply the parameter names of the controller action methods. The last rule, which maps to default.aspx to the all category is required to handle the /.

Test the Routing Rules

Once the Routing Rules and Controller signatures are defined, it's time to test the Rules, which will give us a clear idea on whether the Rules are good enough to map the controller's action and if the correct parameter values are passed for a given URL. The following table shows the test bed of Routing rules that we like to test:

Table 1: Tests

FunctionalityUrl FormatControllerAction
LoginUser/LoginUserControllerLogin
SendPasswordUser/SendPasswordUserControllerSendPassword
SignupUser/SignupUserControllerSignup
LogoutUser/LogoutUserControllerLogout
List All Published StoryStory/Category
Story/Category/[page]
StoryControllerCategory
List Published Stories for a specific CategoryStory/Category/[categoryName]
Story/Category/[categoryName]/[page]
StoryControllerCategory
List Upcoming StoriesStory/Upcoming
Story/Upcoming/[page]
StoryControllerUpcoming
List Stories for a specific TagStory/Tag/[tagName]
Story/Tag/[tagName]/[page]
StoryControllerTag
List Stories Posted By an UserStory/PostedBy/[userName]
Story/PostedBy/[userName]/[page]
StoryControllerPostedBy
Search StoriesStory/Search?q=query
Story/Search/[q]/[page]
StoryControllerSearch
View Details of a StoryStory/Detail/[storyID]StoryControllerDetail
Submit a StoryStory/SubmitStoryControllerSubmit
Vote a StoryStory/KiggStoryControllerKigg
Post a CommentStory/CommentStoryControllerComment

You will find Route.cs in the test projects folder, which is used to test the Routes. We have included both VSTSTest and NUnit implementations of all the Unit Tests. For Mocking, we have used Rhino Mocks. The tests are done based upon the code that Phil Haack blogged few weeks ago in the post Testing Routes In ASP.NET MVC.

Here are few code snippets of the Routing Rule Test:

Implementing the UserController

Earlier, we defined the signature of the UserController. Now it's time to add the actual implementation. The UserController uses the ASP.NET Membership provider for login, signup and similar operations. The only difference between this controller and the others is that all the methods of this controller returns JSON data instead of a regular HTML view. The controller methods are called from the client side using the ASP.NET AJAX Framework. The following code shows the Login method of this controller:

As you can see, we are creating a JsonResult object at the beginning of the method. JsonResult is a simple class which has only two properties: isSuccessful and errorMessage, which denotes if the controller action was successful. If the operation is not successful, it populates the errorMessage with the proper reason. In the end, we are passing the result as view data of the shared view called "Json". Since this is a shared view and it will be used by both UserController and StoryController, we have placed it in the Shared folder under the Views. I am excluding the other methods of this controller as they work almost the same as this. One important thing I would like to mention is that instead of using the static Membership class directly in the code, we are passing the abstract membership provider in the constructor of this controller. The reason behind this is that we can pass a Mock Membership Provider in our Unit Test, which we will check next. And in the other constructor, we are passing the default membership provider, which is configured in the web.config.

Testing the UserController

For testing the Controller, we are also following the same test specific subclass pattern that Phil Haack blogged few weeks ago in the post Writing Unit Tests For Controller Actions. As mentioned in the previous section, we will pass a Mock Membership Provider to test the controller. We will expect that the proper method of the membership provider is called and that the controller is passing correct data to the view. The following code snippet shows how the Login is performed for a successful attempt and how it fails when an empty user name is provided.

Summary

My initial intention was to provide all the details in a single article, but as you can see, the article has already evolved too much to fit in a single part.

In this part, we took a brief overview of the ASP.NET MVC Framework and learned how to assign functionality to controllers, how to define the routing rules and test them against URLs. We have also seen how to create a Controller that returns JSON data instead of regular HTML, and tested the controller. In the next part, we will talk more about the Controller, which renders regular HTML view, using master pages and user controls to create the view, passing strongly typed view data to the view and finally creating the Model. Stay tuned.

Please visit the link at the below url for any additional user comments.

Original Url: http://dotnetslackers.com/articles/aspnet/KiggBuildingADiggCloneWithASPNETMVC1.aspx