Two Guys Arguing

C# Meta-Programming And Extension Methods Question

Posted in .net, functional programming, questions by benjaminplee on 12.30.10

First, it should be noted that my ASP.Net MVC-foo is yet great and I know this.  If you know a better way to do this, please take the time to explain how you are superior.  If you don’t, how will we ever know?

Working with ASP.Net MVC 2 client-side form validation this past week, I ran into two unfortunate (IMHO) facts which kept tripping me up:

  1. Html.ClientValidationEnabled() must be called as a scriptlet BEFORE the form is created
  2. Html.ValidateFor or Html.ValidationMessageFor must be called for EACH property of the model you want validated.

*** This StackOverflow answer includes a couple other important & useful things to note

These two issues (and many more) bother me about ASP.Net MVC 2 client-side validation but #2 in particular was really ticking me off.  I like that I can conditionally turn validation on/off on a field by field basis … but why make me enumerate all validation-needed model fields twice in my view!?  Especially in my case where I want validation turned on for ALL model object fields that have DataAnnotation Validations defined for.  Obviously the fields are going to be enumerated in the view once; how else are the text boxes and drop downs going to be created, but why make me list out each field AGAIN just to turn on validation?

All of this amounts to one WET solution. Am I missing something?

The best solution I have seen, and the one I am about to start implementing, is this one by Rick Anderson over at MSDN found via this related forum post.  The idea is to create additional Html helper extension methods which will combine the creation of the HTML form element with turning on and configuring validation.  This solution has the benefit of making me enumerate the model fields being used only ONCE in my view code and reads cleaner.

The only problem is that I have to walk through our application, find anywhere that is using a built in HtmlHelper extension method to build an HTML form element (e.g. input tag), build a new validating wrapper extension method that matches the signature of the original, and then replace the original code with the new extension method.  This can be done, but is time consuming and error prone.  And I am lazy.

The real issue …

I want to … create additional HtmlHelper extension methods based on all existing ones that produce form elements and take in a Linq expression to find the model property that first pass that expression to helper.ValidateFor() and then return the original extension method’s valued.

Is there any meta-programming feature or technique in C# that will allow me to concisely do that?

e.g.

Since Html.TextBoxFor(user => user.FirstName) is used in our app, as it stands I will am going to create a custom extension method similar to:

public static class ValidatingFormElementsExtension
{
  public static MvcHtmlString ValidatedTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
  {
    helper.ValidateFor(expression);
    return helper.TextBoxFor(expression);
  }

  // and so on for EACH one we use

}

Anyone have any ideas?  Am I completely off base with this? Is there a better way?

~~~~~~~~~~

<mini-related-rant>

A few more quick cracks at ASP.Net MVC  that I need to get off my chest

  • Why are so many things done in scriptlets!?  I feel like I am back in the vanilla JSP days of yesteryear.
  • They are Annotations in Java and Attributes in C# …. so why are the data validation attributes defined in System.ComponentModel.DataAnnotations?
  • I get that HTML checkbox form input fields have TRUE/FALSE values passed back when the form is submitted, and that doesn’t map perfectly to how other fields are handled by the Required attribute …. but why was NOTHING included to do this?  Having to use a RegularExpression validator for [Tt]rue is clumsy no?

</mini-related-rant>

Matrix Puzzle From Hell or: How I Learned to Stop Worrying and Love the Patterns

Posted in challenge, math by benjaminplee on 12.30.10
The Stage

About a year ago, Mr. King (@Adkron) posed a math puzzle on our team’s whiteboard first thing one morning.  The problem seemed at the same time very complex and strangely simple.  Amos said that he had found it surfing the web the night before and that it was from some company’s interview or resume-submitting questions.

After several passionate whiteboarding sessions including members of our team, and any poor souls who walked by (I believe Mr. Young falls into this group), no one had a solution.  Eventually the whiteboard was clearred for more “important” work but the puzzle lingered with me.  On several occasions over the past year I have redrawn the matrix on a pad of paper and spent and hour or two trying to decipher the patterns and make sense of the answer tickling at edge of my brain.

This past week, while drifting off to sleep, the puzzle popped back into my head.  After a few moments a number of ideas I had had months before fell together in just the right way for me to FINALLY figure out a solution.  Eureka! (I mentally shouted) and got out of bed to find a piece of paper to work through some more examples and prove myself right.

The Puzzle

Given a 2D matrix such that each cell’s value is defined as follows:

>> The smallest non-negative integer not already present to the “left” or “above” <<

Determine an constant time function ( O(1) ) which given X and Y indices will return the value of the matrix cell at (X,Y).

For the visual people in the crowd, the top left corner or said matrix looks something like this:

First 8x8 cells of matrix puzzle

First 8x8 cells of matrix puzzle

The picture only shows the top 8×8 of the defined matrix as an example.  We can see that whatever f(x,y) you come up with needs to equal the following example values

f(0,0) = 0
f(1,0) = 1
f(2,0) = 2
f(3,0) = 3
f(3,1) = 2
f(3,2) = 1
……

The real key here is that the solution needs to function in constant time: O(1).  This means that computing the matrix value at (6,3) should be the same cost computationally as computing the matrix value at (10000000,4500005).

Anyone can write a program to compute the whole matrix out to your point (in theory) but can you come up with a better solution? In less than a year?

The Solution

Not just yet.  I will post my thought process and eventual solution soon in a separate post.

** I didn’t think of this puzzle, nor guarantee that I am remembering it correctly **
** If you know who did or have any corrections, please leave a comment  below **


Tagged with: ,
Follow

Get every new post delivered to your Inbox.