February 2011 Entries

DynamicModuleUtility

One of the interesting side-effects of installing ASP.NET MVC 3 is the appearance of Microsoft.Web.Infrastructure in the GAC. Inside the assembly is a DynamicModuleUtility class that will let you do the following: using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; [assembly:PreApplicationStartMethod(typeof(MyAppStart), "Start")] public class CoolModule : IHttpModule { // implementation not important // imagine something cool here } public static class MyAppStart { public static void Start() { DynamicModuleUtility.RegisterModule(typeof(CoolModule)); } } The significant line of code is the line with RegisterModule. The DynamicModuleUtility will let you install an...

Custom Data Annotation Validator Part III: QUnit Tests

QUnit is an easy to use testing framework* for an easy to test language. Once you've downloaded the library you can load up an .html page with all of your scripts, and the boilerplate qUnit HTML: <h1 id="qunit-header">Validator Tests</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="qunit-fixture"> <input id="prefix_first" name="prefix.first" type="text" /> <input id="prefix_second" name="prefix.second" type="text" /> </div> Notice we place two inputs inside of qunit-fixture. QUnit will position the qunit-fixture off screen so you'll...

Custom Data Annotation Validator Part II: Client Code

The validator we looked at in the last post only supports server side validation. To support client side validation we need a little more code on the server, and some custom client script. One approach to client validation is to have the validation attribute implement the IClientValidatable interface, which requires a single method: GetClientValidationRules. public class DateGreaterThanAttribute : ValidationAttribute, ...

Custom Data Annotation Validator Part I : Server Code

Let's say you want to create a GreaterThan validation attribute and use it like so: public class Trip { [Required] public DateTime StartDate { get; set; } [Required] [GreaterThan("StartDate")] public DateTime EndDate { get; set; } } The implementation would look something like this: public class GreaterThanAttribute : ValidationAttribute { public GreaterThanAttribute(string otherProperty) :base("{0} must be greater than {1}") { ...

What's Wrong With This Code (#27)

Cory Ander wanted to make sure his users enter a date value that is reasonably close to the current date. He's writing an MVC 3 app and envisioned using a validation attribute like the following. public class TransactionDispute { [RecentDate] public DateTime TransactionDate { get; set; } // ... } Corey came up with the following. public class RecentDateAttribute : ValidationAttribute { public RecentDateAttribute() :base("{0} must be recent") { ...

Html.Awkward

I’ve seen the HTML helpers in ASP.NET MVC drive developers to madness. For example: @Html.ActionLink("Detail", "Detail", "Car", new { id = 5 }) ... produces ... <a href="/Home/Detail?Length=3" id="5">Detail</a>   Notice "Length=3" in the query string? That's probably not what you expected. We see this output because we are calling the ActionLink overload where “Car” is interpreted as route data and the anonymous object we want to use for route data is instead interpreted as the HTML attributes parameter. If you add one more parameter (a null on the end): @Html.ActionLink("Detail", "Detail", "Car", new { id = 5 }, null) ... it renders ... <a href="/Car/Detail/5">Detail</a> And...

Notes on Building Razor Views

Just like web form views, razor views don’t “build” when you build an MVC project in Visual Studio. By default, the parsing and compilation of a view doesn’t happen until runtime, meaning you might not know about a syntax error in a view until you hit the application with a web browser. Since it’s first release, ASP.NET MVC has provided the ability to parse and compile views at build time by manipulating the underlying MSBuild (.csproj) file. The option works for both web forms (.aspx) and Razor (.cshtml) views. 1. Right-click the MVC project and select...

Revisiting Charts: HTML5 Attributes

The charting sample I wrote years ago rendered image tags like this: <img id="topDestinations" src="roller.gif" /> The roller gif was a spinning animation that let the user know some work was happening behind the scenes. JavaScript loaded into the page had the following responsibilities: 1) Identity the image tags to transform into charts. 2) Call a web service to generate the chart asynchronously. 3) Set the src attribute of each image the to image name returned by the web service call. Although the Microsoft AJAX libraries made it easy to call WCF services, they didn’t provide much in the way of...

