codethinked (kōdthĭngked) adj. To be consumed by or obsessed with code.

Controls Do Not Make You More Productive

I can't believe I'm involving myself in this conversation. In fact, as I write this I am dying a little bit on the inside. Both Nate and Rob are probably going to shake their heads in disgust at me, but I've come across two blog posts today that have made my skin crawl a bit, and so I feel I have to dip my toe into this water. And so here it goes....

CONTROLS DO NOT MAKE YOU MORE PRODUCTIVE.

I seriously thought about putting some nice "marquee" tags around that, maybe a little blinking would help drive the point home.

But there, I said it. You people need to get over your control obsession. Whenever I see people comparing MVC and Web Forms, it is always "MVC is less productive because it doesn't have controls." People will acknowledge that MVC has "helpers", but helpers apparently don't fill the same role as controls. Oh, the argument is that MVC gives you more control, but since I can't drag and drop a bunch of stuff on a form, then it makes me sooooooo slow. <insert your own picture of Eeyore here>

Continue reading the rest of this post...

5 Blogs ASP.NET MVC Developers Should Be Following

I’m a huge fan of ASP.NET MVC (I’ve blogged about it several times) and, like many of you, I’ve been looking around for some good real-world tips on performing different tasks in ASP.NET MVC. There are several major bloggers that have been dropping some good ASP.NET MVC info over the past few months, but unless you are under a rock, you have already heard about Scott Guthrie, Scott Hanselman, Rob Conery, and Phil Haack. You are probably following them, even if you aren’t doing ASP.NET MVC work. But I wanted to put together a list of the slightly less well known blogs which are great sources of ASP.NET MVC information, and most of them are currently almost exclusively focused on it.

Simone Chiaretta’s CodeClimber - A good friend, and a better blogger. Simone is an ASP.NET MVP and is co-writing the book “Beginning ASP.NET MVC 1.0” by Wrox. Simone blogs about all sorts of different ASP.NET MVC topics, and will certainly bring tons more content once he finishes his book. He is also an active developer on the Subtext project.

Stephen Walther - Stephen is a Senior Program Manager at Microsoft where he creates much of the tutorial content on the www.asp.net/mvc website. Somehow he also finds time to put up tons of helpful posts on his personal blog. He is also authoring the book “ASP.NET MVC Framework Unleashed” by Sams.

Kazi Manzur Rashid - Kazi is surprisingly the only person on this list who isn’t writing a book! He is also an ASP.NET MVP and his claim to fame is dotnetshoutout.com (which is a great site) and the open source Kigg project. He writes tons of posts on ASP.NET MVC, and has recently been on quite a run with many lengthy and in-depth articles.

Maarten Balliauw - Maarten is authoring the book ASP.NET MVC 1.0 Quickly by Packt. I’m not sure how Maarten has time to write the book and his blog, because he has been pumping out quite a few awesome ASP.NET MVC posts recently.

Steve Sanderson - Steve is the author of Pro ASP.NET MVC Framework by Apress and like these other guys, still finds time to write some good informative posts on his blog. He is also the author of the xVal validation framework which aims to help developers more easily tie domain validations to the front-end web application.

Luis Abreau – This one is a bonus, and was added because of Marwan's comment below. I went and checked it out, and there are many great little ASP.NET MVC tidbits on this guys blog. Too bad there isn't much information about him at all. It looks like he might be a current or former MVP, I don't know. He has a linked in profile, but not too much info there other than the fact that he is in Portugal. So lots of good ASP.NET MVC information, but other than that, I don't know what to tell you about the guy!

If you are out there and looking for some excellent ASP.NET MVC expertise, you may want to start following these guys blogs. They are producing great real-world ASP.NET MVC info on almost a daily basis. Hope this helps!

File Uploads in ASP.NET MVC 1.0 RTM

I had not messed around with file uploads in ASP.NET MVC for a while and so when I fired up ASP.NET MVC 1.0 RTM I was pleasantly surprised to find out how easy they had made it! That is all…

Just kidding! I’m going to show you exactly how to do it, and even better, I’m going to show you how to test it! How about that?

Before we start off you need to know that in order for a form to post uploaded files you are going to need to add a particular enctype attribute to the form. In order to do this, we need to create a form tag like this:

<% using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>

Then we just need to add an input of type “file” onto the form along with a submit button. You must be sure to put at “name” attribute on the input. We can also put whatever else we want on the form:

<table>
    <tr>
        <td><input type="file" id="picture" name="picture" /></td>
    </tr>
    <tr>
        <td><input type="submit" value="Upload" /></td>
    </tr>
</table>

Now that we have our form and the html to go into it, we are ready to get this sucker on the server side. In my first attempt to upload a file I tried to put in a model binder in order to upload the file, only to find out that there was already one there! So all we have to do is this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(HttpPostedFileBase picture)
{
    if (picture != null)
    {
        picture.SaveAs("C:\wherever\" + picture.FileName);
    }
}

Pretty easy! Now all that is left is to test it. I am going to use Moq 3, and we just need to mock out the file and pass it into the method:

var personPicture = new Mock<HttpPostedFileBase>();
personPicture.Setup(i => i.FileName).Returns("person.jpg");
personPicture.Setup(i => i.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes("")));

var controller = new PersonController();
controller.Edit(personPicture.Object);

personPicture.Verify(p => p.SaveAs("C:\wherever\person.jpg");

Wow. All we had to do was mock out the image, fake a few properties and then call the method on the controller and then verify that the proper method on the picture was called. Simple as that!

Hopefully you already knew about this, but if you didn’t, then I hope that you enjoyed this post!

Spiff Up Your ASP.NET MVC Forms With jQuery

Since many people who are being introduced to ASP.NET MVC are being simultaneously introduced to jQuery I felt like I’d give you a quick introduction to a few jQuery plug-ins that will help you make better forms. But most importantly make your forms better without you really having to do too much to them.

What I am going to show you here is nothing new, but hopefully it will introduce a few people to the joys of jQuery plugins. The plugins that we are going to take a look at are jquery.blockUI, jquery.form, and jquery.datePicker. We are also going to introduce you to a good bit of standard jQuery.

But first, let’s start off by talking about what each of these plug-ins will do for you. The blockUI plugin will give you that cool effect that overlays the UI with a modal dialog and fades out the background. The form plugin lets you post forms via javascript. The datePicker plugin does exactly what it says, it creates date pickers. The jQuery UI project has a date picker as well, but this is just a simple usable date picker.

Our goal is to end up with a form that has watermarks:

Watermark

Row Highlighting:

Row Highlighting

Hovering help messages:

Hovering Messages

Ajax Submit with Modal Dialog:

 Modal Dialog

And a date picker:

Date Picker

First we are going to start off with a simple ASP.NET MVC form:

<div id="messages"></div>   
<% using (Html.BeginForm()){ %>        
    <fieldset>
        <legend>Personal</legend>
        <div class="formitem">
            <label for="FirstName">First Name:</label>
            <%= Html.TextBox("FirstName", Model.FirstName, new { watermark = "First", title = "Please enter your first name." }) %>                
        </div>
        <div class="formitem">
            <label for="LastName">Last Name:</label>
            <%= Html.TextBox("LastName", Model.LastName, new { watermark = "Last", title = "Please enter your last name." }) %>                
        </div>
        <div class="formitem">
            <label for="DateOfBirth">Date of Birth:</label>
            <%= Html.TextBox("DateOfBirth", Model.DateOfBirth, new { Class="date-pick", watermark = "mm/dd/yyyy" }) %>
        </div>
        <div class="formitem">
            <label for="EmailAddress">Email Address:</label>
            <%= Html.TextBox("EmailAddress", Model.EmailAddress, new { watermark = "name@example.com", title = "Please enter your e-mail address." })%>
        </div>
        <div class="formitem">
            <label for="Street">Street:</label>
            <%= Html.TextBox("Street", Model.Street, new { watermark = "Street", title = "Please enter your street address." })%>                
        </div>
        <div class="formitem">
            <label for="City">City:</label>
            <%= Html.TextBox("City", Model.City, new { watermark = "City", title = "Please enter your city." })%>                
        </div>
        <div class="formitem">
            <label for="State">State:</label>
            <%= Html.TextBox("State", Model.State, new { watermark = "State", title = "Please enter your state." })%>                
        </div>
        <div class="formitem">
            <label for="PostalCode">Postal Code:</label>
            <%= Html.TextBox("PostalCode", Model.PostalCode, new { watermark = "Postal Code", title = "Please enter your postal code." })%>                
        </div>
        <div class="submit">                
            <input type="submit" name="Submit" />                
        </div>
    </fieldset>        
<% } %>

Looks good. It is a bit non-standard, but lets not dwell. First lets look at one of the Text Boxes that we are rendering:

Html.TextBox("FirstName", Model.FirstName, new { watermark = "First", title = "Please enter your first name." })

We are passing the name, model property, and then an anonymous type that renders out html attributes. The tag above will render out an input tag like this:

<input type="text" watermark="First" value="" title="Please enter your first name." name="FirstName" id="FirstName" class="watermark" />

So yes, the watermark attribute is non-standard and won’t validate. Sadly, with the html 4 spec there just isn’t a good place to shove data like this on a tag. jQuery has a way to store a piece of data with a tag, and it is the data method. Perhaps in the future I will implement something to make assigning this to each form field easier, but for now you can deal with my non-standard tags. This non-standard tag is how we are going to apply our watermarks to our fields.

What we have here is a pretty vanilla form and now we need to add a bit of flare to it. The first thing we are going to do is include all of our javascript files:

<script src="../../Scripts/jquery-1.3.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.form.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.blockUI.js" type="text/javascript"></script>
<script src="../../Scripts/date.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.datePicker.js" type="text/javascript"></script>
<script src="../../Scripts/spiffy.js" type="text/javascript"></script>

Here we have imported jQuery, the plugins that we are going to use, and my own little creation “spiffy.js”. This is where all of our code will go in order to make the magic on the form.

Okay, so you have seen where we are going, and what code that we are starting off with, and so what is left? You may be saying, is all of the rest accomplished entirely in jQuery? And the answer is, “yep”. So now lets look at the “spiffy.js” file and pick through it piece by piece.

jQuery “ready” Method

First we are going to use the jQuery method that you will see in any jQuery site:

$(document).ready(function() {
    //Magic goes here!
});

This allows us to put in javascript that will be executed after the page has been fully loaded. The rest of the javascript that you see here is going to go inside of the above function.

Date Picker

First we are going to look at how to apply the date pickers. In order to do this we are going to first make the first day of the week Sunday (which we tend to do here in America) and we are going to reset the date format to an American format as well.

// date pickers
Date.firstDayOfWeek = 7;
Date.format = 'mm/dd/yyyy';
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');

Then we use the jQuery “$(‘’)” method in order to find the field by class name. Then we simply call the “datePicker” method on the resulting field (or fields) and set a few options. This post is going to be long enough already so I’ll let you look them up.

Watermarks and Row Highlights

Next we are going to set our watermarks and row highlights. If you don’t mind putting code on the page to create the watermarks, then there is already a watermark plugin available. We want to just pull the watermark attribute though and use that in order to create the watermarks. This is going to require a bit of custom jQuery code, but nothing inside of each page:

// watermarks and row highlights     
$("[watermark]").each(function() {
    this.value = $(this).attr("watermark");
    $(this).addClass("watermark");
})
.focus(function() {
    if (this.value === $(this).attr("watermark")) {
        this.value = "";
        $(this).removeClass("watermark");
    }
    // add row highlight
    $(this).parents(".formitem").css("background-color", "#ddd");
})
.blur(function() {
    if (this.value === "") {
        this.value = $(this).attr("watermark");
        $(this).addClass("watermark");
    }
    //remove row highlight
    $(this).parents(".formitem").css("background-color", "");
});

Okay, so it looks big at first, but let’s break it down into a few different parts. First you’ll see the “$(‘’)” method again, followed by the “focus” method and then the “blur” method. If you look at each piece separately then you’ll find it much easier to understand.

First look at the “$(‘’)” method we use to find our elements, but we use the ‘[attribute]’ syntax to look for elements that have a particular attribute. Then we call “each” in order to loop through each field that we have found. We pass a function into the method to run on each element. What it does is set the field’s text to the text of the watermark and then applied the “watermark” class to the field. The “watermark” class is what we use to give the watermark text that “grayed out” look.

Next you’ll see the “focus” method that allows us to tie a method to the “focus” event on each field. Every method in jQuery that doesn’t do any kind of filtering will pass the same set of elements on to the next method which allows us to “chain” methods together and is one of the biggest selling points of jQuery. But anyways, the function that we pass to “focus” isn’t going to get executed right away. Instead, it will get executed whenever we enter one of the fields with a “watermark” attribute.

This function is checking to see if the text in the field is equal to the text of the watermark and if so, it sets the value to an empty string so that we can enter our own text in. It also removes the “watermark” css class so that our text is not grayed out. After that you will see that we are applying a row highlight the parent of the current field that has the class “formitem”. This allows us to highlight the current row that we are editing. Here we are using jQuery to set the color of the row directly, but most likely you would do what i did in the code just before it and set a class name. I did it this way to show how easily jQuery allows you to modify css directly.

And finally we get to the “blur” event which fires when the focus leaves the field. In the function passed to this you’ll see that we are reapplying the watermark if nothing was entered and putting the “watermark” class back. We are also resetting the row color back to nothing. Again, you probably don’t want to do this because if the row had a color already, we’d be resetting it.

Resetting the Watermarks on Postback

The above code has one issue (it is possible it has others) and that is when you submit the form, the watermarks will be sent back to the server unless they are removed before postback. This will require one more little bit of jQuery.

//remove watermark when form is submitted
$("input:image, input:button, input:submit").click(function() {
    $(this.form.elements).select("[watermark]").each(function() {
        if (this.value === $(this).attr("watermark")) {
            this.value = "";
        }
    });
});

In this javascript we find all of the inputs of type image, button, and submit and add a method to the click event. The method that we attach first looks for all form elements for the clicked element and then filters it down to only elements that have “watermark” attributes and then loops over each comparing the current text to the watermark text. If they are equal then the value of the element is cleared out. It might look a bit complex, but with the chaining abilities of jQuery it all becomes so easy!

Help Messages

Next we are going to look at those fancy help messages that will pop up next to our fields when we enter them.

// tooltips                
$(":text[title]").focus(function() {
    var field = $(this);
    field.after("<p id='tooltip'>" + this.title + "</p>");
    var position = field.offset();
    $("#tooltip")
        .css("top", (position.top + 10) + "px")
        .css("left", (position.left + field.width() + 10) + "px")
        .fadeIn("slow");
})
.blur(function() {
    $("#tooltip").remove();
});

The first thing we do here is find all input elements of type “text” with a “title” attribute and attach a method to the focus event so that it fires when the field is entered. The first thing we do is get the current field using $(this) and then calling the “after” method on it in order to add an element into the page after the current field. The element inserted will be a paragraph tag with a “tooltip” id and the text of the “title” attribute. Then we position the tooltip relative to the current field. After that all we have to do is add a method to the “blur” event to remove the tooltip upon exit.

Ajax Postback With Modal Dialog

And finally…man this post is getting out of hand. But now that we are starting to get used to jQuery we can move a bit quicker through this one. Here we are creating an object using JSON notation. So you can see that we are assigning the variable “options” a set of curly braces with some crap in it! Basically it is an object with two properties, one called “beforeSubmit” and one called “success”. Each of these properties are methods that contain code to execute when these two events happen. Then we have a property called “dataType” that we are just assigning a string of ‘json’.

Now you may be wondering where all of this is coming from, and it is simply a data structure that the “form” plugin knows about and can use to configure itself. As you can see, after we create this object we then pass it into the “ajaxForm” plugin method after we find the form on the page.

var options = {
    beforeSubmit: function(formData) {
        $.blockUI();
        formData.push({ name: 'ajax_submit', value: '1' });
    },
    success: function(result) {
        $.unblockUI();
        if (result.length == 0) {
            $("#messages").empty().append("Thanks!");
        }
        else {
            var list = $("#messages").empty()
                .append($("<ul class=\"errors\">"));
            jQuery.each(result, function(index, item) {
                list.append($("<li>").append(item));
            });
        }
    },
    dataType: 'json'
};
$("form").ajaxForm(options);

So in the “beforeSubmit” method the first thing we do is call the “block” plugin that causes a modal dialog to display during postback. Then we call “formData.push” which submits the form back to the server while setting the “ajax_submit” post variable so that ASP.NET MVC can tell that this is an ajax postback.

In the “success” method we first “unblock” the ui and check the result length to see if we got anything back in our result array. If the length is 0 then we just append “Thanks!” into our “messages” div. If we do get a list of messages back then we clear the “messages” div and append an unordered list with a class of “errors”. Then we loop through item in our array of messages and append list items for each. Since we told the "form” plugin that we were expecting a “json” datatype we knew that we could just pass back a json array and it would interpret it automatically.

Just to get it working I simply added this code inside of the controller method:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection formData)
{
    if (Request.IsAjaxRequest())
    {
        return Json(new string[] { "Test Text!", "Test Text 2!" });    
    }
    else
    {
        return View(new Person());
    }
}

