Friday, January 2, 2009

DIV based CSS vs. Tables - CSS Tricks and Performance Review

After initially failing to find an easy, efficient, and cross-browser compatible way of writing CSS for complex forms, I came across a layout foundation called YUI Grids CSS at the Yahoo! Development Network. I would highly recommend using the YUI framework for page layout, since it covers many scenarios including cross-browser compliance. However, if you are going to be doing a complex form layout with dozens of layout cells, the performance is slower than with using a traditional table. In my informal tests, I found load times to be 20~30% slower when using YUI than a simple table. You can see an example of the form I used in my previous blog post labeled Using CSS - Complex Forms Without Tables? Anyone? Anyone?. Ultimately, I will be using these concepts to create a form generation tool that will create forms on the fly with all the general event handling.

Fortunately, I was able to adopt some of the ideas within the YUI CSS framework and simplify it for form layout developments and make the DIV and CSS based layout perform 25% better. I created examples of forms that include up to 10 columns. The container DIV will always have the class divContainer and the items inside will always have a class called divItem[ColumnNumber]. The following example will have content divided into 3 equal parts.

<div class="divContainer">
    <div class="divItem3">Column 1 Content</div>
    <div class="divItem3">Column 2 Content</div>
    <div class="divItem3">Column 3 Content</div>
</div>

You can also mix and match assuming the item fractions add up properly. (For example: 1/3 + 1/3 + 1/6 + 1/6 = 1)

<div class="divContainer">
    <div class="divItem3">Column 1 Content</div>
    <div class="divItem3">Column 2 Content</div>
    <div class="divItem6">Column 3 Content</div>
    <div class="divItem6">Column 4 Content</div>
</div>

You can also add your own custom css based on existing ones. In this example, I wanted to tweak the 4 column layout so that the first two columns were a bit different. Since the original two column widths would have added up to 48%, I just had to make sure they were calculated appropriately.

        .divItem4
        {
            float: left;
            width: 24%;
            margin-left: 1%;
        }      
       .divItem4Custom1
        {
            float: left;
            width: 9%;
            margin-left: 1%;
        }
        .divItem4Custom2
        {
            float: left;
            width: 35%;
            margin-left: 1%;
        }

<div class="divContainer">
    <div class="divItem4Custom1">Column 1 Custom Content</div>
    <div class="divItem4Custom2">Column 2 Custom Content</div>
    <div class="divItem4">Column 3 Content</div>
    <div class="divItem4">Column 4 Content</div>
</div>

I have included the code for the table based and CSS based and correlating performance results below. As I mentioned earlier, the columns are based on equal sizes, so you can tweak these to make them variable. Also note that if you change the margins are padding, the width will need to be tweaked. I have set the left margin to 1px by default.

As far as centering is concerned, IE doesn't recognize auto margins, so you have to make sure that the body has the text-align set to center and container DIV's to have text-align set to left. All container DIV's also need to include the pseudo element "after" which allows you to include content after the closing tag.

Performance Results

The following tests were performed using Google Chrome's Javascript Console (Ctrl+Shift+J) which allows you to see the load time in milliseconds. I loaded each page 10 times, removed the highest outlier, and then got the average. As you can see below, the CSS Load Time was 25.5814% faster. You can see the full code I used below.

DIV CSS Load Time (ms) Table Load Time (ms)
32 43
37 80 (Outlier)
43 43
76 (Outlier) 55
32 41
31 55
40 36
32 42
48 36
32 40
Average: 36.33333 Average: 43.44444

Code

Compatible Browsers:  Microsoft IE: 7.0.5730.13CO / Google Chrome: 1.0.154.36 / Firefox 3.0.1

DIV Based CSS HTML:

<html>
  <head>
    <style type="text/css">
        body
        {
            text-align: center;
        }
        .divContainer
        {
            border-left-style: solid;
            border-left-width: 1px;
            border-left-color: black;
            border-right-style: solid;
            border-right-width: 1px;
            border-right-color: black;
            border-top-style: solid;
            border-top-width: 0px;
            border-top-color: black;
            border-bottom-style: solid;
            border-bottom-width: 1px;
            border-bottom-color: black;
            width: 950px;
            margin-left: auto;
            margin-right: auto;
            text-align: left;
        }
        .divContainerFirst
        {
            border-left-style: solid;
            border-left-width: 1px;
            border-left-color: black;
            border-right-style: solid;
            border-right-width: 1px;
            border-right-color: black;
            border-top-style: solid;
            border-top-width: 1px;
            border-top-color: black;
            border-bottom-style: solid;
            border-bottom-width: 1px;
            border-bottom-color: black;
            width: 950px;
            margin-left: auto;
            margin-right: auto;
            text-align: left;
        }
        .divContainer:after
        {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        .divContainerFirst:after
        {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

.divItem1
{
    float: left;
    width: 99%;  /*Total: 99%*/
    margin-left: 1%;
}
.divItem2
{
    float: left;
    width: 48%;  /*Total: 96%*/
    margin-left: 1%;
}
.divItem3
{
    float: left;
    width: 32%; /*Total: 96%*/
    margin-left: 1%;
}
.divItem4
{
    float: left;
    width: 24%;  /*Total: 96%*/
    margin-left: 1%;
}
.divItem5
{
    float: left;
    width: 19%;  /*Total: 95%*/
    margin-left: 1%;
}
.divItem6
{
    float: left;
    width: 15.5%;  /*Total: 93%*/
    margin-left: 1%;
}
.divItem7
{
    float: left;
    width: 13.25%;  /*Total: 92.75%*/
    margin-left: 1%;
}
.divItem8
{
    float: left;
    width: 11.4%;  /*Total: 91.2%*/
    margin-left: 1%;
}
.divItem9
{
    float: left;
    width: 10.0%;  /*Total: 90%*/
    margin-left: 1%;
}
.divItem10
{
    float: left;
    width: 8.9%;  /*Total: 89%*/
    margin-left: 1%;
}

  </style>
  </head>
  <body>    <div class="divContainerFirst">
        <div class="divItem1">
            1 Column: Imagination is more important than knowledge. Albert Einstein</div>
    </div>
    <div class="divContainer">
        <div class="divItem2">
            2 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem2">
            2 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem3">
            3 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem3">
            3 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem3">
            3 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem4">
            4 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem4">
            4 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem4">
            4 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem4">
            4 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem5">
            5 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem5">
            5 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem5">
            5 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem5">
            5 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem5">
            5 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem6">
            6 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem7">
            7 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem8">
            8 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem9">
            9 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
    </div>
    <div class="divContainer">
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
        <div class="divItem10">
            10 Columns: Imagination is more important than knowledge. Albert Einstein
        </div>
</body>
</html>

Table Based HTML:

<html>
  <head>
    <style type="text/css">
        body
        {
            text-align: center;
        }
        .divContainer
        {
            border-left-style: solid;
            border-left-width: 1px;
            border-left-color: black;
            border-right-style: solid;
            border-right-width: 1px;
            border-right-color: black;
            border-top-style: solid;
            border-top-width: 0px;
            border-top-color: black;
            border-bottom-style: solid;
            border-bottom-width: 1px;
            border-bottom-color: black;
            width: 950px;
            margin-left: auto;
            margin-right: auto;
            text-align: left;
        }
        .divContainerFirst
        {
            border-left-style: solid;
            border-left-width: 1px;
            border-left-color: black;
            border-right-style: solid;
            border-right-width: 1px;
            border-right-color: black;
            border-top-style: solid;
            border-top-width: 1px;
            border-top-color: black;
            border-bottom-style: solid;
            border-bottom-width: 1px;
            border-bottom-color: black;
            width: 950px;
            margin-left: auto;
            margin-right: auto;
            text-align: left;
        }
        .divContainer:after
        {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        .divContainerFirst:after
        {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
    </style>
  </head><body>
    <table class="divContainerFirst">
        <tr>
            <td>
                1 Column: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                2 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                2 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                3 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                3 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                3 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                4 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                4 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                4 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                4 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                5 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                5 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                5 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                5 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                5 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                6 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                7 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                8 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                9 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
    <table class="divContainer">
        <tr>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
            <td>
                10 Columns: Imagination is more important than intelligence. Albert Einstein.
            </td>
        </tr>
    </table>
</body></html>

Tuesday, December 9, 2008

Using CSS - Complex Forms Without Tables? Anyone? Anyone?

I have spent the last couple weeks doing research on CSS form development for very complex forms that involve things like multiple sections and multiple columns. I often hear that "tables are evil" or that "tables should only use them for tabular data", and I was determined to find a way to incorporate CSS for my next form.

I decided to do some in depth research to determine if there was a standard or best practice for complex form development. Fortunately for me, there are thousands of examples on the web and others that can be found in various books. I decided to purchase The CSS Anthology - 101 Essential Tips, Tricks & Hacks by Rachel Andrews which has a number of great examples. I also downloaded a free book by the same publisher titled The Art & Science of CSS I also went to Borders bookstore and spent some more time perusing through about eight different CSS books. Another book by Rachel Andrew even had the promising title HTML Utopia: Designing Without Tables.

Unfortunately, I could not find a single example that would meet my requirements. Pretty much every example I encountered had a very simple form, usually a very standard one with name, address, and zip code. I could not find a single form that was more complex that involved things like multiple sections and multiple columns.

Ultimately, I have come to the conclusion that while there may be a solution for a complex form using CSS, it hasn't been documented or standardized. Until then, I plan to continue using tables to develop complex forms. If anyone out there in the blogosphere has any suggestions I am posting a screenshot of the form.

Example:


Friday, December 5, 2008

Quick and Dirty Object Sorting by Implementing IComparer<T>

Let's say you have a simple Person class with some properties of First Name and Last Name. You then populate them into a strongly typed List<T> and would like to sort them by Last Name. Fortunately there is a very easy solution.

1. Create a Person class:

public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public Person
}

2. Create a PersonComparer class that implements IComparer<Person>:

public class PersonComparer : IComparer<Person>
{
    public int Compare(Person p1, Person p2)
    {
        return String.Compare(p1.LastName, p2.LastName);
    }
}

3. It was that easy. Now write some test code:

static void Main(string[] args)
{
    List<Person> personList = new List<Person>();
        personList.Add(new Person { FirstName = "George", LastName = "Washington"});
        personList.Add(new Person { FirstName = "Abraham", LastName = "Lincoln" });
        personList.Add(new Person { FirstName = "John", LastName = "Adams" });
        personList.Sort(new PersonComparer()); //Or use alternative below
        foreach (Person p in personList)
        {
            Console.WriteLine("{0}, {1}", p.LastName, p.FirstName);
        }
        Console.Read();
}

Alternative: If you need a one off, create a delegate that will sort the object on the fly. You will not need to implement the PersonComparer class, however it is not as reusable.

personList.Sort(delegate(Person p1, Person p2)
{
    return p1.LastName.CompareTo(p2.LastName);
}});

Thursday, November 13, 2008

Build StringBuilder Code from C#

With a little quick and dirty code, you can generate StringBuilder code from C# code. To use it, all you need is a WinForms project with two TextBoxes and a Button. This is very useful for creating code generation tools. My reason is that I am in the process of creating a dynamic form generation tool for SharePoint Lists and Document Libraries.

Form Example Screenshot:

C# Code (Not Optimized):

public string GetStringBuilderCodeFromCSharp(string[] lines)
{
    StringBuilder stringBuilder = new StringBuilder();
    string line = string.Empty;
    foreach (string s in lines)
    {
        line = s.Replace("    ", "\\t").TrimEnd();    //Replace four spaces with tabs. VS cs uses spaces
        if (line.StartsWith("\\t\\t"))                      //Eliminate double tabs. VS cs defaults with tab
            line = line.Substring(4, line.Length - 4);
        line = line.Replace("\"", "\\\"");               //Replace double quotes with escaped double quotes
        line = "stringBuilder.Append(\"" + line + "\\r\\n\");\r\n";   //StringBuilder Append Code
        stringBuilder.Append(line);
    }
    stringBuilder.Insert(0, "StringBuilder stringBuilder = new StringBuilder();\r\n");
    return stringBuilder.ToString();
}

Monday, July 28, 2008

Apparently not so Cuil after all...

One of the top stories on Google News this morning was a new search engine called Cuil (pronounced "cool") that is supposed to have a larger search index than Google. Although the search results come out in a pretty Web 2.0 looking layout, I will probably still opt for scrolling down a list of search results. I also found a few other things that raised a few eyebrows.

Broken Contact Us Link - One thing that kind of surprised me was the fact that the Contact Us page resulted in an "Oop! We couldn't find that page." error. I recently saw the same thing on a web page of a company I was being interviewed. Of all the page links that could be broken, you'd think that this one would be pretty important.

No Address Recognition - I also tried typing in my current address, but the search engine simply hung for a few minutes after finally displaying a message that it couldn't find any results.

No Detailed Preferences - The preferences are simply Safe Search (on / off) or Typing Suggestions (on /off). I'd like to see more choices than this.

cuil

cuil2

You can also visit my post labeled "A Few Reason's I will keep using Google Search over Windows Live Search."

Wednesday, July 16, 2008

.NET 3.5 - Extension Methods Magic!

One of my favorite new features about .NET 3.5 is the ability to create Extension Methods. Essentially this provides you with the ability to extend a given type with your own custom methods. Let's think about what you would need to do to retrieve a control value from a ASP.NET FormView. First you need to use the Controls collection or FindControl method to return the control. Then, you need to cast the control to the specific control in question. Finally, you have to cast it to the type you need returned. The following is an example of this:

int woodchucksTotal = Convert.ToInt32(((Label)WoodChuckerForm.FindControl("WoodchucksTotal")).Text);

This syntax is very error prone, tedious, and hard to debug if you are doing it with a large number of controls. Alternatively, and with very little work, you can use extension methods and have syntax like this instead:

int? woodchucksTotal = WoodChuckerForm.ControlToInt32("WoodchucksTotal");

This allows me to simplify my syntax and almost cut it in half and decrease the number of parentheses from 8 to 2. I have also provided means to return a nullable typed integer. This can be helpful if, for example, you'd prefer to insert a null instead of a zero in a database. To be able to implement extension methods, you simply need to use the following two simple steps:

Implement an Extension Method

  1. Create a non-nested static class.
  2. Add static methods that have first parameters use the this modifier with the type being extended.

Sample C# Code

public static class WebControlUtil
{
    public static string ControlToString(this FormView formView, string controlName)
    {
        WebControl ctrl = (WebControl)formView.FindControl(controlName);
        switch (ctrl.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                ctrlText = ((TextBox)ctrl).Text;
                break;
            case "System.Web.UI.WebControls.CheckBox":
                ctrlText = ((CheckBox)ctrl).Checked.ToString();
                break;
            case "System.Web.UI.WebControls.DropDownList":
                ctrlText = ((DropDownList)ctrl).Text;
                break;
        }
        return ctrlText;
    }

    public static bool ControlToBool(this FormView formView, string controlName)
    {
        WebControl ctrl = (WebControl)formView.FindControl(controlName);
        bool ctrlBool = false;
        switch (ctrl.GetType().ToString())
        {
            case "System.Web.UI.WebControls.CheckBox":
                ctrlBool = ((CheckBox)ctrl).Checked;
                break;
        }
        return ctrlBool;
    }

    public static int? ControlToInt32(this FormView formView, string controlName)
    {
        WebControl ctrl = (WebControl)formView.FindControl(controlName);
        int? ctrlInt32 = null;
        switch (ctrl.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                if (((TextBox)ctrl).Text != "")
                {
                    ctrlInt32 = Convert.ToInt32(((TextBox)ctrl).Text);
                }
                break;
            case "System.Web.UI.WebControls.DropDownList":
                ctrlInt32 = Convert.ToInt32(((DropDownList)ctrl).SelectedValue);
                break;
        }
        return ctrlInt32;
    }

    public static DateTime? ControlToDate(this FormView formView, string controlName)
    {
        WebControl ctrl = (WebControl)formView.FindControl(controlName);
        DateTime? ctrlDate = null;
        switch (ctrl.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                if (((TextBox)ctrl).Text != "")
                {
                    ctrlDate = Convert.ToDateTime(((TextBox)ctrl).Text);
                }
                break;
        }
        return ctrlDate;
    }
}

Five Things You Didn't Know About Me

This blog has been strictly technical, but I was feeling gutsy and decided to include a few personal items here just for kicks. With that being said, here are five things about me that you didn't know about me:



funeral_home

In order to pay for college, I lived and worked at a funeral home in downtown Seattle for three years.

We were located right on Pine Street and could see Pike's Place Market from the building. To get to our apartment, you had to climb the back stairs and walk through a rather large coffin display room. Legend has it (as I later confirmed), that services for both Bruce and Brandon Lee were held at this same funeral home. We have many experiences, including tear gas in our apartment during the demonstrations at the WTO Ministerial Round in 1999. Incidentally, I was interning for the Japanese Consulate at the time, specifically for the WTO! Sadly to say, the funeral home got sold to a law firm a few years ago, but leases out the chapel to a bar actually called Chapel. It's on the corner of Melrose and Pine and a great place for a martini and feeling morbid, or in my case nostalgic!


greyhound

I have traveled all the way across the U.S. via train, plane, automobile, and Greyhound bus.

I was seventeen during my four day trip from Groton, CT to San Diego, CA on the Greyhound bus, which was about the distance of 3,000 miles. I somehow subsisted on peanut butter, jam, twenty bucks, and the ticket price of a whopping $69.
Tip: If at all possible, try to avoid the St. Louis bus depot at three in the morning. It can be a very scary place. Also, I highly recommend the train if you want to enjoy seeing the back roads of America. That way you won't have to stop every ten minutes for driver smoke breaks and wonder if every seat has been urinated on. In addition, if you can afford it, I highly recommend a sleeper car as sleeping in the chairs get a little uncomfortable after a few days.

猿も木から落ちる

I can speak and read Japanese and was once a medical interpreter.

I was mostly self taught and actually tested into fourth year Japanese at the University of Washington without ever having taken a class. I ended up excelling and took most of the fourth year classes and some graduate level classes. Due to credit limitations, I ultimately ended up with a Japanese minor along with my major in International Studies, with a focus on East Asia. I have a continued interest in Japan, but it has definitely become more of a hobby. And by the way, I don't do karate or origami, and only watch manga occasionally.
Note: The translation from the Japanese text on the left is from a famous kotowaza or Japanese folk saying: "Even monkeys fall from trees."

bloodplasma

I donated plasma for money during college to make ends meet.

Since I was paying for college on my own, times could be tough and tough times called for desperate measures. However, I drew the line with organ donations and pharmaceutical testing.
Tip (not actually recommended): When it comes to plasma banks, you are required to wait a few days before coming back. I guess there's some silly rule about the fact that they are sucking all this blood out of you and don't want you to die. :) Anyways, competing plasma banks don't always check each others records. This means that if you are swift on your feet, you can hit up a couple a week and buy all the sweet ramen and cabbage you can eat!
oppenheimer

I have a love for reading, especially history and contemporary history.

The last book I read was American Prometheus: The Triumph and Tragedy of J. Robert Oppenheimer, by Kai Bird and Martin Sherwin. I also recently finished Guns, Germs, and Steel, by Jared Diamond and Mao: The Unknown Story, by Jung Chang and Jon Halliday. I highly recommend the first two, but you really need to be prepared and have a strong stomach for the third.
I am currently re-reading the classic Catch-22 by Joseph Heller (along with my normal array of geek books). Some of my favorite author's are Don Delillo, Hermann Hesse, Philip Roth, Ralph Ellison, and David Sedaris (can't wait until his new one comes out in paperback).

Note: I have to give some credit to Scott Hanselman's ComputerZen blog post for encouraging to throw some personal touches to my otherwise mundane technical blog.