May 13 2009

ASP.NET MVC HtmlHelper for Uploadify, Take One

Category: ASP.NET | MVC | JavaScriptMatt @ 06:56

As I’ve mentioned before, I really, really hate the way most people seem to be creating reusable UI “controls” with ASP.NET MVC.  I do not like emitting JavaScript, HTML, etc. from within C# code.  It’s cumbersome to create, difficult to really test, and just a real PITA in general.

Based on feedback I received from Rob after my attempts at creating a helper for jqGrid, I decided to take a completely different approach when it was time to wrap another jQuery plug-in: Uploadify.  My goal was to minimize the amount of tag-soup embedded in my C# code while still maintaining the ease-of-use of the jqGrid helper, which required only a single HtmlHelper call to go from nothing to full grid.

Well, one painful afternoon later, I think I’ve arrived at something that makes some sense.  First, I couldn’t completely eliminate the tag soup, but I did minimize it (I think) while still keeping the thing extremely simple to use and (hopefully) maintain.  Let’s start with how you would use it:

<asp:Content ContentPlaceHolderID="HeadContent" runat="server">
    <%=Html.Uploadify("fileInput", 
        new UploadifyOptions
           {
               UploadUrl = Html.BuildUrlFromExpression<SandboxController>(c => c.HandleUpload(null)),
            FileExtensions = "*.xls;*.xlsx",
            FileDescription = "Excel Files",
            AuthenticationToken = Request.Cookies[FormsAuthentication.FormsCookieName] == null ?
                string.Empty :
                Request.Cookies[FormsAuthentication.FormsCookieName].Value,
            ErrorFunction = "onError",
            CompleteFunction = "onComplete"
           }) %>
           
    <script type="text/javascript">
        function onError() {
            alert('Something went wrong.');
        }
        function onComplete() {
            alert('File saved!');
        }
    </script>                                                   
</asp:Content>

The first parameter is the name of the input control to convert to an uploadify control, the second contains all the optional settings you can customize.  I prefer to use an options class like this rather than provide 50,000 overloads.  By using a dedicated options class, I can add new settings without breaking existing code or having to create new overloads.  The options should be fairly self explanatory, but here they are:

/// <summary>
/// Defines all options for <see cref="HtmlHelperExtensions.Uploadify"/>.
/// </summary>
public class UploadifyOptions
{
    #region Public Properties

    /// <summary>
    /// The URL to the action that will process uploaded files.
    /// </summary>
    public string UploadUrl { get; set; }

    /// <summary>
    /// The file extensions to accept.
    /// </summary>
    public string FileExtensions { get; set; }

    /// <summary>
    /// Description corresponding to <see cref="FileExtensions"/>.
    /// </summary>
    public string FileDescription { get; set; }

    /// <summary>
    /// The ASP.NET forms authentication token.
    /// </summary>
    /// <example>
    /// You can get this in a view using:
    /// <code>
    /// Request.Cookies[FormsAuthentication.FormsCookieName].Value
    /// </code>
    /// You should check for the existence of the cookie before accessing
    /// its value.
    /// </example>
    public string AuthenticationToken { get; set; }

    /// <summary>
    /// The name of a JavaScript function to call if an error occurs
    /// during the upload.
    /// </summary>
    public string ErrorFunction { get; set; }

    /// <summary>
    /// The name of a JavaScript function to call when an upload
    /// completes successfully. 
    /// </summary>
    public string CompleteFunction { get; set; }

    #endregion
}

Next, we have the actual HtmlHelper extension method:

/// <summary>
/// Renders JavaScript to turn the specified file input control into an 
/// Uploadify upload control.
/// </summary>
/// <param name="helper"></param>
/// <param name="name"></param>
/// <param name="options"></param>
/// <returns></returns>
public static string Uploadify(this HtmlHelper helper, string name, UploadifyOptions options)
{
    string scriptPath = helper.ResolveUrl("~/Content/jqueryPlugins/uploadify/");

    StringBuilder sb = new StringBuilder();
    //Include the JS file.
    sb.Append(helper.ScriptInclude("~/Content/jqueryPlugins/uploadify/jquery.uploadify.js"));
    sb.Append(helper.ScriptInclude("~/Content/jqueryPlugins/uploadify/jquery.uploadify.init.js"));

    //Dump the script to initialze Uploadify
    sb.AppendLine("<script type=\"text/javascript\">");
    sb.AppendLine("$(document).ready(function() {");
    sb.AppendFormat("initUploadify($('#{0}'),'{1}','{2}','{3}','{4}','{5}',{6},{7});", name, options.UploadUrl,
                    scriptPath, options.FileExtensions, options.FileDescription, options.AuthenticationToken,
                    options.ErrorFunction ?? "null", options.CompleteFunction ?? "null");
    sb.AppendLine();
    sb.AppendLine("});");
    sb.AppendLine("</script");

    return sb.ToString();
}

