Posts tagged with asp.net - page 3

Observations on Microsoft MVC for ASP.NET

Anyone who’s tried to develop large complex web sites with ASP.NET has likely run into many problems covering the page and control life cycle, view state and post backs and subsequent maintainability including the difficulty in creating automated unit tests.

Microsoft, taking a cue from the popularity of Ruby on Rails and subsequent .NET related efforts such as MonoRail, are embracing the model-view-controller (MVC) pattern and developing something more suited to web development than WebForms which aimed to make web development as similar to Windows development as possible (despite the major underlying differences in architecture).

The prototype, currently named System.Web.Mvc or Microsoft.Web.Scalene depending on where you look, is headed by Scott Guthrie with both Phil Haack and Scott Hanselman involved (sounds like a dream project and team to be involved with) and a preview release (“drop”) is due within the coming weeks.

Guthrie and Hanselman presented Microsoft MVC at the ALT.NET conference which revealed some interesting details buried in the video, my rough observations and notes based on the prototype they showed follows:

Philosophy

  • Don’t repeat yourself
  • Highly extensible & pluggable
  • Use generics to achieve strong-typing without code generation
  • Good performance, fast enough for large-scale sites
  • Separation of concern for maintainability
  • Clean URLs in and out
  • Clean HTML

Extensible

  • Interfaces used extensively
  • No sealed classes
  • Plug-in points for view engines (e.g. MonoRail’s NVelocity, Brail)
  • Support for Inversion of Control (IoC) engines (e.g. Windsor, StructureMap, Spring.NET)

Compatibility

  • Runs on the .NET 2.0 CLR
  • Some helper classes require .NET 3.5 (extension methods)
  • Normal Request, Response objects (via interfaces for mocking)
  • Does not support postback form runat="server"
  • Supports MasterPages, DataBinding, CodeBehind
  • Existing .aspx’s are blocked using web.config

Visual Studio

  • Solution templates for web project and unit testing
  • Full designer & IntelliSense integration

Flow

  • Route -> ControllerFactory -> Controller -> Action -> ViewEngine -> View

Routing

  • Routes can be defined dynamically and support RegEx URL matching
  • IControllerFactory pops out the required IController
  • Routing is case insensitive by default
  • Support REST, blog engine, Jango style mappings etc. default is /controller/action/parameters

Controllers

  • FrontController style
  • IController exposes:
    • Execute(IHttpContext context, RouteData routeData)
    • IViewEngine ViewEngine property
  • Some implementations available, all with virtual methods:
    • ControllerBase (adds dispatching)
    • Controller (Populate parameters into ViewData["key"])
    • Controller (Populates parameters by making ViewData type T)
  • Attributes
    • [ControllerAction] attribute to expose methods as actions (secure default behavior by not exposing helper methods)
    • Attribute for output caching
    • [ControllerAction(DefaultAction=true)] to override default method of Index

Parameters (to the controller)

  • Automatically parsed where a TypeConverter exists
  • Future versions will support more complex serialization of types
  • Can be nullable – use null coalesce operator for defaults

View Engine

  • IViewEngine
    • IView LoadView(string viewName)
  • Implementations include:
    • WebFormViewEngine

Views

  • IView
    • virtual void RenderView(object data)
  • Implementations include:
    • ViewPage – pick up parameters from ViewData[""] in conjunction with Controller
    • ViewPage pick up parameters from ViewData as type T in conjunction with Controller