So if we detect that it is an ajax postback then an “ActionResult” of type JsonResult is returned. I have the array hardcoded with two messages for test purposes, but you get the idea. The array is serialized into json by the “Json” method on the controller class.

Summary

Phew. That was a long freaking post. We saw how to add watermarks, row highlights, date pickers, hovering tooltips, and ajax submitting to our web form. The whole point here is to learn something, and I hope you did. I know that there are probably a dozen things that could be done in a better way, and if you see any of them please let me know in the comments. If you want to look at the source, you can find it below.

Click here to get the source.

How Do We Measure Maturity In Software?

Freedom

When I saw a post by Jeffery Palermo entitled “Is Classic WebForms More Mature Than ASP.NET MVC?” I immediately thought “Aha! I know exactly what he means!" And then I read his article and realized that while the post was good, it wasn’t at all about what I thought it was going to be.

In his article Jeffery talks about the platform and the tools which are still in place from “classic” asp.net as a means of showing that all we are doing is really just switching out the top layer software abstraction. We still have this proven, reliable, robust base that is underneath running the whole thing. And trust me, I completely agree with this sentiment. What I thought he was going to point out though is a slightly different scenario, and it requires us to narrow down a bit our definition of what exactly “mature” software is.

So, what is mature software?

Is mature software defined by the amount of time that the software has been on the market? Many times we will call a person mature because they have been around for a long time, but I highly doubt that we should be measuring software maturity based on whether or not it would get a discount at the Shoneys buffet. Sure, you could argue that software which has been around longer has had more time to shake the bugs loose, but unless someone is fixing those bugs, I wouldn’t say that software ages like a fine wine or anything.