The helper uses a StringBuilder (yeah, I hate them, and I’m open to suggestions) to include two JavaScript files.  The first is the standard uploadify script, but the second is something custom, which I’ll get to in just a second.    Finally, the helper outputs a call to initUploadify inside of the page load event, passing in all the options that were specified.

And that brings us to that second JavaScript include:

//This is used in conjunction with the HtmlHelper.Uploadify extension method.
function initUploadify(control, uploadUrl, baseUrl, fileExtensions, fileDescription, authenticationToken, errorFunction, completeFunction) {
    var options = {};

    options.script = uploadUrl;
    options.uploader = baseUrl + 'uploader.swf';
    options.cancelImg = baseUrl + 'cancel.png';
    //TODO: Make this an option?
    options.auto = true;
    options.scriptData = { AuthenticationToken: authenticationToken };
    options.fileExt = fileExtensions;
    options.fileDesc = fileDescription;

    if (errorFunction != null) {
        options.onError = errorFunction;
    }

    if (completeFunction != null) {
        options.onComplete = completeFunction;
    }

    control.fileUpload(options);
}

In here, I’ve created a simple JavaScript function that actually calls the uploadify JavaScript plug-in.  By using this method instead of using C# to emit the configuration code directly, I’m cutting out a fair amount of tag soup, and I’m wrapping things up in a way that will be easier to change in the future.  Hopefully.  The down side to this approach is that you have to create a new JavaScript method and include for every plug-in you want to use, but combining the scripts and correctly setting cache headers should reduce the request overhead.

I’m not claiming that this is the best way to do this.  In fact, I really hope it isn’t, because I still don’t like it.  But I think that I like it better than the approach I took for jqGrid.  If you have any suggestions or feedback, please share.  Feel free to tell me that I’m doing things completely wrong.

Tags:

May 13 2009

Using Flash with ASP.NET MVC and Authentication

Category: ASP.NET | MVCMatt @ 01:47

There is a well-known bug in Flash that causes it to completely ignore the browser’s session state when it makes a request.  Instead, it either pulls cookies from Internet Explorer or just starts a new session with no cookies.  GOOD CALL, ADOBE.  And when I say this bug is well-known, I mean it was reported in Flash 8.  It’s still sitting in the Adobe bug tracker.  It has been triaged, it seems to have high priority, yet it remains unfixed.  Again, GREAT job, Adobe. 

Anyway, why should you care?  Well, if you want to use Flash for anything, even something simple like AJAX file uploads with Uploadify, you better hope you don’t need authorization and authentication.  But really, why would you want to authenticate users before letting them upload stuff to your site, anyway?  There’s no possible way that could ever be exploited, right?

If you do decide that security is important (HINT: IT IS), there are some well-known hacks to work around it.  None of them fit well with ASP.NET MVC though.  Just when all seemed lost, I found this post from Ariel Popovsky that saved the day.  I have wrapped his solution up in an easy-to-apply custom AuthorizationAttribute that you can tag to a controller or action method.  Here’s the code:

/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.  
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class FlashCompatibleAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The key to the authentication token that should be submitted somewhere in the request.
    /// </summary>
    private const string TOKEN_KEY = "AuthenticationToken";

    /// <summary>
    /// This changes the behavior of AuthorizeCore so that it will only authorize
    /// users if a valid token is submitted with the request.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        string token = httpContext.Request.Params[TOKEN_KEY];

        if (token != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

            if (ticket != null)
            {
                FormsIdentity identity = new FormsIdentity(ticket);
                string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
                GenericPrincipal principal = new GenericPrincipal(identity, roles);
                httpContext.User = principal;
            }
        }

        return base.AuthorizeCore(httpContext);
    }
}

The filter checks the request to see if the authentication ticket was submitted.  If so, it tries to decrypt it, then recreates the IPrincipal that is needed by the base AuthorizationAttribute to do its work.  Just apply it to your controller, make sure Flash is submitted the value of the Forms Authentication cookie, and BAM, everything works.

Tags:

May 7 2009

Simplified unit testing for ASP.NET MVC JsonResult

Category: MVC | .NETMatt @ 01:45

There are quite a few examples floating around on the web that describe how to test your JsonResult objects to make sure the data was correctly packaged.  They all follow the same basic pattern: mock out core ASP.NET objects (such as ControllerContext, HttpResponse, and HttpContext), call JsonResult.ExecuteResult, recover what was written to HttpResponse.Output, and deserialize it.  Sure, this approach works, but in the same manner as cleaning your house out by lighting it on fire.  It’s way overkill.  There’s a much easier way.  For simple objects, just cast JsonResult.Data:

   1: string value = "Hello, there!";
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: //SURPRISE!
   6: Assert.AreEqual(value, (string)result.Data);