Revisiting Charting with ASP.NET and LINQ

Once upon a time I wrote an article titled “Charting with ASP.NET and LINQ”. At the time I used a combination of WebForms, WCF, the Microsoft AJAX libraries, and the Microsoft chart control. I had some time to revisit the topic recently and rewrote the sample application using ASP.NET MVC and jQuery. You can download the sample here. The idea behind the sample is to present a “dashboard” full of charts. I’ve worked on a few dashboards over the years, and they are always notoriously difficult to optimize without aggressive caching and asynchrony. In this sample the view...

Data Validation Annotations You Won't See In .NET 5.0

I just heard today - the attributes demonstrated below didn't make the cut. public class EditViewModel { [GoodLooking] [NotATerrorist] public User CurrentUser { get; set; } [ProperGrammer] [Profanity(ProfanityLevel.None)] public string Description { get; set; } }

Stackoverflow Exceptions with Html.Action

If you ever have a stack overflow using Html.Action or Html.RenderAction in a Layout view, then check the return type of your child action. public class Weather : Controller { public ActionResult Forecast() { // ... return View(); } } The problem is if you call that action from a Layout view, like so: @Html.Action(actionName: "Forecast", controllerName: "Weather") ... then the child action is returning a...

Once More In Defense Of The var Keyword

Even today there are those of you who doubt the power of the var keyword in C#! Or rather, there are those of you who steadfastly refuse to use it. I think the var keyword provides a nice symmetry for local variable declarations. No one variable appears more important than another just because it has a type name with more capital letters. var newPatient = new Patient(); var surgicalProcedure = Procedures.Rhinoplasty; var lengthOfStay = TimeSpan.FromDays(2); We can also talk about readability, type inference - blah blah blah. But, I think the following generalization is the real benefit of the...

The Value of Symmetry

Symmetry in code is valuable, and often subtle. When I find symmetry in code, I feel it's a positive sign that the design is working well. I like temporal symmetry. When something opens at the very beginning of a request, I'll expect it to close at the very end of a request. I like conceptual symmetry. Milan Negovan has a discussion about symmetry on an old blog post (Achieving Code Symmetry), and includes examples from Kent Beck's Implementation Patterns book. I also like structural symmetry. It sounds silly to judge code based on it's...

If Software Was Like The Super Bowl

We'd have cheerleaders, fans, and of course . . .  reporters to write about it all. V-TPS Team Defeats Milestone 6 in Overtime Ken Hoethlisberger came out of the project war room with a huge smile and a fist pump. "We did it!", he shouted. "We shipped!" When asked about the victory, Ken gave credit to his hard working team. "All the sprints, the analysis, the design - it all paid off in the end." The release was a sweet redemption for project manager Hoethlisberger, who missed the first four weeks of the year after being...

Make It Yours

I went to a general store, but they wouldn't let me buy anything specific. - Steven Wright. One of the challenges of working with a general purpose programming language (like C#) and a general purpose framework (like ASP.NET, Silverlight, or any other application framework) is building something specific. The trick is to apply constraints and build abstractions to take ownership of the situation, and there is an entire bag of fancy tricks to pull from, like using fluent APIs or applying domain driven design. But taking real ownership goes beyond just building the right classes -...

JavaScript Koans

Programming koans liberally borrow from Zen Buddhism to teach programming. If you look around the Internet, you'll find koans to learn Ruby, koans to learn functional programming, and thanks to Liam Mclennan, you can alse use koans to learn JavaScript. From the readme: JavaScript Koans is an interactive learning environment that uses failing tests to introduce students to aspects of JavaScript in a logical sequence. The inspiration for this project comes from the Edgecase Ruby Koans and the book 'Javascript: The Good Parts'. Open the file jskoans.htm in your favourite browser and make the tests pass. ...

Scott Allen
Posts - 869
Comments - 4493
Stories - 14