HTML

  • Clean HTML generation (have they sorted out the id mangling by MasterPages/INamingContainer?)
  • Static HTML class supports Link, PagingLinks and Url methods
  • Map to action names using Lambda expressions to ensure follows refactoring, e.g. string url – Html.Link<ProductController>(controller =>controller.Edit(4);
  • Is there a way to follow the default action?

Model/data

  • Pagination extension methods extend IQueryable for getting pages of data (skip, limit)
  • Pattern for view-update-view cycle
  • Object property to form field id mapping available and pluggable, allows
    • product.UpdateFrom(Request.Form)

Testing

  • Easy to write tests by using mock objects (request, response)
  • Unit testing framework project (NUnit, MBUnit, xUnit.NET)

Finally

  • What’s with ScottGu’s nametag, can the show’s organizers not afford anything more than a Post It note?
  • What cool software is Scott Hanselman using to do the screen-cast video/zoom/overlay/highlighting?

[)amien

Castle Project & MonoRail concerns

This article is very out of date.

I really want to like MonoRail but I find it difficult to feel the love no matter how much I desire Rails-like features without the scalability issues and unusual syntax/learning curve of Ruby.

Here’s my list of concerns:

Slow release cycle

The current release is 1.0 RC2 which was released November 1, 2006. That’s some 10 months ago and yet we have no RC3 or final release.

Part of the hold-up seems to be trying work out what to include and exclude, which brings me onto my next point…

Abandoning convention over configuration?

One guiding principle behind Ruby on Rails is Convention over Configuration. This means that instead of allowing you to configure everything to the nth degree a single ‘conventional’ approach is taken..

This results in an gentler learning curve with less to configure and is generally part of KISS.

The Castle Project’s take on this philosophy is a little off by providing you with a combination of view engines and IoC interfaces to chose from.

In the case of view engines neither NVelocity or Brail support C# or VB.NET which does mean you need to learn another language for writing your views and loose syntax highlighting and IntelliSense in the process.

If I was prepared to accept all that I might as well switch to Ruby on Rails.

The WebForms view engine supports C# but has a number of limitations and uses what I was trying to get away from in the first place (WebForms).

Ken Egozi has come up with a C# based view engine that avoids WebForms confusingly named AspView.

With Inversion of Control whether you use the Micro-Kernel directly or the Windsor Container wrapper is up to you and I hope you figure out which to use better than I did.

Castle Project web site

Looks good however needs better maintenance/management:

  • Wiki contains spam (FAQ, Tutorial, Tips and Tricks etc.)
  • Samples download returns a 404 not found
  • Enabling Inversion of Control is an empty stub yet is linked from the main intro page

I couldn’t find anything about how navigation/site maps are managed.

Going forward

Castle Project say their projects are independent and they should consider breaking them into separate downloads with individual release cycles to keep the pieces moving independently and competitively.

MVC alternatives

Microsoft are working on an MVC engine for ASP.NET themselves. Whilst Microsoft’s track record with user interface tool kits is less than spectacular the recent work with LINQ and knowing that both Scott Guthrie and now Phil Haack are on the team inspires more confidence.

Until they release a CTP and a timetable however this can’t be seriously considered especially for projects that need to start soon. I’m hoping we’ll see a similar cycle to the AJAX and Control Adapters where early access & final versions were available that hooked in to currently shipping versions of .NET and Visual Studio so that we’re not waiting for .NET 4.0.

RC3 was released the following day. Check out the contents or download it.

[)amien

Web Application Security for Developers presentation

Last nights Guernsey Software Developers Forum meeting was sparsely attended with a number of the regulars attendees absent. There were however two new faces including Kezzer who I’d been chatting to on-line for years.

Hopefully the low numbers were down to the seasonal summer holidays and the subsequent knock-on effect that we couldn’t get email out to the BCS Guernsey division to gather sufficient awareness.

I did a short presentation on Web Application Security for Developers that covered HTML injection, SQL injection and cross-site scripting including some live demonstrations on sample code. Slides and sample are available although without audio or screen cast of the demonstrations until I work out how to do that with Keynote.

Downloads

I’ve come to the conclusion that putting presentations together takes me around 1 hour of preparation to 1 minute of presentation…

[)amien

Typed session data in ASP.NET made easier still

Philippe Leybaert is unimpressed with Microsoft’s Web Client Software Factory approach for typed session data and offers his own Typed session data made (very) easy which still seems overkill to me comprising as it does of generics, a delegate a helper class to achieve the desired effect. (Whilst you are there check out his very interesting MVC project for ASP.NET called ProMesh)

The solution which I have been using since my .NET 1.1 days is much simpler still and involves nothing more than creating a plain class with properties for every session variable and a static get accessor that obtains or creates it on the HttpContext similar to a singleton.

Here’s an example with the important Current property (slightly cleaned up and improved for this post ;-)

public class MySession {
  public string Name;
  public int LoginID;
  public int CustomerID;

  public static MySession Current {
    get {
      MySession currentSession = HttpContext.Current.Session["_session"] as MySession;
      if (currentSession == null) {
        currentSession = new MySession();
        HttpContext.Current.Session["_session"] = currentSession;
      }
      return currentSession;
    }
  }
}

Using the session data then simply involves operations like:

MySession.Current.Name = NameTextBox.Text;
NameLabel.Text = MySession.Current.Name;

This solution is a lot clearer however all of these solutions use HttpContext.Session which is actually supposed to be there for compatibility with ASP.

Ideally Microsoft would provide us with an option in web.config whereby we can choose our session class and it would just instantiate and track it as part of the session life-cycle.

[)amien