Yeah, that seems fairly obvious.  You don’t even need the explicit cast there, I just threw it in to prove the point.  But what about anonymous types?  Easy:

   1: var value = new { Id=5, Something="Else" };
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: IDictionary<string,object> data = new RouteValueDictionary(result.Data);
   6:  
   7: Assert.AreEqual(5, data["Id"]);
   8: Assert.AreEqual("Else", data["Something"]);

See, easy! “But what about arrays of anonymous types?!?!?” Do not fret, LINQ to the rescue:

   1: var values = new[]
   2:                  {
   3:                      new { Id = 5, Something = "Else" },
   4:                      new { Id = 6, Something = "New" },
   5:                      new { Id = 7, Something = "Old" },
   6:                  };
   7:  
   8: JsonResult result = new JsonResult { Data = values };
   9:  
  10: IDictionary<string, object>[] data = ((object[]) result.Data).Select(o => new RouteValueDictionary(o)).ToArray();
  11:  
  12: Assert.AreEqual(5, data[0]["Id"]);
  13: Assert.AreEqual(6, data[1]["Id"]);
  14: Assert.AreEqual(7, data[2]["Id"]);
  15: Assert.AreEqual("Else", data[0]["Something"]);
  16: Assert.AreEqual("New", data[1]["Something"]);
  17: Assert.AreEqual("Old", data[2]["Something"]);

Again, easy!

Alright, I know what you’re thinking.  “But Matt, the other solutions are all way more complicated, plus you’re cheating, that isn’t what JsonResult.ExecuteResult is going to do!” Well, you’re half-right, the other solutions are way more complicated, but this is actually simulating precisely what ExecuteResult will do.  Don’t believe me?  Pop it open in Reflector, or just browse the source (man I love Subversion).  It isn’t doing anything magical, it’s just using JavaScriptSerializer.  My solution just cuts out the middle man and doesn’t require you to mock out a bunch of complicated objects.

Tags:

Feb 6 2009

ASP.NET MVC: Good in a lot of ways, bad in others

Category: ASP.NET | MVCMatt @ 10:06

I have spent the better part of a week now trying to encapsulate a jqGrid control into something that could be cleanly and easily reused from various ASP.NET views.  In some ways, I think I have met those goals, but in others, I think I have failed miserably.  On the plus side, actually creating a grid is quite easy:

   1: <%=Html.JQGrid("treeTabel",
   2:                 new JQGridOptions 
   3:                     { Caption="Components",
   4:                       DataUrl = Html.BuildUrlFromExpression<SandboxController>(c => c.JQGridTreeViewData((int)ViewData["EstimateId"], null)), 
   5:                       PagerId="PagerId", 
   6:                       IsTreeGrid = true,
   7:                       CellEditEnabled = true,
   8:                     },
   9:                 new[]
  10:                     {
  11:                         new JQGridColumn("id", "ID") { Visible = true, IsExpandColumn = true, Editable = false},
  12:                         new JQGridColumn("ComponentId", "ComponentId") { Visible = false, Editable = false},
  13:                         new JQGridColumn("Name", "Component"),
  14:                         new JQGridColumn("HistoricalCost", "Historical"), 
  15:                         new JQGridColumn("EstimatedCost", "Estimated"), 
  16:                         new JQGridColumn("TargetCost", "Target"),
  17:                         new JQGridColumn("Risk", "Risk") { EditType = "select" ,EditOptions = new[] { "Unassigned:Unassigned", "Low:Low", "Medium:Medium", "High:High"}}, 
  18:                     }) %>

That simple (well, sort-of simple), type-safe code produces this horrible mass of HTML and JavaScript:

   1: <script type='text/javascript'>
   1:  
   2: jQuery(document).ready(function(){
   3: jQuery('#treeTabel').jqGrid({
   4: url: '/Sandbox/JQGridTreeViewData/2',
   5: datatype: 'json',
   6: height: '475px',
   7: colNames:['ID','ComponentId','Component','Historical','Estimated','Target','Risk'],
   8: colModel:[
   9: {name:'id',index:'id',sortable:false,width:1},
  10: {name:'ComponentId',index:'ComponentId',sortable:false,width:1,hidden:true},
  11: {name:'Name',index:'Name',editable:true,sortable:false,width:1},
  12: {name:'HistoricalCost',index:'HistoricalCost',editable:true,sortable:false,width:1},
  13: {name:'EstimatedCost',index:'EstimatedCost',editable:true,sortable:false,width:1},
  14: {name:'TargetCost',index:'TargetCost',editable:true,sortable:false,width:1},
  15: {name:'Risk',index:'Risk',editable:true,sortable:false,width:1,edittype:'select',editoptions:{value:'Unassigned:Unassigned;Low:Low;Medium:Medium;High:High'}}
  16: ],
  17: pager: jQuery('#PagerId'),
  18: rowNum:25,
  19: rowList: [10,25,50,100],
  20: imgpath: '/Content/jQueryPlugins/JQGrid/themes/steel/images',
  21: width:(document.body.clientWidth)*(7/10),
  22: shrinkToFit: true,
  23: caption: 'Components',
  24: loadonce: false,
  25: treeGrid: true,
  26: ExpandColumn: 'id',
  27: treeGridModel: 'adjacency',
  28: cellEdit: true,
  29: cellsubmit: 'clientArray'
  30: }).navGrid('#PagerId',{edit:false,add:false,del:false,search:false,refresh:false})
  31: ;});
</script>
   2: <table id='treeTabel' class='scroll'></table>
   3: <div id='PagerId' class='scroll' style='text-align:center;'></div>

Obviously that's a step up.  But when you look under the covers, things are anything but clean and neat.  Basically, I have several methods that build up a bunch of JavaScript strings, then spit them back out.  It reminds me *so* much of old-school PHP, where you have this awful mix of presentation markup and PHP code interwoven together into a blanket that looks like someone threw up on it.  Here's an excerpt:

   1: if (options.IsTreeGrid)
   2: {
   3:     JQGridColumn expandColumn = columns.FirstOrDefault(c => c.IsExpandColumn);
   4:  
   5:     if (expandColumn == null)
   6:     {
   7:         throw new InvalidOperationException("IsTreeGrid is true, but no column found with IsExpandColumn set to true.");
   8:     }
   9:  
  10:     js.AppendLine("treeGrid: true,");
  11:     js.AppendFormat("ExpandColumn: '{0}',", expandColumn.Name).AppendLine();
  12:     js.AppendLine("treeGridModel: 'adjacency',");
  13: }
  14:  
  15: //If cell editing is enabeled, the changed rows are stored client-side,
  16: //and it is the responsibility of the page to provide a mechanism
  17: //for posting the data back.
  18: if (options.CellEditEnabled)
  19: {
  20:     js.AppendLine("cellEdit: true,");
  21:     js.AppendLine("cellsubmit: 'clientArray',");
  22: }

So, I'm torn.  Overall, I think the ASP.NET MVC approach is much, much better than the WebForms approach, but... is this it?  Is this really the best we can do?  There has to be a better way to do things like this.  There has to be a way to keep languages separate.  There has got to be a cleaner way to encapsulate and reuse "controls" in ASP.NET MVC.  I just haven't found it yet.

Tags:

Oct 13 2008

Creating a reusable GridTreeView with ASP.NET MVC and jQuery, take two

Category: MVCMatt @ 05:21

In my last post, I created a partial view page that rendered a collapsible gridview (which I now call a GridTreeView) using the MVCContrib Grid HtmlHelper extension and the jQuery  ActsAsTreeTable plug-in.  While the code works, there are a few drawbacks.  First, I completely forgot about having to link the CSS file in to the view.  That's doable using the view codebehind, but I don't like codebehinds in MVC.  The second drawback is that it doesn't follow the "standard" method of rendering controls in ASP.NET MVC.  All the built-in controls are available via the HtmlHelper object, and that's how I'd like to expose the GridTreeView as well.  Fortunately, it isn't too terribly difficult to do!

First, let's define the HtmlHelper extension method (the final version of this, which I will eventually post online, includes various overloaded versions of the method):

   1: /// <summary>
   2: /// Creates an MvcContrib Grid with the power of the jQuery table-as-tree plug-in.
   3: /// </summary>
   4: /// <param name="dataSource">The data source to display.</param>
   5: /// <param name="attributes">Any HTML attributes to add to the opening table tag.</param>
   6: /// <param name="helper">The helper.</param>
   7: /// <param name="gridId">The ID to assign to the generated table.</param>
   8: /// <param name="idSelector">An expression that selects the ID from an item.</param>
   9: /// <param name="parentIdSelector">An expression that selects the parent ID from an item.</param>
  10: /// <param name="columns">An expression that generates the columns.</param>
  11: /// <param name="sections">An expression that modifies how sections are emitted (such as changing the 
  12: /// opening tags for rows, columns, etc).</param>
  13: public static void GridTreeView<T>(this HtmlHelper helper, string gridId, IEnumerable<T> dataSource, 
  14:     Action<IRootGridColumnBuilder<T>> columns, Func<T, string> idSelector, Func<T, string> parentIdSelector,
  15:     IDictionary attributes, Action<IGridSections<T>> sections) where T : class
  16: {
  17:     GridColumnBuilder<T> builder = new GridColumnBuilder<T>();
  18:  
  19:     if (columns != null)
  20:     {
  21:         columns(builder);
  22:     }
  23:  
  24:     if (sections != null)
  25:     {
  26:         sections(builder);
  27:     }
  28:  
  29:     GridTreeView<T> grid = new GridTreeView<T>(gridId, dataSource, builder,
  30:                                                idSelector, parentIdSelector, attributes, 
  31:                                                helper.ViewContext.HttpContext.Response.Output,
  32:                                                helper);
  33:  
  34:     grid.Render();
  35: }

