Using the 960 Grid System for Layout
May 5th
So I’ve been using the 960 grid system for over 6 months now and I have learned a thing or two that could be helpful to those looking at using it as well. If you don’t already know, 960.gs is a css framework to help you quickly enable layouts and help ease the pain of cross browser compatibility. I will start by laying out the pros and the cons of the 960 and then show you how to overcome possible gotchas.
The Pros
This is what you want to hear right, how is 960.gs going to make your layout easier to manage and create. Well let’s start then.
- Complex layouts relatively fast.
- Consistent layout (IE, Firefox, Chrome, …)
- Reusable and Flexible
- Easy to learn
The Cons
Ok so some of the down sides of using 960.gs, cause there are some obvious ones.
- More stylesheets ( 960.gs, reset.css, text.css and then yours)
- Respect it or it will bite back
- Divitus (lots of div tags based on your layout)
- Everything you need to do isn’t a grid
- not semantic (grid_12 is not expressive)
- multiple css classes on one element
Overview
by default the 960.gs is split into either a 12 column grid or a 16 column grid. I will focus on the 12 column grid. Each column in a 12 column grid is 60px wide with a margin of 10px on each side. You can see that below the max content area you can have is 940px, while the container expands to 960px due to the 10px margin on each side. You can also see that the margin between two columns is 20px, because each column has a 10px when two columns margins combine they make 20px. And finally, a div tag can span multiple columns and it’s length is made up of all the columns it spans and 10px of margin on each side.
ex. a column that spans 11 columns is 880px. column: 60px + 10px + 10px. 11 x 80px = 880px total : 880px with outside margins and 860px without outside margin (content area).
Ok that was a lot of math, but you only need to know how to count up to 12 or 16 to use this system. No need to do this math because it is done for you automatically. The point of the math is to show you that the box model is important to understand. Margin is outside of your div tag, while everything else is inside.
Example – The Basics
So you are curious about the above example, how what does the HTML look like? It looks like this.
<div class="container_12"> <h2> 12 Column Grid </h2> <div class="grid_12"> <p> 940 </p> </div> <!-- end .grid_12 --> <div class="clear"></div> <div class="grid_1"> <p> 60 </p> </div> <!-- end .grid_1 --> <div class="grid_11"> <p> 860 </p> </div> <!-- end .grid_11 --> </div>
Simple right, you see that we use a div with a class of container_12. This is used to help center your page and give a place to start laying out your page. The next thing you will see is grid_12. That is telling that div to span the whole way across, and it is then followed by grid_1, and grid_11. You can guess that we are specifying that the first div is a size of one column, while the next is 11 columns. The div with a class of clear forces the grids to the next line, but I have found if your rows always add up to 12 you can forgo the clearing, since floating will force elements to the next line anyways, that is up to you.
Gotchas
The first and major gotcha that people run into is they attempt to overly style their div tag that already has a grid class. This is a mistake and can lead to huge headaches. Let’s look at why you shouldn’t. I will show you what css rules are ok to use and which aren’t.
Border
The first no-no is border. You shouldn’t use border on your grid divs because it adds size to your layout.
ex. You have a grid div that spans 5 columns. 5 x 80px = 400px. So you want to add a border of 1px solid black (always bet on black). What does that do?
That changes the math 5 x 80px + 2px (border-left and border-right) = 402px. now 2px might not seem like a lot, but it can force whole divs to the next line, throwing off your layout completely.
To fix this problem you should put another div inside the grid div and then style that. What you end up with is a container –> content relationship.
Margin and Padding
So you want to move a grid just a little bit over huh? DON’T. The same problem happens that occurs with Border. You force the columns to stretch pass what they were designed to do. Think of yourself trying to wear pants that are two sizes too small, it just isn’t pretty.
The solution again is to use a container-> content relationship. Where you have another div inside that handles margin and padding.
Width
You might be seeing a theme here, width is the enemy of the grid system, especially explicit widths. If you have an element that is 200px in a column that is only 60px, then you’ll have problems.
The solution is to be mindful of your parent div. If you want to use width, look at using percentage. ex. width: 100% on the content div.
Things that are OK to Style:
background-color, color, background-image, position (absolute and relative).
Conclusion
The 960.gs is very powerful, but some CSS purist might not like it’s lack of semanticness (not sure if that’s a word). I see their point, but the up side is so great that I can overlook my HTML/CSS purism. Keep in mind the gotchas and you should be able to create consistent layouts in all major browsers.
Asp.Net MVC 2 Quick and Simple Site – v1
Mar 9th
*Note: Asp.Net MVC 2 project in Visual Studio 2010
I sat down last night and was thinking about how I could get a simple starter site up and running for a client, until I could design something more tailored to their needs. There is nothing worse than having a “under construction” page or a “coming soon” page. It doesn’t really say much about what is happening or what might be coming. So I sat down and came up with the basics of what a client might want right from the start, here were my requirements.
- Set a Logo, Name, and Subtitle
- Be able to quickly edit a small about section (Content)
- Quickly add some of the more important social networks (Twitter, YouTube, FeedBurner, Delicious, MySpace, and Facebook).
- Be able to add Google Analytics (Optional)
- A dynamic image gallery (drop images in a directory and everything is done for you).
- Basic contact information. Email, Phone, and Website.
- No external libraries to install (this hurts but is helpful).
So I sat down and started writing. I wanted someone to be able to push this site without editing a lot of files or having to setup a database. I opted to put a lot of the client’s settings in configuration. Yes configuration sections are not the new hotness but they can still serve a powerful purpose.
My first iteration had me using controller actions for each part of the site, but I slowly realized it was overkill. I opted to have one controller action from my index, and then break sections up into partial views that would be all rendered at the same time. Then those sections would be hidden and made visible using JQuery. After a little design, I ended up with this.
Let’s look at how to set this up.
Step 1 – Setup the Configuration
There are some pretty simple configuration sections in the web.config included with this project. You will see two App settings: WorkImagesDirectory and GoogleAnalyticsCode. The WorkImagesDirectory is used to find all the images in your gallery. Thumbnails for all your images will be automatically created if they are missing. The GoogleAnalyticsCode setting should be set to your Google Analytics code UA-XX-XXXX (or something like that). If you leave out the Google Analytics code then the script won’t be output to the page.
Next you will see a ContactInformation section. In this section you can set the name, site subtitle, email, phone, and website.
Finally, you will see a SocialNetworks section. Only the social network usernames you set will show up on the page. You can set Twitter, Facebook, YouTube, Delicious, MySpace, and FeedBurner(a blog maybe).
Step 2 – Setup Content
Once the configuration is done, then you probably want to change some of the content to reflect some good information.
All tabs are separated into partial views: About, Contact, Work, Social. Just replace the HTML content in here with what you want, leaving the nested RenderPartials.
Step 3 – Modify Colors and Images
All the images and style sheets you need to modify are under the Content directory. If you like the color and just want to modify the avatar at the top, just overwrite the avatar.png under Content/img.
Step 4 – Deploy It
Just publish what is there to your hosting provider and you are ready to go.
Conclusion
This is a good little site to get up and running for your clients, but it isn’t anything ground breaking. The code is straight forward, so even a novice can get in there and change things. The point here was not to over complicate the solution with third party libraries. It is to get a site up with in minutes, while still giving some great functionality to the people that need it.
Attack of the Bots! – Stop Them With ReCAPTCHA in ASP.NET MVC
Dec 21st
As developers sometimes we forget that there are bad people out there. Nefarious people waiting for you to mess up, just so they can exploit your weaknesses. One of the biggest problems with the internet
today is the use of bots. If you have ever run a publicly open site like a blog, forum, or contact form then you know what I mean. You get flooded with junk that you didn’t even know existed. This can be a huge problem, because it essentially makes the data coming in hard if not impossible to sort. So how do you stop these advanced monsters from reeking havoc on your public facing site?
We first have to understand how they exploit your site. You probably have some kind of form on your site. It is there for anyone and everyone to use, just like you intended. You spent hours meticulously crafting this form with valid HTML and readable labels. There is your first problem. Bots traverse your page looking for FORM tags. Then they proceed to look for INPUT tags which match their criteria. If you use a popular CMS or Blogging engine then you are already at a disadvantage. These systems are known by bots and there are no surprises on how your system works. Then the bots proceeds to submit the form. All this occurs in a matter of nanoseconds. Remember computers are fast, even when they are evil. Now the bots have a choice, leave your defenseless site in search of another or proceed to submit your form mercilessly until your site collapses and your inbox is filled with worthless junk.
The popular solution to combating bots has been CAPTCHA systems. CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart.” It usually involves a challenge-response test. The most popular kind is to show scrambled words in an image, which can be seen below. Some CAPTCHA systems can also get very strange. I have seen one that shows you screenshots of cute fuzzy animals and asks you to pick the kitten. This really is a interesting subject and I suggest you read the Wikipedia page on CAPTCHA.

Let’s get started in developing a solution. You might be thinking to yourself, “I don’t want to write a crazy CAPTCHA system.” Well you are in luck, there are several services on the internet that let you utilize their system. My favorite service is ReCAPTCHA. It offers both image based CAPTCHA tests along with audio tests for better accessibility. Let me show you what the final product will be like. I will be using the ASP.NET MVC sample project and modifying the registration page to add CAPTCHA checking. Dilled Fresno!?!? What the heck is that?

Step 1 – Getting Your ReCAPTCHA account.
Go to the ReCAPTCHA site and sign up for your keys. You will get a private key and and a public key. Copy these to notepad, you will need them.
Step 2 – Download the .Net Library for ReCAPTCHA
You will need to download the ReCAPTCHA .NET Library. Technically you don’t need this, you could write your own wrapper, but this makes it much easier. Go ahead and add this to your ASP.NET MVC project as a reference.
Step 3 – Implement the Client-Side
You want the ReCAPTCHA red box to show up on your site. So we are going to have to put some code in your view. ReCAPTCHA has already provided this code for for you. I have placed it below for faster access. Place this code within your Form tag, it is critical that you do so. Ok you are done. I also placed a ValidationMessage underneath the ReCAPTCHA code so that I could see my message.
<script type="text/javascript"
src="http://api.recaptcha.net/challenge?k=<YOUR PUBLIC KEY>">
</script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=<YOUR PUBLIC KEY>"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
<%= Html.ValidationMessage("ReCaptcha") %>
Step 4 – Implement the Server-Side
When the form is submitted, there will be two extra inputs submitted to your controller action. The “recaptcha_response_field” value and the “recaptcha_challenge_field” value. We will be using these to verify that the user is really human. So for the code that performs the CAPTCHA.
private bool PerformRecaptcha()
{
var validator = new RecaptchaValidator
{
PrivateKey = "<YOUR PRIVATE KEY>",
RemoteIP = Request.UserHostAddress,
Response = Request.Form["recaptcha_response_field"],
Challenge = Request.Form["recaptcha_challenge_field"]
};
try
{
var validationResult = validator.Validate();
if (validationResult.ErrorCode == "incorrect-captcha-sol")
ModelState.AddModelError("ReCaptcha", string.Format("Please retry the ReCaptcha portion again."));
return validationResult.IsValid;
}
catch (Exception e)
{
ModelState.AddModelError("ReCaptcha", "an error occured with ReCaptcha please consult documentation.");
return false;
}
}
RecaptchaValidator is from the assembly you referenced. Notice that we need to set the private key, and that we are getting the user’s I.P. address. We also set the fields that we got from the form. Now we just need to ask the service if everything is ok. The rest is trivial ASP.NET MVC code.
Conclusion
You can get ReCAPTCHA into your site in about 5 minutes, but it might take some time to perfect how you want it to integrate with you current scheme. For me, I don’t make a call to ReCAPTCHA if my model is not valid (see code below), this saves me an expensive and unnecessary internet call. I am also considering placing similar code in an ActionFilter, in the same fashion as ValidateAntiForgeryTokenAttribute. It should be pretty simple to do that.
if (ModelState.IsValid && PerformRecaptcha())
{
...
}
So now you have the power to stop those evil bots and take bake your site. Hope this helps.
ASP.NET MVC Clean HTML
Oct 28th
I love ASP.NET MVC and I feel it is the future of ASP.NET Web Development, but what I don’t like is trying to get your pages to look nice and I’m not talking about visually for the end user, that actually is very easy and enjoyable. If you are like me, then you probably spend hours looking at the source of web pages. I consider myself a source snob, always wanting to see properly indented tags and elements. Below you’ll see what I’m talking about, a nightmare of bad HTML output. ASP.NET MVC doesn’t modify your HTML, which is great for web developers but it can also frustrate the same people if they suffer from being source snobs. So how do we address this issue without spending hours indenting views and thinking of nesting scenarios. There are two approaches we could take.
<div id="main">
<h2>About</h2>
<div>
<div>
<div>
<div>
<div>
<p>
Put content here.
</p>
</div>
</div>
</div>
</div>
</div>
HttpModule
This was the standard way of doing it in a ASP.NET Web Form application. Before any html is spit out to the Response stream, you would modify it to meet your needs. This is partly the right approach for the MVC solution, but HttpModules are indiscriminate and will fire every time a request comes in. You can put logic in our httpmodule but what you will find is that it is very difficult to tell the difference between a ViewResult, JSonResult, or FileResult in an HttpModule.
ActionFilter
We get all the advantages of an HttpModule with the ability to discriminate, either by placing the filter only on actions that return a ViewResult or by accessing properties in the context passed to the filter. So this is the approach to go with, now let’s look at some code.
The Solution
For this solution I am using TidyNet, a great library that let’s you clean up HTML. There are a ton of features in this library but what I am concerned with is indenting, clean html, and making sure there are not stupidly placed tags (look at the above code, we don’t really need all those divs).
So let’s start by thinking about our ActionFilter. We need to access the response stream and modify the HTML right before output. We also need to take into consideration that ViewResults (output that is in html) is our only concern. Other results like JsonResult will be ignored since they aren’t HTML. We also want this to happen after the action is executed (although the approach I’ll take, it probably doesn’t matter). Beep Boop Beep, after some computing we have our action filter. Let’s look at the meat of the filter.
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
var tidy = new Tidy
{
Options =
{
DocType = DocType,
DropFontTags = DropFontTags,
LogicalEmphasis = LogicalEmphasis,
XmlOut = XmlOut,
Xhtml = Xhtml,
IndentContent = IndentContent,
HideEndTags = HideEndTags,
MakeClean = MakeClean,
TidyMark = TidyMark,
}
};
filterContext.RequestContext.HttpContext.Response.Filter =
new HtmlTidyFilter(filterContext.RequestContext.HttpContext.Response.Filter, tidy);
}
}
For this solution, we attach a filter to the response which will run at the time the response is written. Cool right? Let’s look at the meat of the filter itself, which is stream heavy but pretty straight forward. We get the HTML, clean the HTML, and then write the HTML.
public override void Write(byte[] buffer, int offset, int count)
{
var data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string html = Encoding.Default.GetString(buffer);
using (var input = new MemoryStream())
{
using (var output = new MemoryStream())
{
byte[] byteArray = Encoding.UTF8.GetBytes(html);
input.Write(byteArray, 0, byteArray.Length);
input.Position = 0;
_tidy.Parse(input, output, new TidyMessageCollection());
string result = Encoding.UTF8.GetString(output.ToArray());
byte[] outdata = Encoding.Default.GetBytes(result);
_stream.Write(outdata, 0, outdata.GetLength(0));
}
}
}
So now that we have this super sweet ActionFilter, let’s use it. I place the attribute like such.
[TidyHtml]
[HandleError]
public class HomeController : Controller
{ // Controller Actions
...
}
When all is run and the response is written to the page, we have the following output.
<div id="main">
<h2>
About
</h2>
<div>
<p>
Put content here.
</p>
</div>
<div id="footer">
</div>
</div>
Awesome!!! Clean HTML that makes me feel all warm and fuzzy inside and makes the web designers smile. If you are worried about this running everytime you hit an action then I suggest you use the OutputCacheActionFilter so that your pretty HTML is cached. Download the example and feel free to modify it. I exposed certain properties for TidyNet, but you can remove or add the ones you can see using in your projects. Have fun.
Aqua Bird Clean Html ActionFilter (318 kb)
Update : There is a bug in Tidy.Net that puts a break in your textarea tags. Your textareas will still work, but it will have an indent at the beginning. This can be very annoying.
Static Google Maps Html Helper
Oct 26th
Maps are always a nice thing to have on a site, especially if you are a business that relies on customers finding you; businesses like restaurants, car repair shop, or clothing store. Google has a great map API that has found it’s way into everything from mobile applications to your local news. It really is a great product. This particular helper will dynamically generate an image of your location to be placed on your site. The final result will look like the following. Again, this example uses the static API, so there is no dragging functionality or JavaScript involved.
Before you use this html helper, I suggest you read the documentation of the Google Maps API. This will give you an understanding of what properties are available and how you can customize your map.
Using the Helper
You will need to get an API key from Google or else you won’t be able to make requests. The minimum requirements for a request are a key, center, and sensor. Below you will see the code used to generate the image seen above. Don’t forget to replace “your_key” with your actual key.
Note: if you do local development, generate a Google API key using http://localhost so that you can streamline local development.
<%= Html.GoogleMap(new
{
key = "your_key",
zoom = 14,
size = "400x400",
center = "Capitol Complex East Wing, Harrisburg, PA",
sensor = "false",
markers = "color:blue|label:H|Capitol Complex East Wing, Harrisburg, PA"
}
)%>
Now here is the code to spit out the image tag necessary to display your new map.
public static class GoogleExtensions
{
public static string GoogleMap(this HtmlHelper htmlHelper, IDictionary<string,object> mapValues, IDictionary<string,object> attributes )
{
var builder = new TagBuilder("img");
var source = new StringBuilder();
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
const string template = "{0}={1}&";
source.Append("http://maps.google.com/maps/api/staticmap?");
// Create the Url
foreach (var key in mapValues.Keys)
source.AppendFormat(template, key, urlHelper.Encode(mapValues[key].ToString()));
// remove the last ampersand
var finalSource = source.ToString().Remove(source.Length - 1, 1);
builder.Attributes["src"] = finalSource;
builder.MergeAttributes(attributes);
return builder.ToString(TagRenderMode.SelfClosing);
}
public static string GoogleMap(this HtmlHelper htmlHelper, object values)
{
return GoogleMap(htmlHelper, values, null);
}
public static string GoogleMap(this HtmlHelper htmlHelper, object values, object attributes)
{
return GoogleMap(htmlHelper, values.TurnObjectIntoDictionary(), attributes.TurnObjectIntoDictionary());
}
public static IDictionary<string, object> TurnObjectIntoDictionary(this object data) {
var attr = BindingFlags.Public | BindingFlags.Instance;
var dict = new Dictionary<string, object>();
if (data == null)
return dict;
foreach (var property in data.GetType().GetProperties(attr).Where(property => property.CanRead))
dict.Add(property.Name, property.GetValue(data, null));
return dict;
}
}
There you have it. Now when you want to display a quick map on your site, this helper will make it a breeze.
That Pesky Active Page for ASP.NET MVC
Oct 22nd
When working with HTML and CSS there are some visual queues that you can add to enhance the user experience. One of these tricks is to highlight the menu button in your navigation. Most web applications do it, but how do you accomplish this in your current ASP.NET MVC application? First let’s look at what we are trying to do. Below you will see the header to the Aqua Bird Consulting site. You’ll notice that one of the buttons is different than the others; the button that relates to the page we are on is different.
If we look at the source of the page we’ll see that the home button has an id of “active”. Obviously you could accomplish the same thing by putting a class on the HTML element, but that’s another discussion. So how do you get the correct button to be active as we move around the site? There are two ways, I’ll first talk about the BAD way to do it.
<ul>
<li id="active">
<a href="/"><span>Home</span></a>
</li>
<li>
<a href="/About"><span>Company</span></a>
</li>
<li>
<a href="/Services"><span>Services</span></a>
</li>
<li>
<a href="/Portfolio"><span>Portfolio</span></a>
</li>
<li>
<a href="/Products"><span>Products</span></a>
</li>
<li>
<a href="/Contact"><span>Contact</span></a>
</li>
</ul>
The Bad
You could always place a value into ViewData, TempData, or even on your view model. This is bad because, now we are pulling visual elements down into our controller. This is a big no-no, and we would be violating the will of the MVC gods. Having the “Home” button highlighted doesn’t change the state of our underlying application (by underlying, I mean business logic). So don’t do this; it will definitely work but you’ll be in a world of pain if you decide to redesign your site or refactor.
The Good
The great thing about ASP.NET MVC and .NET 3.5 is the extensibility of it all. Everything is right there for you to access. So knowing that little fact about the extensibility of the ASP.NET MVC framework, you have to figure there is a way to know what Controller, Action, or even View we are on. For the scenario pertaining to the Aqua Bird Consulting site, we needed to link buttons to Controllers and Actions. Know let’s look at how we get the Controller and Action.
// helper is and HtmlHelper var currentController = helper.ViewContext.RouteData.Values["controller"].ToString(); var currentAction = helper.ViewContext.RouteData.Values["action"].ToString();
Cool! Nothing to it. Now all we need to do is check it on the view. I created an extension method, where you pass in a controller name, or a controller name and action pair. In addition to those parameters you pass in your designated output. I also have one where you can pass the controller name only, possibly for multipurpose controllers or sections.
public static string IsActive(this HtmlHelper helper, string controllerName, string output)
{
var currentController = helper.ViewContext.RouteData.Values["controller"].ToString();
return (currentController == controllerName) ? output : string.Empty;
}
public static string IsActive(this HtmlHelper helper, string action, string controllerName, string output)
{
var currentController = helper.ViewContext.RouteData.Values["controller"].ToString();
var currentAction = helper.ViewContext.RouteData.Values["action"].ToString();
return (currentController == controllerName && action == currentAction) ? output : string.Empty;
}
And here is what the view code looks like. Notice that I declare my output as a constant string in the view. I chose to do this in case I chose to change my html. I also didn’t want html to sneak into my helpers and thought this was a good alternative to that.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="AquaBird.MainSite.Infrastructure.Extensions"%>
<%const string output = " id=\"active\""; %>
<ul>
<li<%=Html.IsActive("Index", "Home", output)%>>
<a href="<%=Url.Action("Index", "Home") %>"><span><Home</span></a>
</li>
<li<%=Html.IsActive("About", "Home", output) %>>
<a href="<%=Url.Action("About", "Home") %>"><span>Company</span></a>
</li>
<li<%=Html.IsActive("Services", output) %>>
<a href="<%=Url.Action("Index","Services") %>"><span>Services</span></a>
</li>
<li<%=Html.IsActive("Portfolio", output) %>>
<a href="<%=Url.Action("Index", "Portfolio") %>"><span>Portfolio</a>
</li>
<li<%=Html.IsActive("Products", output) %>>
<a href="<%=Url.Action("Index", "Products") %>"><span>Products</a>
</li>
<li<%=Html.IsActive("Contact", output) %>>
<a href="<%=Url.Action("Index", "Contact") %>"><span>Contact</a>
</li>
</ul>
There you have it. Now you can know whether you are on a certain controller and action from your view without breaking the rules of MVC.
P.S. Having multiple elements on the same page with the same id will make your page invalid when run through a HTML validator, keep that in mind.


