Sep 3
2010

Using Extension Methods in .NET

Written by Robert Greiner | posted in Programming | View Comments

Extension methods are a handy way of adding your own custom methods to a class when you normally wouldn’t be able to. .NET treats extension methods exactly like instance methods. In fact, in your day-to-day .NET programming you may be calling extension methods and not even know it.

Let’s say we have access to an API with a simple Person class. Also, for the purposes of this post, let’s say we don’t have access to extend or modify this class.

public class Person {

  public Person(string first, string middle, string last) {
    FirstName = first;
    MiddleName = middle;
    LastName = last;
  }

  public string FirstName { get; set; }
  public string MiddleName { get; set; }
  public string LastName { get; set; }
}

In order to get the full name of a Person we’d have to do something like this:

Person p = new Person("Robert", "N", "Greiner");
string fullName = String.Format("{0} {1}", p.FirstName, p.LastName);

This is perfectly fine, but what if you have to do this in several places? You’d either have to copy/paste this code wherever you needed it (bad idea, what if your boss came in later and said that she really wanted to use middle name also? Then, you’d have to go manually change every line of code that gets the full name) or you could create a stand alone method to return the full name (a better option, but the new method would be separate from the class). Wouldn’t it have been nice if the original authors of the class included a method to return a Person’s full name? This is where extension methods come in handy. We can add a FullName() method and have it treated as if it was part of the class the whole time.

public static class ExtensionMethods {
  public static string FullName(this Person p) {
    return String.Format("{0} {1}", p.FirstName, p.LastName);
  }
}

This is the syntax for creating an extension method. There are a few things to note here:

  1. Extension methods must reside in a public static class.
  2. Extension methods must be static
  3. Extension methods must use the this keyword in the parameter list of the function. This is how .NET knows what object to attach your extension method to (in this case, the Person class.)

Now that we have our extension method, we can call FullName() just like any other method belonging to the Person class.

Person p = new Person("Robert", "N", "Greiner");
string fullName = p.FullName();

Did you notice how the FullName() was declared statically, but is eventually treated as if it is an instance method? In fact, .NET treats all C# and VB extension methods in the exact same way as instance methods.

But, what about encapsulation? What if I don’t want parts of my class to be exposed publicly under any circumstances? Don’t worry, extension methods don’t have access to any private or protected methods in a class.

This is a bit of a contrived example, in the real world, you would likely just modify or extend Person to add the FullName() method. You can just as easily add an extension method to a class you don’t have access to:

public static class ExtensionMethods {
  public static string RemoveSpaces(this string s) {
    return s.Replace(" ", "");
  }
}
...
string text = "This is a text string.";
text = text.RemoveSpaces();

Extension methods are a great way to add a level of simplicity and tidiness to your application. However, extension methods should be used in moderation. They are not always the right answer in every situation and should only be used when they make sense. Typically, if you can modify or extend the existing client code, you should.

Aug 27
2010

Grouping Radio Buttons in ASP .NET MVC 2

Written by Robert Greiner | posted in Programming, Web Design | View Comments

Here’s a simple issue I ran into today when dealing with radio buttons in an ASP .NET MVC 2 application.

Radio buttons should only allow the user to select a single option out of multiple choices. This should be enforced by only allowing one radio button to be selected for each option set. But, what if your application has multiple options that all need radio buttons? How do you distinguish the radio buttons from one option from the other.

This is where groups comes in. By setting the GroupName property for each of your radio buttons, you can specify which buttons to associate to an option.

<div>
  <asp:RadioButton ID="ActionMatch" GroupName="RegexActions" Checked="true" Text="Match" runat="server" />
  <asp:RadioButton ID="ActionReplace" GroupName="RegexActions" Text="Replace" runat="server" />
</div>

Also, note that in ASP .NET MVC 2 there is no default group, so you must define a GroupName in order for the radio buttons to work properly.

Aug 23
2010

How to Properly Style HTML Tables

Written by Robert Greiner | posted in Web Design | View Comments

Some folks would argue that you should never use tables. And, for the most part, I agree.

I believe that HTML markup should be meaningful, and therefore, you shouldn’t use tags for something they weren’t intended for (such as laying out a web page.) However, tables were put into the HTML standard for a reason, displaying tabular data.

For instance, if we have a database of employees and we want to print a report that contains our top performers, their salary, and contact information a table would be the perfect candidate.

Here’s a fictitious example of what a web page might return from a database of employees.

<table id="employees">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Salary</th>
    <th>Extension</th>
  </tr>
  <tr>
    <td>Albert</td>
    <td>Einstien</td>
    <td>$500,000</td>
    <td>3141</td>
  </tr>
  <tr>
    <td>Alan</td>
    <td>Turing</td>
    <td>$300,000</td>
    <td>1243</td>
  </tr>
  <tr>
    <td>Nikola</td>
    <td>Tesla</td>
    <td>$300,500</td>
    <td>0987</td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>Gates</td>
    <td>$100,000,000</td>
    <td>2222</td>
  </tr>
</table>

This, in my humble opionion is perfectly acceptable. We have tabular data that belongs in an HTML table. But, what do we do from here? The table returned is drab and needs some styling to look as sharp as the rest of the site. Let’s add some style.

#employees {
  width:100%;
  border-collapse:collapse;
}
#employees td, #runners th {
  border:1px solid #28647f;
  padding:3px 7px 2px 7px;
}
#employees th {
  font-size:1.2em;
  text-align:left;
  padding-top:5px;
  padding-bottom:4px;
  background-color:#26394c;
  color:#FFFFFF;
}
#employees tr.alt td {
  color:#000;
  background-color:#d3e5f2;
}

Better! This turned our drab table from the 90′s into something that looks clean and professional.

Remember, you should only use tables for displaying tabular data. If you want a good way to lay out the graphics on your web page, then check out this tutorial to help get you started.

You can view the entire web page here.

Aug 17
2010

A Simple College Prank

Written by Robert Greiner | posted in Random | View Comments

Today is the day my brother-in-law leaves for college and I’m feeling a little nostalgic, so in honor of him leaving I thought I’d write a quick post about my favorite prank in college.

One of the first things that most college kids do right after moving in to the dorms is run to Wal-Mart one last time with their parents to make sure you can get as much last-minute stuff as possible without having to pay for it. Because, once the parents are gone, you can pretty much mark that down on your calendar as the day they start drastically decreasing the amount of free cash they float your way.

Now, as you scour the isles searching for anything and everything you might conceivably need throughout the next few months, chances are you will figure out sooner or later that you don’t have an answering machine. I mean… you do need an answering machine, don’t you?

Typically, there will be several options on answering machines and you better believe that everyone is going to buy the cheapest one on the shelf. Why? Because it’s an answering machine, you don’t need top-of-the-line here; you just need something to get you by.

Here’s the beauty of the situation, this means that a great majority of new students will have the same answering machine as you, and yes, they all have a remote administration feature.

All you have to do is dial up some of your buddies when they are in class (or, you know, wherever college kids hang out these days) and wait until their answering machine picks up. Simply type in the default administrator code (usually “1111”) and you’re in! Now you can change their greeting into something a little more embarrassing.

Most of the time, your victims won’t even realize their greeting message has been changed for several weeks.

This is especially sweet when you do this to your next door neighbors because you can hear your custom greeting from your dorm room every time they miss a call.

So there you have it, a low-risk and somewhat lame prank that can potentially give you and your buddies a few laughs during the first couple weeks of college.

And, if you’re leaving this week for the dorms for the first time; good luck!

Oh! And don’t forget to head on over to Amazon and grab your free one-year subscription to Amazon Prime.

Aug 3
2010

Are You a Student? Great, Here’s a Free One-Year Amazon Prime Subscription

Written by Robert Greiner | posted in Random | View Comments

If you’re a student with a valid email address, head on over to Amazon and get a free one year subscription to Amazon Prime.

  • Amazon Prime free for one year ($79 value)
  • Unlimited FREE Two-Day Shipping on textbooks and millions of other items
  • No minimum order size
  • Upgrades to One-Day shipping for $3.99/item
  • E-mail alerts for exclusive deals and promotions
  • It’s free for students – sign up by providing your school and major

Now there’s no excuse for you to not have your books in time for class, eh?

.NET Algorithmic Art ASP ASP .NET ASP .NET MVC audio Bill Gates C# code review Computational Art CouchDB CSS Database DateTime debug DevDays eclipse ethics FileSystem Git Improvement iPhone Java JQuery Knopflerfish Layouts mail Microsoft Oracle OSGi Processing Python Ruby SMTP SOA Software Piracy Source Control SQL StackOverflow tools TortoiseGit training Web Standards Windows XHTML