Let's talk through the parameters real quick, because some of them are fairly nasty.

  1. helper - By prefixing it with the "this" keyword, this method becomes an extension method for HtmlHelper instances, which is what we want. 
  2. gridId - This will be used as the "id" attribute for the table that's created by the control.
  3. dataSource - This is any enumerable type.  Items from this data source will be used to build the rows of the grid.
  4. columns - Ok, this one is complicated.  It is an Action delegate that takes an IRootGridColumnBuilder.  What that means is that the caller must specify a delegate (or lambda) that uses an IRootGridColumnBuilder to define the columns for the grid.  This is straight out of the Grid helper from MVCContrib, so go here if you want more info.
  5. idSelector - This is a delegate (or lambda) that will be called when the grid is being built.  The delegate will receive an object from the dataSource as input, and it must return a string representing the ID of the object as output.  This is half of what is used to tie parent/child rows together.
  6. parentIdSelector - This is the other half.  This delegate (or lambda) must return the parent ID of the instance that is passed to it.
  7. attributes - This is a simple key/value pair of attributes to assign to the <table> element of grid.
  8. sections - You can use this to override how the grid is rendered.  For more information, go here.

That's sounds pretty complicated, but it really isn't.  Here's how you could use it (I have omitted the markup code for clarity):

   1: Html.GridTreeView("MyGridTree", ViewData.Model,
   2:                       column =>
   3:                       {
   4:                           column.For(w => w.Name);
   5:                           column.For(w => w.Description);
   6:                           column.For(w => Html.TextBox("Description_" + w.Id, w.Description), "Editable").DoNotEncode();
   7:                       },
   8:                        w => w.Id.ToString(), w => w.ParentId.ToString(),
   9:                        new Hash(style => "width: 100%"),null
  10:                ); 

It may look a little intimidating, but it's actually quite simple.  An IEnumerable containing Widgets is passed in via the ViewData.Model property. Next, you can see the lambda expression that creates columns (one bound to the widget name, one bound to the description, and a text box that is also bound to the description), followed by two lambdas that deal with IDs.

