Creating Helpers for ASP.NET Web Pages with WebMatrix

If you are unfamiliar with helpers and haven’t read my blog post on “Getting Started with ASP.NET Web Helpers for WebMatrix”, you should start reading there.  Otherwise, we’ll move on to create helpers for use with the Razor View Engine and WebMatrix.  In a later post I’ll describe how to create helpers using Visual Studio 2010 for use in WebMatrix.

There’s four steps to creating helpers for Razor views.

1. Create the helper file.

The helper file belongs in the \App_Code folder located under your site’s root.  If there is no \App_Code folder in the project, go ahead and create one.  You can name it whatever you’d like, but note that the name of the helper file without the extension will be used in the calling syntax and the extension must be .cshtml. In MVC with VS 2010, helper are stored as .cs or .dll files instead.

cshtml_2

 

2. Add the @helper directive to the top of the helper file.

Here’s what the signature for a helper looks like:

@helper HelperName([DataType arg], [DataType arg]…) { // helper code }

 

You can store multiple helpers in a single .cshtml file, as well as functions which we’ll look at in the next section of this post.  Each helper works syntactically as if it’s a static method when called (more on that below).

3. Add code, markup and text.

Start adding elements that you want to render and don’t forget that Razor code is case sensitive.  In this example, a helper named  RenderDiscountedPrice that accepts a decimal input and renders out a message displaying the featured product’s final price with the discount.

@helper RenderDiscountedPrice(decimal price)

{

    Buy now for only <strong>$@(GetDiscountedPrice(price))</strong> with $1.00 off!

}

Alternatively, if you want to also use functions in a helper for doing calculations, providing logic, etc.…you can.   Here’s a code sample showing the same code but rewritten to include a function:

@helper RenderDiscountedPrice(decimal price)

{

    Buy now for only <strong>$@(GetDiscountedPrice(price))</strong> with $1.00 off!

}

 

@functions {

    public static decimal GetDiscountedPrice(decimal price)

    {   

        return price-1// just a dollar off, we’re cheap

    }

}

All that’s needed for a function library is the @functions declaration with braces to signify the beginning and ending of the code block.  Many functions can be placed here and the function signatures have the exact syntax as if they were in a standard .cs file.  The calling syntax,HelperFileName.helperName([args…]); is a combination of the filename without the extension but with the name of the helper instead. Using default.cshtml located at the root of the web site, locate this block of code…

<div id=”featuredProduct”>

    <img alt=”Featured Product” src=”@HrefAttribute(“~/Images/Products/” + featured.ImageName) />

    <div id=”featuredProductInfo”>

        <div id=”productInfo”>

            <h2>@featured.Name</h2>

            <p class=”price”>$@string.Format(“{0:f}”, featured.Price)</p>

            <p class=”description”>@featured.Description</p>

        </div>

        <div id=”callToAction”>

            <a class=”order-button” href=”@HrefAttribute(“~/order”, featured.Id) title=”Order @featured.Name“>Order Now</a>

        </div>

    </div>

</div>

and replace it with this block of code (the highlighted code is the modifications necessary)…

<div id=”featuredProdcut”>

    <img alt=”Featured Product” src=”@HrefAttribute(“~/Images/Products/” + featured.ImageName) />

    <div id=”featuredProductInfo”>

        <div id=”productInfo”>

            <h2>@featured.Name</h2>

            <p class=”price”>

                @{var price = featured.Price;}

                $@string.Format(“{0:f}”, price) <br/>

                @Pricing.RenderDiscountedPrice(price) // HelperFile.HelperName syntax/behaves like a static

            </p>           

            <p class=”description”>@featured.Description</p>

        </div>

        <div id=”callToAction”>

            <a class=”order-button” href=”@HrefAttribute(“~/order”, featured.Id) title=”Order @featured.Name“>Order Now</a>           

        </div>   

    </div>

</div>

The code’s been changed to declare a variable named price and set it to the featured product price, which is then to be used in the following two lines of code, including the existing line that renders the price.  The variable is available to all parts of the web page below where it’s declared by default. (you can modify a variable’s scope if need be).  Anywhere in the Bakery site that you want to include a message about the discount, you can use the same single line call to produce the same message about the discount.

4. Verify the Results

Run the default.cshtml file and check that the sales message has been rendered.

image_8

When using WebMatrix as the tool for creating helpers, you can release helpers only as .cshtml files into \App_Code folders across projects (at this point in time, and subject to change).  If you need to release .dll files, you can create helpers in Visual Studio 2010 and package them with NuPack if you’re creating something sharable or as a private .dll otherwise.

Why ASP.NET MVC is different than Classic ASP

There’s still a lot of Classic ASP developers out there, maintaining and adding features to existing ASP sites. Many want to migrate or upgrade to ASP.NET, and particularly ASP.NET MVC. During my MVC presentations, the most frequently asked question I get is: “This looks like Classic ASP code, are we just going backwards with MVC stuff?”. If we dig into MVC a bit deeper, we’ll see that the answer is most definitely, NO. Although at first glance, the mixture of HTML and script in the views may appear to be similar to Classic ASP, upon further investigation, there are some very remarkable differences.

Note: When speaking of Classic ASP in this post, I’m referring to the ASP found in .asp pages, not .aspx Web Forms.

MVC Models & Classic ASP Data Access

MVC:

There are many options for dealing with data in MVC models; EF (db or code first),  LINQ to SQL, POCOS, Service Layers or even DataSets and DataReaders. No matter what the choice, all data model code is partitioned away from the views and controllers, and that’s the important factor to consider. MVC convention and application templates guide the developer to add models to a \Models folder or use a library reference (preferably) the data access layer. As a developer you get full control over where and how you create the data access layer and business objects so it doesn’t interfere with UI code.

Classic ASP:

There’s two primary ways of dealing with data in ASP. Developers often place data access code directly in the .asp page and other times in a COM component. Data returned from the data access layer is returned into ADODB.Recordset objects which represent the data as a rectangle, and that data is directly sent to the ASP page.

Because of the tight coupling, code in the data access model is harder to test and maintain.

MVC Views & Classic ASP Pages

MVC:

Views are the reason that prompts developers to look at MVC and think it’s similar to ASP, and that’s because in the view both HTML and code exist side by side. However, peering into views a bit deeper reveals that views contain only enough markup and syntax to render pages from data that is passed to views from a controller. That means the code in MVC isn’t a bunch of large gobs of script interlaced with markup, they’re generally just code nuggets. This also means that the most noticeable difference is the lack of actual code itself (hopefully!), as views should be clean and not cluttered.

Classic ASP:

Pages in ASP often contain server script, client script, markup, and the kitchen sink thrown in for good measure. JavaScript obtrusively pilfers the markup throughout entire pages. All too often, the ASP page contains large amounts of business logic code, and everything gets stuffed into big .asp pages.

Although there are techniques for working with ASP to get some separation of concerns, that concept gets offset since most all of today’s ASP development is in maintenance mode so many aren’t investing in enhancing Classic ASP technology, particularly when there are other alternatives.

MVC Controllers & Classic ASP

MVC:

Rather than mapping URL addresses to individual static pages living on a web server, MVC uses Routing to map the HTTP request to methods, not complete pages, in controllers called action methods. Action methods retrieves an entity in the model to match the model to a corresponding view based on routing information in the URL. These URL patterns, called Routes, are defined and added to an application wide RouteTable object so the routes can identify and execute controllers automatically. This gives tremendous flexibility, as the controller can behave as a traffic cop, directing requests to a specific code location which is natively more testable than a whole page. This also gives us a nice separation of concerns as well.

Classic ASP:

There’s nothing to compare to a controller in ASP as there’s nothing out of the box that supports routing in any similar way to MVC. URLS are directly mapped to a an .asp file and there’s nothing in the ASP platform itself to help out. You could write an ISAPI filter or some sort of module to create your own routing system, but it’s more work and maintenance compared to MVC, as MVC has this functionality built in.

Summary

MVC isn’t just a rehash of Classic ASP and we’re definitely not going backwards in technology with it. MVC gives you a way to write much cleaner, separated,  and robust code. The MVC pattern and ASP.NET MVC project templates in Visual Studio also assist in guiding the developer to do better things with their code, such as unit testing or implementing other practices such as dependency injection (DI), which are hard to near impossible to do in older versions of ASP. The good news: If you’re writing ASP applications now, the move from Classic ASP to MVC doesn’t have to be such a huge learning curve.

A few tips for being a more effective solo developer

There’s tons of developers that are self employed, freelance or consultant; some who take long term contracts on teams and others that have a few key, stable customers that they routinely work for.  If you’re solo in the sense that you’re the primary start-to-finish person for most of your projects, there’s not a lot of resources out there targeted your way. Most training, talks, books, blog posts and other content is geared toward the enterprise developer that works on a team.  Since that’s the case, I wanted to throw out a few things you can do as a solo developer to take some of the pain away from not having the resources that teams generally have (e.g., hardware, CI server, costly software developer tools, etc…) to help boost your productivity.

Use Source Code Control

Many solo developers have managed with their own way of using “copy & paste” source control.  While you might have a routine down when doing so, you can still benefit from even some of the basic features of source control – with actual source control being the first reason.  There’s lots of room for mistake when something’s done manually, particularly when that something is maintaining versions of sets of files.

Source control systems offer basic tracking of files and project assets that you’ll label with a version, and most integrate with familiar tools like Visual Studio (often including express versions).  SCC software also allows you to freely explore code you’d like to write without you having to mentally keep track of changes when changing code, you can work on multiple files and roll back any or all of them to their previous state, without worry.  It’s safe to say that most developers have experienced this pain at least once in their career – that is, chasing an idea with many changes to the code and when the developer’s ready to ditch the changes, s/he can’t recall what’s been changed.

Download  TFS Basic for Visual Studio 2010 for individual source code control, and you can also use other popular SCC programs like Tortoise SVN.

Try out some Agile practices

Although you can’t do 100% Scrum (an Agile subset) as an individual developer you can do some of it.  Obviously it’s silly to do daily standups as an individual, but you can still incorporate many parts of Agile and/or Scrum into your projects.

The Agile manifesto states the principles that Agile values…

“Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan

That is, while there is value in the items on
the right, we value the items on the left more.”

These principles are easy to follow as an individual developer or as a team, it works for everyone.

One of the most important things to remember is to keep the feedback loop with your client open, and have frequent discussions with the client about the progress of the app.  Respond to change by allowing the feedback from the customer to drive the next cycle of coding, which should be short (1-2 weeks). As a solo developer, you can create and use backlogs, use burn down charts and hold retrospectives with the customer. Those practices give a nice reality check as to the health of the project.

JD Meier’s blog with living Agile

Unit Testing – It’s for you too.

You may be thinking unit testing is overkill for the type of projects you work on particularly if they’re small projects, or that it’d cost too much to ramp up to speed with a testing framework and tools.  If so, you’re not alone, as those are some common misconceptions that solo developers make (perhaps because they’re not getting out to mingle with their professional peers and aren’t getting up to date info; see below 😉 ).

If you’re looking for a low friction way to get started with unit testing and you’re already using Visual Studio 2010, then try the built in MS Test tools.  After you get a solid feel for creating unit tests; the knowledge is there to compare other tools & testing frameworks such as nUnit or xUnit (xUnit was built by Brad Wilson on the ASP.NET team).

One of the primary goals of ASP.NET MVC is to promote a concept called “convention over configuration”.  This means when writing MVC applications, developers are guided to use test projects when without having to download separate utilities, as well as guided to use other best practices.  By using the conventions, your code will be cleaner and better, especially because you’re now testing.

Get out and mingle with your professional peers

Don’t get out to user groups? Code Camps? It’s a great place to network and learn new things, and keep your skills sharper than they’d be without.  Get on social networking like Twitter, LinkedIn and Facebook.  These are all great ways to keep in touch with other developers, many of whom are also solo devs.  Having an issue?  Post the question on forums such as http://www.asp.net or MSDN Forums (among many others). Send out a tweet on Twitter and watch the replies come in, or post questions on a blog, many of who are on the various product teams here at Microsoft. Getting an answer from the source or a trusted MVP or community members is a great way to expand your knowledge base, stay up to date, and see what’s important out there to other developers.