Introduction To Extension Methods in C#

Extension methods allow you to extend the functionality of an existing class without using inheritance.

For example, suppose you were implementing a system which allowed users to post comments on a web site but you wanted to disallow swear words or other offensive content.

You could write a SwearChecker class (static or otherwise) or you could enable the same functionality by adding an extension method to the String class.

An extension method is defined a static method within a static class. The keyword this is used before the first method parameter and signifies the type that is being extended.

The following defines an extension method for String.


public static class OffensiveStringExtensions
{

    public static bool IsOffensive(this string stringToCheck)
    {
        // define list of offensive words (real swear words omitted...)
        List<string> offensiveWords = new List<string> {"darn", "damn", "blast"};

        foreach (var offesiveWord in offensiveWords)
        {
            // A real implementation may need to handle uppercase, localisation, etc.
            if (stringToCheck.Contains(offesiveWord))
                return true;
        }

        // no offensive words found
        return false;
    }

}


The extension method is called just as if it were a member of the type itself:

string wordsToCheck = "This is darn offensive!";
if (wordsToCheck.IsOffensive())

    //.... perform some logic ....


MSDN states: "In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type."

We cannot inherit from String because it is sealed, so an extension method is one way of adding this functionality to all strings.

Some things to note when using extension methods:

  • If an extension method has the same signature as an instance method, the instance method will be used and the extension method will never be called;
  • The extension method can't access private members of the type it is extending;

A Simple Menu Roll-over using jQuery and CSS

The following ASP.NET page shows a simple example of a menu created using a combination of CSS and jQuery.

The menu is defined as an unordered list (which makes semantic sense) and styled with CSS (a real web site would of course have its CSS defined in external file(s)). When the user moves the mouse over a menu item, a CSS class is dynamically added; then removed when the mouse leaves. In addition a simple "infobox" span is defined whose text is changed to that of the title attribute of the <a> element.

There are lots of examples of image based roll-overs, this one is really cool and based on a simple idea.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <title>Simple jQuery Menu Example</title>

    <script type="text/javascript">

        var menuPrompt = "Please select a page to view."; // simple prompt for user
       
        $(document).ready(function() {

            // initialise the infobox prompt
            $("#infobox").text(menuPrompt);
       
            $(".nav_menu_list li a")
            .mouseover(function() {
                // add the mouseover style
                $(this).addClass("nav_menu_item_mouseover");
                // set the text of the infobox span to the anchor title attribute
                $("#infobox").text("Go to " + $(this).attr("title"));
            })
            .mouseout(function() {
                //remove the mouseover style
            $(this).removeClass("nav_menu_item_mouseover");
                // reset the text of the infobox span to user prompt
                $("#infobox").text(menuPrompt);
            })
        })
   
    </script>

    <style type="text/css">
        .nav_menu_list
        {
            list-style-type: none;
            margin: 0 0 0 21px;
            padding: 0;
        }
        .nav_menu_list li
        {
            float: left;
            text-align: left;
        }
        .nav_menu_list li a
        {
            display: block;
            padding: 0 10px 0 5px;
            text-decoration: none;
            font-size: 36pt;
        }
        .nav_menu_item_notmouseover
        {
            color: #0000FF;
            background-color: White;
        }
        .nav_menu_item_mouseover
        {
            color: White;
            background-color: #ec1c24;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul class="nav_menu_list">
            <li><a title="Page 1" href="#" class="nav_menu_item_notmouseover">Page 1</a> </li>
            <li><a title="Page 2" href="#" class="nav_menu_item_notmouseover">Page 2</a> </li>
            <li><a title="Page 3" href="#" class="nav_menu_item_notmouseover">Page 3</a> </li>
        </ul>
        <div style="clear: both;">
            <span id="infobox"></span>
        </div>
    </div>
    </form>
</body>
</html> 

Changing background image on <body> element with jQuery when using ASP.NET master pages

If you have an ASP.NET master page defined as below which specifies a css class for the body element to generate a background image for the whole page, you might want to override the default background on specific pages.

One way to accomplish this is to use jQuery to replace the css class that is being applied to the <body> element.

The master page below declares 2 ContentPlaceHolder controls; the first (ID="head") exisist within the <head> element, the second (ID="MainContentPlaceHolder") exists within the main body of the page.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
   
    <script type="text/javascript" src="jquery-1.3.2.js" ></script>
   
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
   
</head>

<body class="defaultbodybackground">
    <form id="form1" runat="server">  
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>

</html>

 

 
In one of our child pages we could add the following:


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script type="text/javascript">

           $(document).ready(function() {
               $("body").removeClass("defaultbodybackground");
               $("body").addClass("newbodybackground");
           })
        
        </script>
</asp:Content>


When the page is loaded, the above jQuery JavaScript runs and replaces the class "defaultbodybackground" with the page specific "newbodybackground".

A cool thing about jQuery is that you can have multiple $(document).ready() defined - for example you could also have some jQuery defined in the master page.

Throttle Your ASP.NET Connection Speed

As a tool to test responsiveness on slow connections Firefox Throttle is handy Firefox add-in. There is also an IE version. You can add a localhost throttle if you are using Visual Studios local web server. For example, setting the download speed to 56K dialup, you can check any Silverlight media buffering UI animations are working as expected.

Determine site’s absolute, fully-qualified url in asp.net

 I'm working on a Silverlight media player like you get on MySpace and other sites. The app is meant to be as simple as possible, so i've created a Silverlight-enabled WCF service which returns a list of the MP3s available in the songs directory on the server. To allow the SL app to be as loosely coupled to the location of the physical mp3s, the wcf service needs to return a list of fully qualified URIs to each mp3 in the directory. When the user selects a song to listen to we can simply set the MediaElement.Source to the URI.

 The following post contains some great code (that can even be used outside of a WebForm) to convert  "~/myfolder/mysubfolder" to http://foo.bar/myfolder/mysubfolder".

http://stackoverflow.com/questions/121962/determine-sites-absolute-fully-qualified-url-in-asp-net

 

Microsoft Certified Master Program

The 3 week master program costs US$18,500 (I'm assuming not inclusive of accommodation!) and runs in Redmond, Washington.

You have to be accepted onto the program by supplying a CV and potentially a 30-60 min interview (after paying $125 non-refundable fee).

 http://www.microsoft.com/learning/mcp/master/register/default.mspx 

Upgrade exams for MCPD to Visual Studio 2008

No dates as yet for upgrade exams, but if you're an existing MCPD (Windows, Web or Enterprise) you'll be able to take a single upgrade exam (except for Enterprise where 2 exams are required.

 

http://www.microsoft.com/learning/mcp/mcpd/vstudio/2008/default.mspx 

SilverKeys is Live

The first version of my Silverlight scale\chord finder is complete, it can be found at http://www.dontcodetired.com/live/silverkeys/

I'd like to improve the UX around the scale degrees, perhaps a circle of scale degrees...(I also have some TODO:s to do around refactoring)

I'll be posting source eventually in addition to an explanation of some of the more interesting elements..