Ok, so I've shown you how to define the extension method, and I've shown you how to call the method, now I need to show you how to implement the GridTreeView class.  Let's dive into the code:

   1: /// <summary>
   2: /// An extension of <see cref="Grid{T}"/> that adds
   3: /// jQuery ActsAsTree functionality.
   4: /// </summary>
   5: /// <typeparam name="T">The type of the data item being displayed in the grid.</typeparam>
   6: public class GridTreeView<T> : Grid<T> where T : class
   7: {
   8:     #region Const Fields
   9:  
  10:     /// <summary>
  11:     /// The index into the HttpContext.Items bag, it tracks whether or not
  12:     /// the includes for this control have already been written to the the
  13:     /// response.
  14:     /// </summary>
  15:     private const string mItemKey = "GridViewTree.Initialized";
  16:  
  17:     /// <summary>
  18:     /// The default path to the ActsAsTree javascript file.
  19:     /// </summary>
  20:     private const string mDefaultJavaScriptPath = "~/Content/jQueryPlugins/ActsAsTreeTable/jquery.acts_as_tree_table.js";
  21:  
  22:     /// <summary>
  23:     /// The default path to the ActsAsTree CSS file.
  24:     /// </summary>
  25:     private const string mDefaultCssPath = "~/Content/jQueryPlugins/ActsAsTreeTable/stylesheets/jquery.acts_as_tree_table.css";
  26:  
  27:     #endregion
  28:  
  29:     #region Private Delegates
  30:  
  31:     /// <summary>
  32:     /// The function that selects the parent ID from an item.
  33:     /// </summary>
  34:     private readonly Func<T, string> GetParent;
  35:  
  36:     /// <summary>
  37:     /// The function that selects the ID from an item.
  38:     /// </summary>
  39:     private readonly Func<T, string> GetId;
  40:  
  41:     #endregion
  42:  
  43:     #region Private Fields
  44:  
  45:     /// <summary>
  46:     /// The DOM ID to assign to the grid.
  47:     /// </summary>
  48:     private readonly string mGridId;
  49:  
  50:     /// <summary>
  51:     /// The HTML helper class, which is used to resolve URLs.
  52:     /// </summary>
  53:     private readonly HtmlHelper mHelper;
  54:  
  55:     #endregion
  56:  
  57:     #region Public Static Properties
  58:  
  59:     /// <summary>
  60:     /// The path to the JavaScript ActsAsTree file.
  61:     /// </summary>
  62:     /// <remarks>
  63:     /// This shouldn't need to be changed, but just in case, you can override it by changing this property.
  64:     /// </remarks>
  65:     public static string JavaScriptPath { get; set; }
  66:  
  67:     /// <summary>
  68:     /// The path to the CSS file that needs to be included for the tree to display correctly.
  69:     /// </summary>
  70:     /// <remarks>
  71:     /// This shouldn't need to be changed, but just in case, you can override it by changing this property.
  72:     /// </remarks>
  73:     public static string CssPath { get; set; }
  74:  
  75:     #endregion
  76:  
  77:     #region Static Constructors
  78:  
  79:     /// <summary>
  80:     /// Initializes the static fields to default values.
  81:     /// </summary>
  82:     static GridTreeView()
  83:     {
  84:         JavaScriptPath = mDefaultJavaScriptPath;
  85:         CssPath = mDefaultCssPath;
  86:     }
  87:  
  88:     #endregion
  89:  
  90:     #region Public Constructor
  91:  
  92:     /// <summary>
  93:     /// Creates a new GridTreeView class.
  94:     /// </summary>
  95:     /// <param name="dataSource"></param>
  96:     /// <param name="columnBuilder"></param>
  97:     /// <param name="htmlAttributes"></param>
  98:     /// <param name="output"></param>
  99:     /// <param name="helper"></param>
 100:     /// <param name="idSelector">A delegate that returns an ID from a T.</param>
 101:     /// <param name="parentIdSelector">A delegate that returns a parent ID from a T.</param>
 102:     /// <param name="gridId">The ID to assign to the grid.</param>
 103:     public GridTreeView(string gridId, IEnumerable<T> dataSource, GridColumnBuilder<T> columnBuilder, Func<T, string> idSelector, Func<T, string> parentIdSelector, IDictionary htmlAttributes, TextWriter output, HtmlHelper helper) : base(dataSource, columnBuilder, htmlAttributes, output, (helper == null ? null : helper.ViewContext.HttpContext))
 104:     {
 105:         GetParent = parentIdSelector;
 106:         GetId = idSelector;
 107:         mGridId = gridId;
 108:         mHelper = helper;
 109:  
 110:         //Override the ID if it has been set
 111:         HtmlAttributes["id"] = gridId;
 112:     }
 113:  
 114:     #endregion
 115:  
 116:     #region Private Methods
 117:  
 118:     /// <summary>
 119:     /// Renders the row with the default ActsAsTree functionality.
 120:     /// </summary>
 121:     /// <param name="item"></param>
 122:     /// <param name="isAlternate"></param>
 123:     private void RenderActsAsTreeRow(T item, bool isAlternate)
 124:     {
 125:         string row = string.Format("<tr class=\"{0} child-of-node-{1}\" id=\"node-{2}\">",
 126:                         isAlternate ? "gridrow_alternate" : "gridrow",
 127:                         GetParent(item), GetId(item));
 128:  
 129:         RenderText(row);
 130:     }
 131:  
 132:     /// <summary>
 133:     /// Writes the tags to include the required ActsAsTree javascript file.
 134:     /// </summary>
 135:     private void WriteJavaScriptInclude()
 136:     {
 137:         const string script = @"<script type=""text/javascript"" src=""{0}""></script>";
 138:  
 139:         RenderText(string.Format(script, ResolveUrl(JavaScriptPath)));
 140:     }
 141:  
 142:     /// <summary>
 143:     /// Writes the JavaScript to initialize the grid as an ActsAsTree grid.
 144:     /// </summary>
 145:     private void WriteActsAsTreeJavaScript()
 146:     {
 147:         const string script =
 148:             @"<script type=""text/javascript"">
 149:             $(document).ready(function()  {{
 150:                 $(""#{0}"").acts_as_tree_table();
 151:             }});
 152:             </script>";
 153:  
 154:         RenderText(string.Format(script, mGridId));
 155:     }
 156:  
 157:     /// <summary>
 158:     /// Writes some HTML to do a dynamic CSS include.
 159:     /// </summary>
 160:     private void WriteCssInclude()
 161:     {
 162:         const string script =
 163:             @"<script type='text/javascript'>
 164:         var link=document.createElement('link');  
 165:         link.setAttribute('rel', 'stylesheet');  
 166:         link.setAttribute('type', 'text/css');  
 167:         link.setAttribute('href', '{0}');
 168:         var head = document.getElementsByTagName('head')[0];  
 169:         head.appendChild(link);
 170:         </script>";
 171:  
 172:         RenderText(string.Format(script, ResolveUrl(CssPath)));
 173:     }
 174:  
 175:     /// <summary>
 176:     /// Resolves a URL if an HtmlHelper instance is available, otherwise
 177:     /// just returns the URL.
 178:     /// </summary>
 179:     /// <param name="url"></param>
 180:     /// <returns></returns>
 181:     private string ResolveUrl(string url)
 182:     {
 183:         return mHelper != null ? mHelper.ResolveUrl(url) : url;
 184:     }
 185:  
 186:     #endregion
 187:  
 188:     #region Protected Overrides
 189:  
 190:     /// <summary>
 191:     /// Renders the row.
 192:     /// </summary>
 193:     /// <param name="item"></param>
 194:     /// <param name="isAlternate"></param>
 195:     protected override void RenderRowStart(T item, bool isAlternate)
 196:     {
 197:         //If there's a custom delegate for rendering the start of the row, invoke that instead.
 198:         if (Columns.RowStartBlock != null)
 199:         {
 200:             Columns.RowStartBlock(item);
 201:         }
 202:         else if (Columns.RowStartWithAlternateBlock != null)
 203:         {
 204:             Columns.RowStartWithAlternateBlock(item, isAlternate);
 205:         }
 206:         else
 207:         {
 208:             RenderActsAsTreeRow(item, isAlternate);
 209:         }
 210:     }
 211:  
 212:     #endregion
 213:  
 214:     #region Public Methods
 215:  
 216:     /// <summary>
 217:     /// Renders the grid along with all required scripts and resources.
 218:     /// </summary>
 219:     public override void Render()
 220:     {
 221:         //Include the required CSS/JavaScript if this is the first tree we are rendering.
 222:         if (Context == null || Context.Items[mItemKey] == null)
 223:         {
 224:             //This checks for null first to enable unit testing.
 225:             if (Context != null) Context.Items[mItemKey] = true;
 226:  
 227:             WriteCssInclude();
 228:             WriteJavaScriptInclude();
 229:         }
 230:  
 231:         //Render the jQuery script to initialize the GridTree.
 232:         WriteActsAsTreeJavaScript();
 233:  
 234:         //Render the GridTree.
 235:         base.Render();
 236:     }
 237:  
 238:     #endregion
 239:  
 240: }

That's quite a bit of code, but most of it is straight forward.  There are static properties and fields that you can change based on where the jQuery plug-in is installed.  The constructor doesn't do much other than grab references to the parameters so that they can be used later.  The neat stuff starts in the overridden methods from Grid. 

First, Render checks to see if the necessary JavaScript and CSS files have already been included in the page.  If not, they are included using helper methods (more on those in a sec).  Next, the JavaScript to turn the grid into a GridTreeView is written.  Finally, the actual grid rendering is delegated back to the base class.  The only deviation from the standard behavior is in how the row start (tr) tags are written.  The RenderRowStart method is overridden, and for the most part, it behaves exactly like the base class.  If a caller has chosen to override how rows should be rendered, the specified delegates are called.  Otherwise, the helper RenderActsAsTreeRow method is called.  This method renders a tr tag with the required class and ID attributes.  It does this using the delegates that were passed in to the GridTreeView constructor. 

There are a couple of other helper methods that are worth mentioning.  First, there is a helper ResolveUrl method.  This exists to facilitate unit testing while keeping the code clean.  If an HtmlHelper instance was passed to GridTreeView, the call is routed to it, otherwise the method just returns the original URL.  Second, the WriteCssInclude method may appear unnecessarily complex upon first inspection.  Why does it write JavaScript that creates a link element instead of just emitting the link element?  Stylesheet includes are supposed to go in the HTML header of a page.  HtmlHelper extensions do not have access to the HTML header, so they cannot add CSS to the page correctly.  The JavaScript works around that limitation by inserting the link element into the head even though the JavaScript could potentially be written anywhere in the DOM.

So, that's basically it.  If there is sufficient interest, I'll wrap everything up in a standalone library (with source code) that can be reused.  If you want it, leave me a note in the comments.

Tags:

Oct 8 2008

Creating a reusable grid tree view with ASP.NET MVC and jQuery

Category: ASP.NET | JavaScript | MVCMatt @ 08:45

I think it is a safe assumption that every web developer has had to display tabular data at one point or another.  Tabular data is easy with ASP.NET: bind a GridView to a data source, and you're all set.  But with ASP.NET MVC, things are a little trickier.  We don't have access to all the nice WebForms controls.  Still, it's fairly easy to do: just write a for-loop, or better yet, use the grid helper from MvcContrib.

Things get a trickier though if your tabular data is also hierarchical.  Typically, we display hierarchical data in a tree of some kind, but trees really aren't great for tabular data.  What would be great is to combine the two somehow.  Fortunately, there's a nice plug-in for jQuery that does just that: ActsAsTreeTable.  It's easy enough to use; all you have to do is embed ID's and CSS class information in your table rows, and the JavaScript does everything else.  Here's a simple example from the docs:

   1: <link href="path/to/jquery.acts_as_tree_table.css" rel="stylesheet" type="text/css" />
   2: <script type="text/javascript" src="path/to/src/jquery.acts_as_tree_table.js"></script>
   1:  
   2: <script type="text/javascript">
   3:     
   4: $(document).ready(function()  {
   5:     $("#your_table_id").acts_as_tree_table();
   6: });
</script>
   3:  
   4: ...
   5:  
   6: <table id="tree">
   7:   <tr id="node-1">
   8:     <td>Parent</td>
   9:   </tr>
  10:   <tr id="node-2" class="child-of-node-1">
  11:     <td>Child</td>
  12:   </tr>
  13: </table>

We can now combine this with the grid from MvcContrib to produce a collapsable Grid Tree View.  This example is encapsulated inside a view user control so that it can be used on any page.  It displays imaginary "widgets" in a tree.  The widgets aren't really hierarchical, so I've fudged it by making it appear that each widget is a child of its predecessor in the table.

First, let's create the grid:

   1: <%
   1:  Html.Grid(GetWidgets(), new Hash(id => ClientID, style => "width:100%"), 
   2: column =>
   3:       {
   4:           column.For(w => w.Name);
   5:           column.For(w => w.Description);
   6:           column.For(w => Html.TextBox("Description_" + w.Id, c.Description), "Editable").DoNotEncode();
   7:       },
   8: sections =>
   9:     {
  10:         sections.RowStart(c =>
  11:                               {
%> <tr class="child-of-node-<%=w.Id - 1%>" id="node-<%=w.Id%>"> <%
   1:  
   2:                               });
   3:     }    ); 
%>

That probably looks horrendous, so let's walk through it.  GetWidgets() is a method on the view user control that grabs widgets from wherever (in practice, probably the model or view data).  Next, the Hash just contains key/value pairs that are embedded in the opening table tag; here, we've specified the table's ID (by using ClientID, it will have the name that ASP.NET gives to the user control), and we've specified that it should be 100% wide.  Next, we define the columns using lambda expressions.  The first two columns simply display the widget's name and description.  The last column is a little more complicated.  It creates a text box using the TextBox helper method.  Since the column contains HTML that shouldn't be encoded, we call DoNotEncode on it.  Finally, we use a lambda expression to override how rows are created.  The code here populates the row with the 'child-of-node-#' class and the id attribute, both of which are needed by ActsAsTreeTable.  It may look intimidating, but it's actually nice once get comfortable with the syntax. 

The last thing we need to do is spit out the JavaScript to turn our gird into an ActsAsTreeTable:

   1: <script type="text/javascript">
   2:         $(document).ready(function()  {
   3:             $("#<%=ClientID %>").acts_as_tree_table();
   4:         });
   5: </script>

If you set everything up correctly, you should now have a working "grid tree view".  In a future article, I'll introduce a new Html helper that does all the heavy lifting for you.

Tags:

Aug 4 2008

Unit testing complex ASP.NET MVC controllers with Moq

Category: MVCMatt @ 08:56

One of the advantages of the new ASP.NET MVC framework is improved testability.  Testing simple controllers is as simple as testing any other class.  Once you start accessing HttpContext-related things though (such as the request, response, etc), things become much more tricky.  There's a few things in MVC Contrib that can help, but I've found them to be very lacking.  For example, I was trying to test a controller that inspected the HttpMethod property of the request, but MVC Contrib provides no way to alter this value (at least not that I have found).

Instead, I found some extensions created by Alan Dean in the AltNetUK project on Google Code.  These extension methods utilize Moq and enable you to do some really cool things, such as modify HttpContext properties:

   1: /// <summary>
   2: /// Verifies that the method correctly modifies the HttpMethod property.
   3: /// </summary>
   4: [Test]
   5: public void SetHttpMethodTest()
   6: {
   7:     var mockContext = HttpContextBaseMock.New();
   8:  
   9:     mockContext.Request.SetHttpMethod("BYAH");
  10:  
  11:     Assert.AreEqual("BYAH", mockContext.Request.HttpMethod);
  12: }

We're still trying to figure out how to mock out a few more advanced things, like the user context.  It is starting to look like it isn't doable easily, but I'll post an update if/when we manage to crack this scenario.

Tags: