Currently I’m building a image gallery component for a website where the user is able to upload images and they are displayed in a gallery using http://pikachoose.com. I have one action on my controller called Download which takes the id of the image that should be downloaded as an argument. It worked fine using this code (in the beginning):

   1: public ActionResult Download(int id)
   2: {
   3:     var image = Repository.GetById(id);
   4:  
   5:     return File(image.Data, image.ContentType, image.Filename);
   6: }

The problem with this code only showed up with some images. The problem is the last parameter to File(), image.Filename. Which is the filename of the original image the user has uploaded. If the filename contains “invalid characters” ASP.NET MVC throws this exception:

[FormatException: An invalid character was found in the mail header.]
   System.Net.Mime.MailBnfHelper.GetTokenOrQuotedString(String data, StringBuilder builder) 
   System.Net.Mime.ContentDisposition.ToString() +270
   System.Web.Mvc.FileResult.ExecuteResult(ControllerContext context) +164

 

The part that confused me was “in the mail header”. Suppose they’re reusing some mail component for mime parsing. To fix it I only had to make sure that the filename didn’t had any invalid characters, I did it by setting it to the filename I use on the server instead of the filename submitted by the user.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

In one of my recent projects using ASP.NET MVC (updated to RC2) I was going to use Fluent NHibernate. While using Fluent NHibernate I also needed Castles NHibernate Facility for session management, which would simplify the management of sessions in the repositories in the project. It wasn't as easy as I'd hoped to get it all running smoothly.

EDIT: I’d recommend you to use Sharp Architecture (http://code.google.com/p/sharp-architecture/) which is a project template complete with nhibernate+automap, castle windsor and a bunch of other useful things.

1. Castle binaries

First off, get the latest (trunk) Castle binaries from their build server (or build it yourself). You'll need something later than RC3 (which is the version that's available for download as a release) since the IConfigurationBuilder wasn't public before and there was no way of defining a custom configuration builder which we will leverage to be able to hook into the configuration and making sure that automappings are used.

2. Create custom configuration builder

Based upon this excellent post by Mike Hadlow we're creating a custom configuration builder. This is where the magic from Fluent NHibernate comes into play as well.

   1: public class FluentNHibernateConfigurationBuilder : IConfigurationBuilder
   2: {
   3:     public NHibernate.Cfg.Configuration GetConfiguration(IConfiguration facilityConfiguration)
   4:     {
   5:         var defaultBuilder = new DefaultConfigurationBuilder();
   6:         var configuration = defaultBuilder.GetConfiguration(facilityConfiguration);
   7:         
   8:         configuration.AddAutoMappings(AutoPersistenceModel.MapEntitiesFromAssemblyOf<Headline>());
   9:  
  10:         return configuration;            
  11:     }
  12: }

The method AddAutoMappings() on line 8 does all the magic, it's an extension method from Fluent NHibernate which will wire up the normal automappings from Fluent NHibernate. If you want to use the normal Fluent Nhibernate way with manually mapping entities there's a method called AddMappingsFromAssembly() which you should use instead.

3. Setup HttpModule for Castle NHibernate integration

Since we're using Castle NHibernate facility in a web environment we're going to use their httpmodule for managing sessions as well. If you don't manually set it up correctly you will run into issues like "no session or session was closed" with lazy loading when the session is closed. For example if the view is iterating over a list of objects which are supposed to be lazy loaded. With this HttpModule it will take care of it and setup a session per request.

The <httpModules> section of the web.config looks like this with the addition of the new NHibernateSessionWebModule:

<httpModules>
      <add name="ScriptModule" 
           type="System.Web.Handlers.ScriptModule,
                 System.Web.Extensions,
                 Version=3.5.0.0,
                 Culture=neutral,
                 PublicKeyToken=31BF3856AD364E35"
       />
       <add name="UrlRoutingModule" 
            type="System.Web.Routing.UrlRoutingModule,
                  System.Web.Routing,
                  Version=3.5.0.0,
                  Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35"
       />
       <add name="NHibernateSessionWebModule" 
            type="Castle.Facilities.NHibernateIntegration.Components.SessionWebModule,
                  Castle.Facilities.NHibernateIntegration"
       />
</httpModules>

4. Initialize the container

Do something like this in the Application_Start in your HttpApplication class (usually global.asax.cs). The line number 7 sets the controller factory from the mvccontrib project as the default. This means that the controllers will be resolved by castle windsor and all dependencies will also be resolved from the container.

   1: IWindsorContainer container = new WindsorContainer();
   2:  
   3: // Configure the container either by the ordinary config file with XmlInterpreter
   4: // or by fluent like this etc
   5: container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>());
   6:  
   7: ControllerBuilder.Current.SetControllerFactory(new MvcContrib.Castle.WindsorControllerFactory(Container)); 

5. Configure Windsor/NHibernate Facility in web.config

First off we add a new <section> to <configSections> in web.config.

<section
  name="castle"
  type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />

The <castle> section  is quite large but we'll break it down.

   1: <castle>
   2:   <facilities>
   3:     <facility id="nhibernate"
   4:               isWeb="true"
   5:               type="Castle.Facilities.NHibernateIntegration.NHibernateFacility,
   6:                     Castle.Facilities.NHibernateIntegration"
   7: configurationBuilder="Incendi.Configuration.FluentNHibernateConfigurationBuilder, Incendi">
   8:         
   9:       <factory id="nhibernate.factory" >
  10:         <settings>
  11:           <item key="show_sql">true</item>
  12:           <item key="connection.provider">NHibernate.Connection.DriverConnectionProvider</item>
  13:           <item key="connection.driver_class">NHibernate.Driver.SqlClientDriver</item>
  14:           <item key="dialect">NHibernate.Dialect.MsSql2005Dialect</item>
  15:           <item key="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=Incendi;Integrated Security=True</item>
  16:           <item key="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</item>
  17:         </settings>
  18:       </factory>
  19:         
  20:     </facility>
  21:   </facilities>
  22:   <components>
  23:     <component id="GenericRepository" type="Incendi.Repositories.Repository`1, Incendi"/>
  24:   </components>
  25: </castle>


On line 4 we tell NHibernate Facility that we'll we using it in a web environment so it can use a special sessionstore for this purpose. Line number 7 indicates that we are specifying a custom configuration builder, which is the one we created in step 2. Make sure the namespace.class, assembly is correct. If you miss this you'll get a not so informative error "classType must be set". Next is the factory where we specify the configuration (if you want some in web.config, in my case I needed the type and connectionstring in the web.config and not specified by Fluent NHibernate since I switch it to SQLite when testing.

Note: I had to add line number 16 after upgrading NHibernate to 2.1

As you can see in the <components> section I've also registered a "GenericRepository" class. This is my base generic repository Repository<T>. There are lots of generic repositories out there, look at Rhino.Commons for example. It's quite easy to write one on your own as well.

6. Using SessionManager from NHibernate Facility in the repository

By setting up NHibernate Facility and retrieving the repository from Windsor which will inject the SessionManager into the Repository. It's now just as easy as calling OpenSession() on SessionManager to get a session. Below is an excerpt from the generic repository I wrote and use in the application to show you how easy it is when you don't need to worry about session management.

   1: public class Repository<T>
   2: {
   3:     private readonly ISessionManager _sessionManager;
   4:  
   5:     public Repository(ISessionManager sessionManager)
   6:     {
   7:         _sessionManager = sessionManager;
   8:     }
   9:  
  10:     public virtual IList<T> GetAll()
  11:     {
  12:         using (var session = SessionManager.OpenSession())
  13:         {
  14:             return session.CreateCriteria(typeof(T)).List<T>();
  15:         }
  16:     }
  17:  
  18:     public virtual T Get(int id)
  19:     {
  20:         using (var session = SessionManager.OpenSession())
  21:         {
  22:             return session.Get<T>(id);
  23:         }
  24:     }
  25: }

 

7. Putting all of it to use with the controllers

For example, I’ve added a UserService component to the castle windsor container which implements IUserservice. The UserController requires a IUserService in the constructor. This dependency will be resolved by castle windsor automatically thanks to the controller factory.

   1: public class UserController : Controller {
   2:     private readonly IUserService _userService;
   3:  
   4:     public UserController(IUserService userService) {
   5:         _userService = userService;
   6:     }
   7: }

Phew, that's a lot of configuration to get it up and running. I hope I didn't forgot anything, drop me a comment if you're having trouble setting it up. Good luck!

Currently rated 1.0 by 2 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

I've been trying to configure custom error pages for my web application using [HandleError] attributes. While trying to configure my application I've noticed a few things which I thought I should share, which weren't obvious, for me at least.

HandleError is meant to be a way to specify a view to display when a specific exception is thrown. In my case I wanted a "permission denied" view to be displayed when an user didn't have the correct permissions to view/invoke an action on a controller.

So far I've noticed these things:

CustomErrors in web.config must be Off

For the HandleError attribute to intercept the exception the customErrors config value in web.config must be set to Off. Otherwise the exception message and complete stack trace is shown and not the custom view.

Ordering of attributes

The order of the attributes you specify on your controller impacts the way ASP.NET MVC chooses the view to display. For example:

   1: [HandleError]
   2: [HandleError(View = "PermissionDenied", ExceptionType = typeof(PermissionDeniedException))]
   3: public class OCABController
   4:     : Controller
   5: {
   6:     public ActionResult test()
   7:     {
   8:         throw new PermissionDeniedException();
   9:     }
  10: }

The result of the PermissionDeniedTest() method would be that the ASP.NET MVC would display the "PermissionDenied" view. Any other exception and the default "Error" view would be displayed.

The problem is that if you change the order the attributes are specified. For example:

   1: [HandleError(View = "PermissionDenied", ExceptionType = typeof(PermissionDeniedException))]
   2: [HandleError]
   3: public class OCABController
   4:     : Controller
   5: {
   6:     public ActionResult test()
   7:     {
   8:         throw new PermissionDeniedException();
   9:     }
  10: }

Then the default "Error" view would be displayed, just because the order of the HandleError attributes is different.

Don't throw exceptions that would result in an non-HTTP 500 error code

My first attempt for displaying a "PermissionDenied"-view when a user tried to perform something which he didn't had the permission for was to throw an UnauthorizedAccessException. While just trying this out I couldn't get the HandleError attribute to pick up the exception. None of the HandleError attributes picked up the exception and displayed a custom error page. Instead it gave me the call stack and exception message. While debugging the ASP.NET MVC code to try to figure out why it didn't display a custom view I found the answer in HandleErrorAttribute.cs.

   1: // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
   2: // ignore it.
   3: if (new HttpException(null, exception).GetHttpCode() != 500) {
   4:     return;
   5: }

 

Basically it means that any exceptions that would case a non-HTTP 500 error is ignored.

It's possible to decorate a base class with [HandleError]

I've created a base class which inherits from the Controller class. All my controllers inherit from my base controller. This way I can control some common decisions. One of those is which view gets displayed for which exception. In my case I just need to display a "PermissionDenied"-view when a user tries to do something he doesn't have permission to do. Using IAuthorizationFilter to throw a PermissionDeniedException when an user tries to do something which he lacks the permissions to do and setting up an HandleError attribute in my base class with the ExceptionType = typeof(PermissionDeniedException) I can remove some duplicated code and be sure that each Controller behaves the same way.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

As my last post suggested, there is a problem (or bug) in ASP.NET MVC RC1 when adding model errors with AddModelError(string key, string errorMessage) without calling SetModelValue(string key, ValueProviderResult result). Failing to use SetModelValue() to set a value will result in a NullReferenceException with some HtmlHelpers.

A reply on a thread at the asp.net forums by a member of the ASP.NET team:

If you have a custom binder that calls AddModelError() without calling SetModelValue(), the HTML helpers will sometimes throw a NullReferenceException when you try to use them.  The reason is that a call to AddModelError() without a call to SetModelValue() doesn't really mean anything.  Consider that model errors are due to the user submitting bad form data, and by using the HTML helpers you're implicitly telling us that you want them to redisplay the user's invalid submitted form data, but the binder never told us what the bad data was!  It only gave the helpers half the data necessary to render themselves properly; it told them that there was an error, but it didn't provide the expected old value.

Obviously it's not really desirable behavior for us to throw this exception.  We're looking into ways to address this, but choosing an answer isn't as trivial as it seems.  We could silently fall back to a blank value, we could throw a different exception, etc., but in any case we're going to confuse and irritate developers who wrote custom binders and wonder why the users' bad values aren't being propagated between requests.

I've three issues with this. First and foremost the way the AddModelError() and SetModelValue() are linked together, the AddModelError() method wont work if the other method is not invoked and vice versa smells bad to me. It's like setting up an object with a constructor that will create an object in a state where it still needs more data to be functional. My suggestion to fix this issue would be to add another argument to the AddModelError() method, containing the attempted value. This way it's not possible to "forget" to call the SetModelValue() method.

My second issue is the rename of the method from SetAttemptedValue() to SetModelValue(). I dont think the name of the method express it's intent very well. The SetAttemptedValue() is much more clear on what its used for.

The third issue I have is the arguments to the SetModelValue() method.

void SetModelValue(string key, ValueProviderResult result)

The second argument is a ValueProviderResult object. Which has the following constructor:

ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture)

My issue here is the first argument, object rawValue, what's this? Looking through the source code to ASP.NET MVC RC1 revealed that it's the value that gets converted to a string and then displayed by the HtmlHelpers. The string attemptedValue doesn't get used in that scenario, it only has a few usages in the ASP.NET MVC source code.

In the project I'm currently working on I've created an extension method to the ModelStateDictionary to ease the use of adding a model error. It looks like this:

  1: public static void AddModelError
  2:   (this ModelStateDictionary modelState, string key, string errorMessage, string attemptedValue)
  3: {
  4:   modelState.AddModelError(key, errorMessage);
  5:   modelState.SetModelValue(key, new ValueProviderResult(attemptedValue, attemptedValue, null));
  6: }
This way it's a little bit easier to work with the ModelStateDictionary.AddModelError/SetModelValue methods.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

As my last post indicated, I wasn't sure where SetAttemptedValue on ModelStateDictionary had gone, or what has replaced it. With a little bit of experimenting I noticed that if I used the SetModelValue method, which I suspect is new with 1.0 RC, it would display the input that failed to validate. Which pretty much behaves the same way it was before with SetAttemptedValue(string key, string value). However, there is one difference, if I don't use the SetModelValue I'll get a NullReferenceException from MVC. Before it just displayed the default value. Looking in the source code for MVC 1.0 Release Candidate and Beta 1, I noticed it's been through a major refactoring.

Before in Beta 1, it used the following code to get the attempted value:

string attemptedValue = htmlHelper.GetModelAttemptedValue(name);

And uses the attemptedValue as value for the textbox in my case. Displaying the input the user tried to enter.

However, in 1.0 RC it's gone. Instead it tries to get the value from the model state with the following method:

internal object GetModelStateValue(string key, Type destinationType) {
ModelState modelState;
if (ViewData.ModelState.TryGetValue(key, out modelState)) {
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
return null;
}

Debugging the application shows the error, the ViewData.ModelState contains the key and returns true. The modelState variable however only contains the list of ModelErrors in Errors (which contains 1 error). The Value is unfortunately null. Which of course will be a NullReferenceException when trying to use

modelState.Value.ConvertTo(destinationType, null)

Probably I've just missed this change in the documentation and it's always been mandatory to set the value in the modelState, but it really shouldn't throw a NullReferenceException.

[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) in ...   
System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType  ...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

So, I just installed the new ASP.NET MVC release (see Scott Gu's blog) and updated my project which was based on beta 1. In the release notes there were some information about how to upgrade, although I somehow managed to screw it up so I got "HtmlHelper does not contain RenderPartial" error messages. The issue I had was that I messed up the namespaces in the web.config. To see how it should be just create a new ASP.NET MVC project and compare the web.config with your current web.config.

There has been a change to the ModelBinder API which produced compilation errors, the ModelBinderResult class seems to have been removed and the BindModel() method now takes two arguments of type: ControllerContext and ModelBindingContext. The ControllerContext contains among other things the HttpContext. The BindModel() method doesn't remove the ModelBinderResult anymore, instead it returns object. That change seems a bit weird, but I'm sure it was done with a lot of consideration.

There was another breaking change for me which had to do with the ModelStateDictionary. The method SetAttemptedValue(string key, string value) is removed? I'm not sure if it's been replaced by the method SetModelValue(string key, ValueProviderResult result), I can't find any information about it in the release notes.

What I did find in the release notes however was the improved support for file upload, just in time for me to begin implementation of a an upload document and image feature for the web application I'm currently building.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

This blog is hosted by Surftown which is a cheap and pretty decent shared web host. I've been looking for some sort of CMS to do simple web sites, I've had requests from a few of my friends if I could help them set up a web site. Sure, no problem. However, I'm looking for something that could be sort of a framework I could build all these sites on, which I could customize to fit my needs. I started looking at Umbraco (www.umbraco.org) which looks really good, but unfortunately does not work with medium trust. Found Cuyahoga(http://www.cuyahoga-project.org/) which also was very promising but with the same problem, no support under medium trust...

With the simple requirements I have it's more or less no point to look and evaluate another CMS, I could just as easily build one myself. While building it I could use some ASP.NET MVC which I really enjoy and hope to dig into a bit more. But, a few questions remained. Does Surftown support .NET 3.5? Does ASP.NET MVC need full trust? I was pretty sure ASP.NET MVC didn't need full trust to operate. But would it work on Surftown?

I created the sample project in Visual Studio 2008 and published my site to a subdomain to see if it worked. The first I received was the 404 not found when browsing /Home. Fair enough, changed the route to be /Home.aspx instead. It looks like ASP.NET but atleast you'll know it's not the traditional ASP.NET. Voilá, it worked. Best news I've had all day, now to do a simple CMS... how hard could it be?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

After installing Visual Studio 2008 SP1 I started to get weird crashes while trying to view aspx markup in ASP.NET MVC Preview 5 projects. The IDE would just disappear without any error messages. I tried rebooting my machine, but it didn't help. I looked in the event log and found this message:

.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (6EF35E00) (80131506)

Not very informative but at least something use when searching the web. I found a few posts with this error message, some posts had tips on how they solved the issue. I tried to clearing out my temp folders

  • c:\windows\temp
  • c:\users\<user>\appdata\local\temp
  • c:\windows\microsoft.net\framework\v2\temporary internet files

Unfortunately that didn't resolve the issue, Visual Studio continued to crash.

Since I had installed the Silverlight 2.0 Tools and SDK recently I figured it might be cause of the problem. Uninstalled it and rebooted the machine but to no avail. I started to look through the programs I had installed, trying to find anyone that could cause the problems. Among a few tools I've installed were PowerCommands for Visual Studio 2008. Uninstalling it solved the issue. Very weird, I hope it gets fixed soon. PowerCommands is great and I hope to be able to install it soon again.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Following the Evaluating a move from Monorail over to ASP.NET MVC post, I started to dig deeper into the authorization mechanism in ASP.NET MVC. There were some core differences, in ASP.NET MVC they had taken a step further with authorization and created a specific filter Authorize implementing the IAuthorizationFilter interface. This enables you to specify users and roles that are authorized to invoke a certain action on a controller. For example if you require that only users in the "Administrators" role are allowed to invoke Index() it would like this:

Authorization filter in ASP.NET MVC

Where you decorate the controller with a special [Authorize(Roles="Administrators")] filter attribute. This [Authorize] filter would check the user before invoking the Index() method. If the user did not had the specific role it would output an error. If the user is not logged in it would be redirected to the login page etc.

This is very nice, you can do the same in Monorail since filters exists in both ASP.NET MVC and Monorail. However, in Monorail you had to specify that the filter would be executed before the action is invoked and there is no special treatment for the filter. It's treated just like any other filter. In my application it looks like this (the selected line):

Authorization filter in Monorail

You explicitly has to specify that the filter should be executed before the action, it wouldn't make much sense otherwise for an authorization filter, if it would be invoked after the action has been executed. To make sure that you don't miss this they specifically created an interface IAuthorizationFilter which always will be executed before any action. Personally I really like this approach, this way you won't accidentally forget to specify it should be executed before any action.

So far so good, in ASP.NET MVC there's no need to explicitly specify it should be executed before and there's no question about what the filter does, just read the name of the filter. Unfortunately, since the Authorize filter in ASP.NET MVC only works with users and roles I either has to change my Monorail authorization and permission scheme or implement a new feature in ASP.NET MVC. In my application I do not specify Users or Roles in the application, instead I use permissions after a suggestion from Christer. I must say it's been great, the system feels a lot more flexible when I can define different permissions. For example my job advertisement controller has five actions: Create, Update, Delete, Read and Approve. Which gets translated into five different permissions CreateAdvertisement, UpdateAdvertisement, DeleteAdvertisement, ReadAdvertisement and ApproveAdvertisement. The actions on the controller are decorated with the suitable permission. This way I can manage the permissions so that any user can read advertisements. Any logged in user can create and update their own job advertisement. Only administrators can approve new job advertisements and delete existing advertisements. In the administration view it's possible to change these permissions.

permissions3

Of course, this can be done using roles only. Hard coding in roles into the application. But this way, there's another layer of abstraction which hopefully doesn't need to change after all permissions are specified. Another advantage using this permission approach is that whenever you need to add another role to the system you only need to specify it and then go into the administrations view and determine which rights the role should have. No need to browse through each action for each controller in the system, and hoping that you didn't miss any.

Fortunately, the team behind ASP.NET MVC has made it super easy to just create a new authorization filter. All you need to do is create a class that implements the IAuthorizationFilter and inherits from the FilterAttribute class (actually, I'm not sure it needs to be derived from the FilterAttribute class). For example I created the RequirePermission attribute, which implements the IAuthorizationFilter. The only method in IAuthorizationFilter is the void OnAuthorization(AuthorizationContext filterContext). After that I could decorate my Delete() method with the new AuthorizationFilter: RequirePermission.

permission4

Which would enable the system to verify the role of the user against the relation between role and permission.

I must say that ASP.NET MVC has made some progress regarding authorization, comparing to Monorail. They are almost implemented identically, however there are some subtle differences that makes a huge difference in my opinion. It's impressive how easy it is to implement new filters in ASP.NET MVC.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

I started building a web site for my father a few years ago, back then I based it on PHP/MySQL. After some time I discovered Ruby on Rails and rebuilt most of the system using RoR, although I didn't complete the project for a few reasons (not going into detail here). Late 2007 I started to thinking about rebuilding it and leaned toward using .NET. I was thinking I could use it to try out some new technologies in .NET that I hadn't used yet. I'm not a big fan of ASP.NET, so using traditional ASP.NET was out of the question. Since I'm used to PHP and using POST/GET and reading query strings etc I feel that ASP.NET actually confuses developers with postbacks, events and viewstates causing all sorts of problems. Another issue of ASP.NET is the testability, it's cumbersome to write unit tests for ASP.NET applications, it's possible for example using a Model-View-Presenter (MVP) pattern.

Looking for another web framework to use I found Monorail, which is a MVC framework by Castle Project inspired by ActionPack. It's built on top of ASP.NET but, everything gets routed to an action on a controller. I also discovered ASP.NET MVC, however, it was so early that it felt like it changed a lot between every preview, big breaking changes which would meant fixing a lot of code whenever upgrading to a newer preview. That's way I settled with Monorail for the time being.

The web application that was built had the following features

  • Membership (Users, groups and permissions)
  • CMS (pages and menus)
  • Questionnaire
  • Create conference and have members registering to attend
  • Create, send as PDF and manage invoices (the sum of the invoices for the last conference was close to $350 000)
  • Post job advertisements
  • Forum

The web framework used was Monorail and for data access I used NHibernate with ActiveRecord, which made my life so much easier. It's incredible powerful to be able to re-create the database with just a command and be able to switch between different databases by only changing the configuration. At one time I developed the application on my development machine which had a SQL 2005 server and I deployed to a MySQL server and it worked right out of the box. I used the ability to destroy and create the database a lot when creating integration tests. No need to try to reset the database to a specific state, now I was confident that everything was exactly the same each time I ran the tests. The database got swiped and created between each test. There's also the possibility to use an in memory database such as SQLite for performing integration tests, since it only resides in memory it's incredible fast.

I'm pretty pleased with the outcome of the system, it's working great and it's easy to add new features. But, I'm like many of you, I always want to try new things and learn more. Now when ASP.NET MVC has had almost a full year of development since I last visited it I feel like it's time for doing another re-build of the system. This time I'm hoping to be able to re-use some of the business logic and a lot of the data access layer since I'm still going to use NHibernate. I know Entity Framework (EF) has been released, but it's lacking a lot of features and is at the moment inferior to NHibernate. I'm sure it will turn out great when version 2 is released of EF, and I'll probably replace the data access layer when it's out :)

Looking through the code for the web application today trying to look for what needs to be replaced when moving over to ASP.NET MVC from Monorail, it feels like it's not really that much that needs to be changed. I could use a NVelocity view engine keeping the views more or less intact. The data layer is the same and since I wrapped everything in services the controller does not really contain a lot of logic, it'll certainly help. However, obviously there are some core differences between Monorail and ASP.NET MVC. I'm going to go over the issues I encounter one by one as I browse through the code looking for certain perks that needs to either be rewritten in ASP.NET MVC or could just be moved over simply by renaming some classes etc. I'm really looking forward to try out the new features in ASP.NET MVC that I haven't looked at yet, particularly that controller action is not void anymore, instead they return an object. This will make unit testing so much easier.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5