If software’s maturity cannot simply be measured by how long it has been on the market, yet time in the market is clearly an indicator of how mature a piece of software is, then what is the factor that we are measuring here? I would say that we are measuring the software’s evolution in two distinct ways.

First we are measuring how “solid” the software is. This can be broken down into several different qualities as well, but I will just stick with a measure of defects. Over time the number of defects will hopefully be on the decline as a piece of software matures.

Second we are measuring how well the software has evolved to fill its role. Over time we assume that a piece of software is going to change with market pressures to become something that fills its role better than when it was originally released. This is a relative measurement, but given a particular piece of software you could probably find some ways to measure it. I think that this measurement also includes how well a piece of software has adapted to keep up with its market, as its market is changing.

Overall I think that this points to the fact that what we are really measuring is the delta of a tool’s effectiveness. Over time tools tend to become more and more effective. Whether it is because a new feature is added or because bugs have been found  and removed, software usually becomes more “mature” over time because we have had a chance to make it better.

So if we measure ASP.NET WebForms and ASP.NET MVC against these measurements, then where does each fall?

ASP.NET WebForms clearly has an advantage when it comes to time on market, but how does it stack up when we start looking at defect numbers? Well, the release early and often approach that the ASP.NET MVC team has taken will almost certainly result in fewer bugs in the initial release of ASP.NET MVC versus ASP.NET WebForms. ASP.NET MVC has had 6 preview releases, a beta, a release candidate, and a release candidate refresh, all the while the source code was completely available to the public. People have been running production sites on this code for almost a year now. Let’s just suffice to say that the quality is going to be high, and will likely be higher than the code coming out of ASP.NET WebForms.

Now, when it comes to measuring how well a piece of software has evolved to fill its role… well… I’d actually say that ASP.NET MVC has a huge advantage in this space. ASP.NET has really only had two major releases with some service packs in between. As I said earlier ASP.NET MVC has already had 9 public releases with significant changes during each release that were in direct response to customer feedback! I would say that ASP.NET MVC has evolved more to what the market has demanded in its short life than ASP.NET WebForms has in its entire life. Now this is due to the fact that Microsoft has to keep ASP.NET WebForms stable and can only really add features onto the periphery,  but I don’t think this fact negates the speed at which ASP.NET MVC has been changing.

I just don’t think the concern about ASP.NET MVC not being mature is a valid concern, and sounds more to me like people that just don’t want to invest into moving to another platform. ASP.NET MVC is solid, evolving, and will also have a ton of community support through projects like MvcContrib. ASP.NET MVC will also be an out of band product which will allow it to evolve faster, and keep up with customer demand. Whether this will affect its long term stability will remain to be seen.

The question that I hear over and over again is will ASP.NET MVC end up eclipsing WebForms? I think the jury is still out big-time on that one. It is all going to come down to how well Microsoft pushes and endorses the platform, but so far it is looking pretty good. I just hope that people don’t use the excuse that ASP.NET MVC is immature as a reason to not even give it a second look.