DevelopMENTAL Madness

Wednesday, June 24, 2009

ASP.NET MVC: An Application Platform

The MVC / WebForms Debate

Yesterday I wrote about the stored procedure/dynamic sql debate - I must be feeling a bit argumentative lately, because today I was reading Tony Lombardo’s post on WebForms versus MVC. I don’t know Tony, I haven’t read any of his other posts or met him in any forum so I don’t hold anything against him. I’d be a hypocrite if I disagreed that you need to weigh the pros/cons and make an informed decision. I just made the same argument myself. However, at the end of his post he said this:

“The best advice I’ve seen so far is that WebForms is the platform of choice for building web applications, where MVC is more suited to building web sites.  This is still a bit abstract since there’s no clear definition of web applications, but I think it’s safe to say that if you’re building a web version of a win client application, you’re building a web application.  If you have a ‘grid’ in your page for purposes above that of just layout, you’re building a web application.”

It’s true MVC is very attractive for “web sites” when you consider how nicely url routing helps you build an SEO friendly site that also adheres to RESTful principals. However, this is only superficial in that these are features that stand out when you look at an MVC site. These were certainly goals of the MVC team, but if that’s all you see in MVC then you’re judging the book by it’s cover.

MVC as an Application Platform

I agree with your argument to use the best tool for the job. This is always the case in software development and loosing site of this is just going to bite you in the end. However, I believe that as future versions continue to be released WebForms will continue to loose ground because MVC will cover more and more scenarios where WebForms holds an advantage. I disagree with the recommendation that Application == WebForms, WebSite == MVC.

MVC is an application platform from the ground up. There are many reasons why, here are some that matter to me:

Model Binding

When WebForms was first released I was so excited that I didn’t have to use Request.Form[] and Request.QueryString[] (or just plain Request[]) to get access to my form data. I could look at a TextBox or better yet a DropDownList and get not only the value submitted via POST but I could inspect additional properties like SelectedItem.Text. It was a much richer model than classic ASP.

What this new model didn’t do for me was return primitive types (unless I built my own custom controls or purchased a 3rd party control library). I still had to parse the strings to primitive types, but at least validation allowed me to safely do so without using TryParse().

I have been using MVC since Preview 1 (Nov 2007) and I have found that it gets out of my way. I get strongly typed binding both in my view and when responding to any request. I no longer have to spend time parsing strings into primitive types then hydrating an object by hand. Instead I just have to do this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
 
namespace MyApp.Web.Controllers
{
    public class MyObject {
        DateTime Date { get; set; }
        Int64 Integer { get; set; }
        String Text { get; set; }
    }
 
    public class Default1Controller : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index() {
            return View();
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(MyObject model) {
 
            // save my model
            Repository.Save(model);
 
            return View();
        }
    }
}

I think that speaks for itself.

RAD Without Drag-n-Drop

It’s no secret you get no DnD from MVC. But here’s what you do (or will) get:

  • Scaffolding – at the moment this is a bit of a stretch to say MVC gives you scaffolding. It doesn’t support DynamicData yet (it’s in the pipeline), but on a per View basis you can have an entire page built for you (List, Create, Edit, Detials) with a strongly typed model by selecting the type of page you want and the type of your model.

    image 

  • Easy HttpHandlers – need to return an image or file other an an HTML response? The WebForms way is usually to create a Generic Handler (a class inheriting from IHttpHandler). You can do it with System.Web.UI.Page as well, but the point is that you create the handler create your content, set your Http headers and then write to the response stream. With MVC you simply return from an action a result type that corresponds to your content/type or use File and specify the mime type:
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
     
    namespace MyApp.Web.Controllers
    {
        public class Default1Controller : Controller
        {
            //
            // GET: /Default1/
     
            public FileResult SomeFile()
            {
                return File("/Path/To/File.ext", "content/type");
            }
     
            public JsonResult JavaScriptObject() {
                return Json(new { 
                    Property1 = "something", 
                    Propety2 = DateTime.Now, 
                    Property3 = 323.00 
                });
            }
     
            public JavaScriptResult ClientScript() {
                return this.JavaScript("function message(val) { alert(val); }");
            }
     
            public PartialViewResult HtmlSnippet() {
                return PartialView("NameOfAscxControl.ascx");
            }
        }
    }
  • Lightweight Web Services – as a side effect of easy control over the mime-type of your results you can create your own lightweight web services without the need of formally creating web services via .asmx or .svc files. JsonResult allows you to make easy calls from your javascript and return a JSON resonse or use FileResult and specify application/xml as your content type and you’re off and running with a working response to an ajax request to a RESTful interface.

Testability

If I'm building an application then being able to write unit tests for both my application logic and business logic is very important to the long-term life of my project. Applications are organic, they change and grow in size and complexity. Often an application will outlive the employment of the programmer(s) who wrote it. Maintaining unit tests ensure that the application continues to work as intended. This keeps things clean and maintainable, which in turn extends the life of your application longer than any other method I know of.

Control

WebForms is very closed when compared to MVC. Sure you get a lot of control/flexibility through HttpModules, HttpHandlers, Application and Page events, Server Controls. But many times I have needed to add custom logic which required a hack because I couldn’t put it where I needed to most to get the cleanest or most effective solution. You can debate that if you know what you’re doing then it isn’t a problem and I won’t let my pride get in the way of that. But in MVC I can hook in wherever I want at any level and MVC doesn’t try to “protect” me from myself. I could shoot myself in the foot, but I’m also free to do what I decide is best for my application. This is something you can’t fully appreciate until you experience it.

Other Concerns

WebForms Designer vs. Raw HTML

Many people site having to get their hands dirty in html and how nicely WebForms abstracts these details from them. This is strictly my own opinion and I may be biased. I started out almost 10 years ago writing HTML and classic ASP in notepad and I have never used the WebForms designer. I’ve tried it many times, but I find that it slows me down and very quickly looses any fidelity with the end result such that it becomes worthless to me.

Writing server controls by hand and writing raw HTML by hand are almost the same – it’s all tag soup. In some cases I’d even rather write the raw HTML when you compare the two:

<asp:TextBox ID="myTextBox" runat="server" />

compared to:

<input type="textbox" id="myTextBox" />

But even there I get helpers:

<%=Html.TextBox("myTextBox")%>

Tag Soup?

On a related note: after years of WebForms we’ve become conditioned to believe that the classic ASP style escapes (<%= %>)are bad, bad, bad. It’s mixing server code with markup. How’s that different from a server control – it isn’t html either, it just looks like it.

What’s bad is placing logic into the page. Rob Conrey demonstrated this better than I ever could.

Conclusion

Should you evaluate the needs of your application against the benefits of WebForms vs MVC? Yes. Should you learn MVC so you know what it has to offer? Most definitely. Will you regret using MVC? I haven’t and I don’t believe you will. MVC is an incredible application platform and it will only get better. WebForms was developed in a relatively closed way, whereas from day one MVC was developed with extensive community involvement and feedback. It had 5 preview releases before beta and was being used in production environments all along the way. The MVC team developed this so that it works and it works well. Give it a spin, you won’t regret it.

Labels: , ,

Tuesday, June 09, 2009

ASP.NET MVC: Discover the MasterPageFile Value at Runtime

A couple weeks ago it was finally time to add a context-sensitive, data driven menu system to our MVC application. As I thought about it I was stuck. I wasn't sure what the best way to implement it was. As is common with an MVC application there was no 1-to-1 relationship between actions and views. And even more difficult was that our *.master files could be used by views tied to different controllers. So it was looking like I would have to load the data I needed from the ViewMasterPage.

I really didn't like this option and looked around a bit trying to find out what others had done. Here's a couple examples of what I found:

While all of these options work, none of them sat well with me because they either require me to remember to include the data or they feel contrived or foreign to MVC.

@Page Directive

When you create a new View file you can specify that you want to use a MasterPage. When you do this your @Page Directive will look like this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Default.Master" Inherits="System.Web.MVC.ViewPage" %>

This can be changed as needed but if you are using MasterPages in your application you the value of the MasterPageFile is exactly what you need to determine which MasterPage is being used by the view being returned. I like this idea because the same action can return different views, or even result in a redirect, so it isn’t until you actually arrive at the controller’s ActionExecuted event that you know for sure that the result is a View and which view that will be.

Controller.OnActionExecuted event

The key to the whole thing is you need to be able to read the @Page directive located in the first line of your ViewPage. When you’re handling the OnActionExecuted event you get an ActionExecutedContext object passed in from System.Web.MVC.ControllerBase which contains the result of Action which just finished executing. Here’s what you do to get from the start of the event to the value of MasterPageFile:

  1. Check to see if ActionExecutedContext.Result is an ViewResult
  2. Check to see if ViewResult.ViewName has been set (if you’re writing tests for your Actions you’ll be doing this anyway). If it hasn’t then you know that the name of your view will be the same as the Action, so you can get the value from ControllerContext.RouteData.
  3. As long as you are using the WebForms view engine (or inheriting from it) you can use the ViewResult.ViewEngineCollection.FindView method to let the ViewEngine find the view for you.
  4. FindView returns a ViewEngineResult has a View property which returns a WebFormView which in turn has a ViewPath property.
  5. At this point you can get the source of your view, parse it and retrieve the value of MasterPageFile. Once you’ve done this I’d recommend caching the value to prevent the need to parse the file every time.

Here’s what the full implementation looks like:

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace GPM.Web.Code {
    public class MasterMenuDataFilterAttribute : ActionFilterAttribute {
 
        // private vairables supporting MasterPageFile discovery
        private static Dictionary<string, string> _viewMasterType = new Dictionary<string, string>();
        private static Regex _masterFilePath = new Regex("\\bMasterPageFile=\"(?<path>[^\"]*)\"", RegexOptions.Compiled);
 
        // private members for improved readability
        private HttpContextBase _httpContext;
        private ControllerContext _controllerContext;
 
        /// <summary>
        /// Loads data for dynamic menus in our MasterPage (if applicable)
        /// </summary>
        private void LoadMenuData(string viewName, string masterPath) {
            if (string.IsNullOrEmpty(masterPath) || !System.IO.File.Exists(_httpContext.Server.MapPath(masterPath)))
                return;
 
            switch (Path.GetFileName(masterPath)) {
                case "Site.Master":
                    break;
                case "Default.Master":
                    break;
                case "Custom.Master":
                    break;
                default:
                    break;
            }
        }
 
        /// <summary>
        /// Discovers the master page declared by the view so we can determine
        /// which menu data we need loaded for the view
        /// </summary>
        /// <remarks>
        /// If we find that we have too many controllers which don't need this 
        /// functionality we can impelment this as a filter attribute instead
        /// and apply it only where needed.
        /// </remarks>
        public override void OnActionExecuted(ActionExecutedContext filterContext) {
            // this logic only applies to ViewResult 
            ViewResult result = filterContext.Result as ViewResult;
            if (result == null)
                return;
 
            // store contexts as private members to make things easier
            _httpContext = filterContext.HttpContext;
            _controllerContext = filterContext.Controller.ControllerContext;
 
            // get the default value for ViewName
            if (string.IsNullOrEmpty(result.ViewName))
                result.ViewName = _controllerContext.RouteData.GetRequiredString("action");
 
            string cacheKey = _controllerContext.Controller.ToString() + "_" + result.ViewName;
            // check to see if we have cached the MasterPageFile for this view
            if (_viewMasterType.ContainsKey(cacheKey)) {
                // Load the data for the menus in our MasterPage
                LoadMenuData(result.ViewName, _viewMasterType[cacheKey]);
                return;
            }
 
            // get the MasterPageFile (if any)
            string masterPath = DiscoverMasterPath(result);
 
            // make sure this is thread-safe
            lock (_viewMasterType) {
                // cache the value of MasterPageFile
                if (!_viewMasterType.ContainsKey(cacheKey)) {
                    _viewMasterType.Add(cacheKey, masterPath);
                }
            }
 
            // now we can load the data for the menus in our MasterPage
            LoadMenuData(result.ViewName, masterPath);
        }
 
        /// <summary>
        /// Parses the View's source for the MasterPageFile attribute of the Page directive
        /// </summary>
        /// <param name="result">The ViewResult returned from the Controller's action</param>
        /// <returns>The value of the Page directive's MasterPageFile attribute</returns>
        private string DiscoverMasterPath(ViewResult result) {
            string masterPath = string.Empty;
 
            // get the view
            ViewEngineResult engineResult = result.ViewEngineCollection.FindView(
                _controllerContext, result.ViewName, result.MasterName);
 
            // oops! caller is going to throw a "view not found" exception for us, so just exit now
            if (engineResult.View == null)
                return string.Empty;
 
            // we currently only support the WebForms view engine, so we'll exit if it isn't WebFormView
            WebFormView view = engineResult.View as WebFormView;
            if (view == null)
                return string.Empty;
 
            // open file contents and read header for MasterPage directive
            using (StreamReader reader = System.IO.File.OpenText(_httpContext.Server.MapPath(view.ViewPath))) {
                // flag to help short circuit our loop early
                bool readingDirective = false;
                while (!reader.EndOfStream) {
                    string line = reader.ReadLine();
 
                    // don't bother with empty lines
                    if (string.IsNullOrEmpty(line))
                        continue;
 
                    // check to see if the current line contains the Page directive
                    if (line.IndexOf("<%@ Page") != -1)
                        readingDirective = true;
 
                    // if we're reading the Page directive, check this line for the MasterPageFile attribute
                    if (readingDirective) {
                        Match filePath = _masterFilePath.Match(line);
                        if (filePath.Success) {
                            // found it - exit loop
                            masterPath = filePath.Groups["path"].Value;
                            break;
                        }
                    }
 
                    // check to see if we're done reading the page directive (multiline directive)
                    if (readingDirective && line.IndexOf("%>") != -1)
                        break;  // no MasterPageFile attribute found
                }
            }
 
            return masterPath;
        }
    }
}

I’ve implemented this as an ActionFilterAttribute so you can just apply it to any controller or action. This way you can use it in a more flexible way. The only thing left for you to do is fill in the blanks in the LoadData method to retrieve the data you need based on the name of the MasterPageFile.

Conclusion

We’ve been running this setup for a couple weeks now in development, QA and UA and it’s working like a charm so far. Once you have it setup, you’re free to forget about it until you need to change how your menus function or your data set. Plus now you’re keeping all your interactions with your model inside your controller and your view just needs to pull the data from the ViewDataDictionary.

Labels: