Tuesday, February 22, 2011

Writing a WebMatrix Helper

I’ve been playing around with Microsofts WebMatrix for some time now. Together with the new Razor View Engine, Microsoft introduced the concept of Helpers. Helpers are mostly small static classes with static methods that generate some Javascript or HTML code which is rendered onto a web page at run time. It’s pretty easy to write such a helper yourself and I’m going to present the steps required within this post. As an example, I’ll show you how to create a helper, that inserts a “Add to favorites” link to a site.

Let’s first create a new class library project in Visual Studio 2010. I just name it HelperLibrary. Within the project delete the class that was generated by the Visual Studio template and create a new class named FavoriteHelper. Make the class public and static. Before we can write our methods, we need to import the following two DLLs:
·         System.Web
·         System.Web.WebPages

In the class insert a static method named AddToFavorites with the following signature:

public static HelperResult AddToFavorites(string text)
    return new HelperResult(tw => tw.Write(
        "<a href=\":"+
            "\" onDragstart=\"return false\" "+
            " onClick='window.external.AddFavorite(location.href,
document.title);return false'>"+

The method accepts a string parameter, whose text will later be shown on the web page. It returns an object of type HelperResult which can be interpreted by the Razor Engine. The HelperResult class is contained within the System.Web.WebPages assembly and accepts a TextWriter in its constructor.
Alternatively you could use the following method:

public static IHtmlString AddFavorite(string text)
    return new HtmlString("<a href=\":" +
                            text +
                            "\" onDragstart=\"return false\" " +
                            " onClick='window.external.AddFavorite(
location.href, document.title);return false'>" +
                            text + "</a>");

In that case you won’t need the System.Web.WebPages.dll. It’s also a little bit easier, because you don’t have to use an additional TextWriter.
After we have inserted our methods, we need to build the library and integrate it into our WebMatrix project. Before compiling the assembly, check the settings and make sure the correct framework version is used. In order to use Razor, you have to target at least .NET Framework 4.0. After building the assembly we can just copy it to the bin folder of our web application project, hit refresh within WebMatrix and insert the call to our helper method on any web page:

@HelperLibrary.Favorites.AddToFavorites("Add to favorites!")

Pay attention to use the full namespace declaration. Otherwise the method won’t be found.
If you start the page, you will see a link on it to add this page to your favorites:

A test by clicking on it reveals that it works: