What’s The First Thing To Learn About ASP.NET MVC?

Monday, November 30, 2009 by K. Scott Allen
29 comments

If you are an ASP.NET Web Forms programmer making the switch to ASP.NET MVC – what’s the first thing you should learn?

There are lots of candidates for the number one spot. Some people will say the first thing to do is learn and embrace the spirit of the MVC design pattern. Others might say you should learn how to unit test a controller, or learn how to use a view model.

fill out your forms! My answer is:

Learn how to use an HTML <form>.

Please excuse the ASP.NET web forms programmer who forgets about the <form> tag. Although every .aspx file has one, they never need to touch it, or even look at it. The form tag is not only well hidden, but also constrained. It only take a few years to start thinking the web revolves around pages that only submit information back to themselves.

The most important things to lean (or relearn) are:

  • You can use the method attribute of <form> to specify the HTTP method to use for  submission (GET or POST).
  • You can use the action attribute of the <form> to submit information to any URL.
  • You can have multiple <form> tags on a single page.

Let’s look at each case.

Method Attribute – GET versus POST

There are two types of requests a web browser will use when communicating with a web server – POST requests and GET requests. Both are designed to do what they sound like – GET a response, or POST some information and receive a response. Web forms always use POST methods. HTTP POST is the best method to use when you are submitting information to a web server and changing state in your application. For example, if a user fills out a <form> with textbox and radio button controls full of patient information you want to save in a database, then POST is the HTTP method you should use. The browser will POST the user’s values to the server where you can save them in the database, and then you can respond and tell the user everything worked (or tell them something blew up).

On the other hand, an HTTP GET operation operation is the best way to submit information to a server when you are not changing state inside the application. The best example is a form used to search for information. You need to send search parameters to the server, but the search parameters aren’t creating new records in a database – they are only used as to query information.

image <form action="/search" method="get">
    <input type="text" name="searchTerm" />
    <input type="submit" value="Search" />
</form>

If the user enters “baby blue bathysphere” into the textbox and clicks the button, the browser will send off a GET request with the following URL:

 /search?searchTerm=baby+blue+bathysphere

Notice how the submitted form values are placed in the URL itself. Not only is a GET operation cacheable, but users can also bookmark the response to a GET submission because all the information needed to produce the page is in the URL. GET is the default value for the method attribute of a <form>, so if you don’t specify the method you’ll have a GET by default.

Actions

ASP.NET web forms always POST to themselves, which can be limiting. As the previous example demonstrates, you can set the action attribute to submit a form to any URL, even a URL pointing to another application on a different server. For example, the following HTML would send the user to Google (both Google and Bing both expect the search parameter to have the name “q”).

<form action="http://google.com/search" method="get">
    <input type="text" name="q" />
    <input type="submit" value="Search" />
</form>

You’ll usually be setting the action attribute to submit information to some controller action in your MVC application. The Html.BeginForm helpers will help build the correct <form> tag to reach the desired action for you. If we were using the first code-snippet in this post (the one with an action of “/search”), we could respond to the search request with the default action of a SearchController. The MVC framework can automatically pass the searchTerm form parameter as a parameter to the action.

public class SearchController : Controller
{
    public ActionResult Index(string searchTerm)
    {
        // ....
        return View();
    }
}

Two Forms Are Better Than One

Well … not always.

There are times when having multiple <form> tags on a page is a good idea. You can have two distinct pieces of a page submit information to two different URLs. Multiple <form> tags regularly make sense on portal type pages that contain multiple sections with disparate functionality. Like an area that lets a user get a stock quote, and an area that lets a user search for a movie. These are two different tasks that will probably best be handled by two different controllers, two different URLs, two different forms, and two different sets of input controls.

<form action="/stock/quote">
    <input type="text" name="symbol" />
    <input type="submit" value="Quote It!" />
</form>

<!-- ... --->

<form action="/movie/search">
    <input type="text" name="q" />
    <input type="submit" value="Search" />
</form>

Not every scenario requires multiple forms, however. Sometimes you want a single form to provoke different behaviors from the server. For example, imagine a shopping page where a user selects some check boxes for products they are interested in. You might need a button allowing the user to submit this information to “compare products” and another button allowing the user to save the selected items in a “wish list”. Both buttons need to submit the same information to the server, so they’ll probably live inside the same form

<form action="products/shop" method="post">
    <!-- -->
    <input type="submit" name="task" value="Compare" />
    <input type="submit" name="task" value="Save to wish list" />
</form>

Both buttons in the above form will force the browser to POST to products/shop. Notice how both buttons have the same value for the name attribute, but their values are different. In an MVC application you can create a controller to accept this form submission:

public class ProductsController : Controller
{
    [AcceptVerbs(HttpVerbs.Post)]        
    public ActionResult Shop(string task)
    {
        // ...
        return View();
    }
}

The value of the task parameter in the Shop action will contain the value of the button – either “Compare” or “Save to wish list”. You can inspect this value and decide what to do next.

Conclusion

Having <form> tags available to due your bidding in an MVC application allows you a great deal of flexibility and control. Every bit you learn about using forms will give you an edge in building your application. Experiment with them, read about them, and learn to love them!

CSS Resets

Sunday, November 29, 2009 by K. Scott Allen
8 comments

reset buttonEvery web browser has a default style sheet it uses when rendering content, and every web browser uses slightly different defaults. Perhaps a button will use an extra 2 pixels of width in one browser, but 3 fewer pixels in another. These differences are insignificant to many of us, but they worry some designers and keep them awake at night. This is where CSS reset style sheets come into play.

The goal of a CSS reset style sheet is to set the default styling for all HTML elements into a known state. A good CSS reset will effectively “undo” all the default styles any web browser might define. The CSS designer can then built their own style rules and feel relatively confident that a design will look the same across all browsers and environments.

For example, here is what you will be starting with after applying the YUI Reset CSS:

  • Black text on a white page background
  • Margin and padding for all elements set to zero
  • Table borders set to zero
  • All fonts sized 100% of base
  • Font-weight and font-style set to normal
  • and more …

There are a few CSS resets available on the web:

Note that YUI and Blueprint both include a CSS reset as part of a larger CSS framework.

Should I Be Using A CSS Reset?

This is the subject of some debate.

Some people feel a CSS reset creates more work – both for the designer and the web browser. The designer has to start from scratch and will write more CSS style rules to design a page that has been stripped of all aesthetics by a CSS reset. Naturally the browser will also work harder to process all these additional rules and cascades. 

But, if you care deeply a design, and how that design will render around the universe, then you won’t mind any of the extra work. CSS reset can be good.

As Eric Meyers says in his post “Crafting Ourselves”:

Reset styles clearly work for a lot of people, whether as-is or in a modified form. As I say on the reset page, those styles aren’t supposed to be left alone by anyone. They’re a starting point. If a thousand people took them and created a thousand different personalized style sheets, that would be right on the money. But there’s also nothing wrong with taking them and writing your own overrides. If that works for you, then awesome.

For others, reset styles are more of an impediment. That’s only to be expected; we all work in different ways. The key here, and the reason I made the approving comment above, is that you evaluate various tools by thinking about how they relate to the ways you do what you do—and then choose what tools to use, and how, and when. That’s the mark of someone who thinks seriously about their craft and strives to do it better.

Eric’s commentary applies to many of the tradeoffs we face in software development.

Is Microsoft Taking Dynamic Languages Seriously?

Monday, November 23, 2009 by K. Scott Allen
11 comments

Specifically IronPython and IronRuby.

Consider this …

  • IronPython got underway in July of 2004. Five years later it appears IronPython is still not a candidate to be a first class language in the .NET framework and tools. You can vote on this issue.
  • Microsoft first released IronRuby at Mix in 2007. Nearly three years later it appears IronRuby is still not a candidate to be a first class language in the .NET framework and tools. You can vote on this issue.

A first class language is deployed when the full .NET framework is installed. It’s as easy to find as csc.exe. It’s not a language you have to ask the IT department to install separately. It’s not a language that requires you to jump out of Visual Studio to edit or run.

Most of all, a first class language doesn’t require justification to higher powers. A first class language is pre-certified and stamped with a seal of approval. It’s as easy to use in the locked-down big corporate setting as the company paper shredder.

shredder

The DLR and the PDC

I was depressed when I read the session list from Microsoft’s recent Professional Developers Conference. If you browse the session list you’ll find hundreds of sessions covering cloud computing, Sharepoint, Silverlight, SQL Server, and modeling. There are a handful of sessions covering concurrency, and a few dedicated to C++.

There is exactly one session featuring the Dynamic Language Runtime in a significant fashion. The title is Using Dynamic Languages to Build Scriptable Applications. You can learn how to augment an existing application after you’ve done all the real work in a first class language.

Perhaps Microsoft is just hedging their bets, but it’s clear that that dynamic languages aren’t high on the priority list. Maybe they’ll be first class citizens one day, but many developers are tired of waiting.

P.S. Is Managed JScript dead?

Keeping CSS Files DRY with .less

Sunday, November 22, 2009 by K. Scott Allen
16 comments

dotless - a LESS css port for .NETIt was just a few weeks ago when I heard of LESS for Ruby, and now there a port for .NET developers: .less (dot less).

One of the frustrating aspects of working with CSS (one of many, actually) is the amount of duplication in a .css file. CSS does allow us to separate content from presentation, but, if I had a nickel for every time I did a search and replace for some hexadecimal RGB code replicated 5 times in a CSS file, I’d buy each of you an interactive t-shirt.

.less help to keep your CSS files DRY using 4 constructs:

  • Variables
  • Mixins
  • Operations
  • Nested Rules

The examples on the .less home page are self-explanatory. For example, variables:

@gold : #cccc99;

body {
  background-color: @gold;
}

“Mixin” is a Ruby concept, and with .less the you can “mix” one style rule “into” another.

.rounded_corners {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}
 
#header {
  .rounded_corners;
}

How’s It Work?

You enter your styles into a file with a .less extension and include them in a view or web form just like any style sheet.

<link href="/Content/Site.less" rel="stylesheet" type="text/css" />

An HTTP handler is configured to respond to requests for the .less files.

<httpHandlers>
    
  <add validate="false" path="*.less" verb="*"
    type="dotless.Core.LessCssHttpHandler, dotless.Core" />
              
</httpHandlers>

When a request arrives for a .less file it is the handler’s job to parse the .less file and transform it into standard CSS rule sets. .less does this using PEG Lib and offers the ability to both minify and cache the resulting CSS.

The source code is available on GitHub, so check it out for yourself. .less will let you write lean, mean style sheets.

Improving JavaScript Skills

Tuesday, November 3, 2009 by K. Scott Allen
6 comments

A few people have asked me how to improve their  JavaScript ability. Not just learn about syntax and crazy stuff like closures, but how to apply the same design skills they have in their primary language(s) to the code they stuff into .js files.

I think the key is to submerse yourself in JavaScript for an extended period of time. So often in web development we context-switch into JavaScript mode to bang out a few client-side event handlers, then jump right back into the server code. I’m not suggesting you try to write all the JavaScript code for a web site all at once (that’s just silly), but you could try a code kata with JavaScript every now and then.

Uncle Bob has a nice bowling game Kata. It’s written in Java, however, you can play along with any other language, including JavaScript.

Here’s how to start (for ASP.NET developers):

1. In Visual Studio, select File –> New –> Web Site.

2. Delete the Default.aspx file.

3. Download jQuery and qUnit (both qUnit.js and qUnit.css). Add them all to the root of the site.

4. Add a new HTML page to the web site with the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <link href="qunit.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="qunit.js" type="text/javascript"></script>

  <script>        
    
  </script>
  
</head>
<body>
  <h1 id="qunit-header">JavaScript Code Kata</h1>
 <h2 id="qunit-banner"></h2>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
</body>
</html>

5. Start practicing.

As an example, here is what you might have inside the script tags by slide 18 on Uncle Bob’s Bowling kata:

test("Test Gutter Game", function() {
   
    var game = new Game();
    
    for (var i = 0; i < 20; i++) {
        game.roll(0);
    }
    
    equals(0, game.score());
});

And by slide 19 you’ll make the above test pass. You might have the following code (inside the script tag, or you could put it in a separate .js file).

function Game() {

}

Game.prototype = {
    roll: function(pins) {

    },

    score: function() {
        return 0;
    }
};

Once you get to the end, try some other katas. Or, try the same kata with a different style (like avoid for loops, as an example). Everything gets easier with practice.

JavaScript submersion is fun (and makes you better too).

BitLocker To Go

Monday, November 2, 2009 by K. Scott Allen
5 comments

I had some data on a Cruzer flash drive I wanted to protect, and I just discovered how easy it use to use BitLocker on a flash drive (thanks to Hanselman, who pointed this out in one sentence at the end of a post).

BitLocker is another Windows 7 feature that has been around since Vista, but BitLocker To Go (encryption for removable drives) is new.  I believe it is only available on Win7 Ultimate and Enterprise.

Once the drive is inserted, right-click the drive in Windows Explorer and select “Turn on BitLocker…”. Windows will ask if you want to unlock the drive using a password or a smart card + PIN. I took the password option:

bitlocker to go setup

Encryption can take some time (~ 15 minutes for my 4GB flash drive).Windows will place a BitLocker To Go “reader” application on the drive so you can have read access to files from Vista and XP machines (bitlockertogo.exe). Note: the down-level reader only works if the drive was not formatted with NTFS. It’s interesting to read about how this works:

Getting BitLocker To Go functionality to work on Windows XP and Windows Vista required some reengineering of the core BitLocker feature. To do this, the team refactored the method by which BitLocker protects FAT volumes. BitLocker behavior was modified to overlay a "discovery volume" onto the physical, original volume and virtualize the blocks overwritten. The discovery volume contains the BitLocker To Go Reader as well as a readme file. This is called a Hybrid BitLocker drive. By default, when a FAT drive is encrypted, a hybrid BitLocker drive is created. The discovery drive is visible only on the Windows XP and Windows Vista operating systems.

I always thought encrypting my entire system hard drive was a little bit scary. I like BitLocker To Go because it is built-in, and can protect a removable device where I keep sensitive files.

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!