Category Archives: Samples

Render MVCContrib Grid with No Header Row

The MVCContrib Grid allows for the easy construction of HTML tables for displaying data from a collection of Model objects. I add this component to all of my ASP.NET MVC projects.  If you aren’t familiar with what the grid has to offer, it’s worth the looking into.

What you may notice in the busy example below is the fact that I render my column headers independent of the grid contents.  This allows me to keep my headers fixed while the user searches through the table content which is displayed in a scrollable div*.  Thus, I needed a way to render my grid without headers. That’s where Grid Renderers come into play. 

  1. <table border="0" cellspacing="0" cellpadding="0" class="projectHeaderTable">
  2.     <tr>
  3.         <td class="memberTableMemberHeader">
  4.             <%= Html.GridColumnHeader("Member", "Index", "MemberFullName")%>     
  5.         </td>
  6.         <td class="memberTableRoleHeader">
  7.             <%= Html.GridColumnHeader("Role", "Index", "ProjectRoleTypeName")%>     
  8.         </td>       
  9.         <td class="memberTableActionHeader">
  10.             Action
  11.         </td>
  12.     </tr>
  13. </table>
  14. <div class="scrollContentWrapper">
  15. <% Html.Grid(Model)
  16.     .Columns(column =>
  17.             {
  18.                 column.For(c => c.MemberFullName).Attributes(@class => "memberTableMemberCol");
  19.                 column.For(c => c.ProjectRoleTypeName).Attributes(@class => "memberTableRoleCol");
  20.                 column.For(x => Html.ActionLink("View", "Details", new { Id = x.ProjectMemberId }) + " | " +
  21.                                 Html.ActionLink("Edit", "Edit", new { Id = x.ProjectMemberId }) + " | " +
  22.                                 Html.ActionLink("Remove", "Delete", new { Id = x.ProjectMemberId }))
  23.                     .Attributes(@class => "memberTableActionCol").DoNotEncode();
  24.             })
  25.     .Empty("There are no members associated with this project.")
  26.     .Attributes(@class => "lbContent")
  27.     .RenderUsing(new GridNoHeaderRenderer<ProjectMemberDetailsViewModel>())
  28.     .Render();
  29. %>
  30. </div>
  31. <div class="scrollContentBottom">
  32.     <!– –>
  33. </div>
  34. <%=Html.Pager(Model) %>

Maybe you noticed the reference to the GridNoHeaderRenderer class above?  Yep, rendering the grid with no header is straightforward.  

  1. public class GridNoHeaderRenderer<T> :
  2.     HtmlTableGridRenderer<T> where T: class
  3. {
  4.     protected override bool RenderHeader()
  5.     {
  6.         // Explicitly returning true would suppress the header
  7.         // just fine, however, Render() will always assume that
  8.         // items exist in collection and RenderEmpty() will
  9.         // never be called.  
  10.         // In other words, return ShouldRenderHeader() if you
  11.         // want to maintain the Empty text when no items exist.
  12.         return ShouldRenderHeader();
  13.     }
  14. }

Well, if you read through the comments, there is one catch.  You might be tempted to have the RenderHeader method always return true.  This would work just fine but you should return the result of ShouldRenderHeader() instead so the Empty text will continue to display if there are no items in the collection.

The GridRenderer feature found in the MVCContrib Grid is so well put together, I just had to share. 

* Though you can find countless alternatives to the fixed headers problem online, this is the only solution that I’ve ever found to reliably work across browsers. If you know something I don’t, please share.

.NET MailMessage, LinkedResources, AlternateViews and Exceptions

It doesn’t take much to hack together email functionality using the .NET framework.  In most cases you can new-up a MailMessage reference, assign sender and recipient addresses, provide a subject and a message body, configure your SMTP settings and then send.  Done and done.

But let’s say you need to provide both plain text and HTML versions of your message body.  Or maybe you would like to embed an image or two within the message body.  Or, what if, for some reason, you actually want to handle exceptions appropriately.  Well, there’s more to it then.

There are a numerous ways to better organize the following code.  In fact, we just went through an exercise at work where we refactored the heck out of the core email functionality and produce a really clean usable component which can be easily mocked, configured and leverages email templates.  It’s pretty cool.  That being said, I believe the following sample demonstrates the aforementioned core features of .NET emailing. 

I hope it helps. Let me know if I missed anything or it the example could be more clear.

    // Assign a sender, recipient and subject to new mail message
    MailAddress sender =
        new MailAddress("", "Sender");

    MailAddress recipient =
        new MailAddress("", "Recipient");

    MailMessage m = new MailMessage(sender, recipient);
    m.Subject = "Test Message";

    // Define the plain text alternate view and add to message
    string plainTextBody =
        "You must use an email client that supports HTML messages";

    AlternateView plainTextView =
            plainTextBody, null, MediaTypeNames.Text.Plain);


    // Define the html alternate view with embedded image and 
    // add to message. To reference images attached as linked 
    // resources from your HTML message body, use "cid:contentID" 
    // in the <img> tag...
    string htmlBody =
        "<html><body><h1>Picture</h1><br>" +
        "<img src=\"cid:SampleImage\"></body></html>";

    AlternateView htmlView =
            htmlBody, null, MediaTypeNames.Text.Html);

    // ...and then define the actual LinkedResource matching the 
    // ContentID property as found in the image tag. In this case, 
    // the HTML message includes the tag 
    // <img src=\"cid:SampleImage\"> and the following 
    // LinkedResource.ContentId is set to "SampleImage"  
    LinkedResource sampleImage =
        new LinkedResource("sample.jpg", 
    sampleImage.ContentId = "SampleImage";


    // Finally, configure smtp or alternatively use the 
    // mailSettings
    SmtpClient smtp = new SmtpClient
              Host = "",
              UseDefaultCredentials = false,
              Credentials =
                  new NetworkCredential("username", "password")

    //    <mailSettings>
    //        <smtp deliveryMethod="Network">
    //            <network host="" 
    //              port="25" defaultCredentials="true"/>
    //        </smtp>
    //    </mailSettings>

catch (ArgumentException)
    throw new
        ArgumentException("Undefined sender and/or recipient.");
catch (FormatException)
    throw new
        FormatException("Invalid sender and/or recipient.");
catch (InvalidOperationException)
    throw new
        InvalidOperationException("Undefined SMTP server.");
catch (SmtpFailedRecipientException)
    throw new SmtpFailedRecipientException(
        "The mail server says that there is no mailbox for recipient");
catch (SmtpException ex)
    // Invalid hostnames result in a WebException InnerException that 
    // provides a more descriptive error, so get the base exception
    Exception inner = ex.GetBaseException();
    throw new SmtpException("Could not send message: " + inner.Message);

Expand Urls with C# and LongUrlPlease

I think everyone is familiar with those short urls which are being passed around in applications like Twitter.  It’s pretty neat that there are dozens of services willing to shorten urls for us, but what about lengthening them?  That’s where comes in.  As they say, they promote safer and productive browsing by lengthening short urls so that you don’t have to.  The good folks at longurlplease provide an API documentation and demos on their site. I looked around a bit but I didn’t find a .NET/C# implementer so I put one together last night.

The included sample application merely requests that longurlplease lengthens 1+ short urls using the wrappers class which follows:


public class LongUrlPlease
    private const String LongUrlPleaseUri = "{0}";

    public static Dictionary<String, String> ExpandUrls(params String[] shortUrls)
        var longUrls = new Dictionary<String, String>();

        HttpWebRequest webRequest = GetLongUrlPleaseRequest(shortUrls);
        var response = (HttpWebResponse) webRequest.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
               longUrls = 
new JavaScriptSerializer().Deserialize<Dictionary<String, String>>(sr.ReadToEnd()); } } catch (WebException ex) { } return longUrls; } private static HttpWebRequest GetLongUrlPleaseRequest(IEnumerable<string> shortUrls) { Uri longUrlPleaseUri = GetLongUrlPleaseUri(shortUrls); return (HttpWebRequest) WebRequest.Create(longUrlPleaseUri); } private static Uri GetLongUrlPleaseUri(IEnumerable<String> shortUrls) { var parameters = new StringBuilder(); String delimiter = string.Empty; foreach (var url in shortUrls) { parameters.Append(delimiter).AppendFormat("q={0}", url); delimiter = "&"; } return new Uri(string.Format(LongUrlPleaseUri, parameters), UriKind.Absolute); } }

And here are a couple sample calls:

var singleUrl = LongUrlPlease.ExpandUrls("");

var multipleUrls = LongUrlPlease.ExpandUrls("",


Note the code comments as I needed to use the JavaScriptSerializer rather than the DataContractJsonSerializer due to the fact that longurlplease was essentially returning anonymous types back in the response. 

Download LongUrlPlease


ClickOnce Getting Started Sample

ClickOnce is pretty simple to get going once you know where to click (no pun intended.)  Here’s a down and dirty, quick start guide on how to implement ClickOnce in your application:

First, create a sample application in Visual Studio.  The attached sample is a WPF application using VS 2008.  ClickOnce configuration is managed through the project property pages so right-click on the project and click properties (or type ALT+ENTER) to access the properties pages.


Under the Signing Tab, Select Sign the ClickOnce manifest.  When you first publish, a temporary key (named [APPNAME]_TemporyKey.pfk) will be created and added to your the project.  Additionally, the temporary certificate information will be generated and displayed in the Certificate textarea.image

Under the Security Tab, Select Enable ClickOnce Security Settings.  Also select This is a full trust application.  If you wish to go with the partial trust option, I would recommend configuring your permissions per the Calculate Permissions option. 

Note, an empty WPF application (single XML windows with no logic) must be run as a full trust application according to the Calculate imagePermissions analyzer.  A similar Windows Application (single form with no logic,) in comparison, can be run with partial trust. 
Under the Publish Tab, enter a Publish Location.  You may, for example, provide a locally hosted website.  If the website doesn’t exist, it will be created – assuming appropriate permissions are granted to the logged in user.  Be sure to select imageThe application is available offline as well. 

Open the Updates… dialogue. Check The application should check for updates.  Keep the default which states the application will check for updates before it starts.  Click OK.

Open the Options… dialogue. Under Description, provide a Publisher and Product name.  Under Deployment, provide a imageDeployment web page.  I recommend “Publish.htm” and check Automatically generate deployment web page after publish.  Under Manifests, you may wish to select Create desktop shortcut. Click OK.

Your basic ClickOnce configuration is now in place and it is time to test.  Compile and publish the application.  Publishing many be done through the Publishing Tab’s Publishing Wizard, or via the Publishing imageNow option.  Alternatively, you may use the Publish option under the Build Menu. 

The Publish action will copy your compiled application to the publish location and render publish.htm page in your default browser.  Notice the application name, version and publisher is displayed along with an Install link.  imageClick on the Install link to kick off the download and installation of the application. You will be potentially be prompted with a security warning along with the request to install.  Continue with the installation.  Once complete, the application will launch automatically.  The application may be launched via the application shortcuts going forward. 

That’s it. The downloadable sample application doesn’t do much of anything. It merely demonstrates the installation of a WPF application using ClickOnce technology.  You may uninstall as you would any traditional application. 

Download Sample ClickOnce WPF


See ClickOnce In Action:

Caching with C#, AOP and PostSharp

I’ve been spending lots of time getting my head around Aspect-Oriented Programming (AOP). At its foundation, AOP separates crosscutting concerns (concerns which are not localizable and cannot be implemented successfully using pure imperative or object-oriented programming) into loosely coupled, modularized units called aspects and injects them into the otherwise one-dimensional base program.  Without AOP, we end up with a system with tangled and scattered code which is harder to design, understand, implement, and evolve primarily due to poor traceability, lower productively, less code reuse and testing difficulties. With AOP, well, my head started to hurt…until I put an ended to my research and put AOP to practice.image

I know it’s a bit of a tease, but I’m going to save my “What is OAP” post for another day.  Right now, I’m going to show you some code.

Postsharp is an open source library which encapsulate aspects as custom attributes and adds new behaviors to your code through policy injection (which is just another name for AOP.) 

Smelly, Old Code

The follow code serves as an example of a crosscutting concern (Cache) which needs to be separated from the base program and modularized into an aspect.  Notice the offending code checks the cache and queries the database.  It laughs in the face of the Single Responsibility Principle.

private const string KeyNumber = "RandomNumber";

private int GetNumber()
    int value;
    if (!CacheHelper.Get(KeyNumber, out value))
        value = DataAccess.GetNumberRandom();
        CacheHelper.Add(value, KeyNumber);

    return value;

Shiny, Happy Code

Using PostSharp, GetNumber() is left to do one thing (query the database) and all the caching checks are handled by the aspect, the custom CacheAttribute.  Notice this is all hooked up by decorating GetNumber() with the CacheAttribute tag which accepts the key in the constructor.

private const string KeyNumber = "RandomNumber";

// Pass the key associated with the cached item in the constructor
private int GetNumber()
    // This logic is only executed if the CacheAttribute calls upon it.
    return DataAccess.GetNumberRandom();

The attribute’s logic is basic but very powerful.  When the GetNumber (or any other method which is decorated with the CacheAttribute)  is invoked, CacheAttribute checks to see if the data is in cache using the provided key.  If so, the data is extracted and returned. Period. The GetNumber method is completely bypassed and never executed.  In the sample application, I added some logging to help clarify this point.  However, if the data is not found in cache, the custom attribute invokes the caller, the GetNumber() method, stores the result in cache and then returns the value.  In this case, GetNumber’s logic is executed but it is invoke via the CacheAttribute. 

using System;
using PostSharp.Laos;

namespace PostSharpWebApplicationCache
    public sealed class CacheAttribute : OnMethodInvocationAspect
        private readonly string key;

        public CacheAttribute(string key)
            this.key = key;

        public override void OnInvocation(MethodInvocationEventArgs context)
            object value;

            if (!CacheHelper.Get(key, out value)) 
                // Do lookup based on caller's logic. 
                value = context.Delegate.DynamicInvoke();  
                CacheHelper.Add(value, key); 

            context.ReturnValue = value;

As you can see, both the smelly, old code and the shiny, happy code achieve the same effect, but the latter option is a lot cleaner and more elegant if you ask me.

As noted, I’ve included some downloaded code if you want to play around with Postsharp and AOP on your own.  To get the code to work, you’ll need to visit the Postsharp site and install the latest bits.  In my case, I’m using PostSharp 1.0.  Please don’t be fooled.  You’ll need to use an ASP.NET Web Application Project rather than ASP.NET Web Site in order for PostSharp to work.  This is because Postsharp does compile-time weaving and cleverly mucks with your IL. Details.  Don’t worry. we’ll get into all of it.  For now, just trust me and know the sample project is a Web Application Project.  Enjoy.


Download Sample PostSharp Web Project:

jTemplates with jQuery, AJAX and Json

jTemplates is a jQuery plugin and template engine for Javascript.  If you keep up with Dave Ward and/or Rick Strahl you may already be familiar with jTemplates as they have both highlighted the plugin on their respective bolgs.  About 1.5 months ago, however, I got into the action and started using jTemplates in conjunction with jQuery, AJAX and Json to dynamically populate dropdowns and tables on the client side.

As you’ll see in the examples, jTemplates provides custom syntax to do such things as iterate through Json data and populate a predefined template.  Once you get a grasp of the syntax and the proper usage, you will be ready to roll.  Getting started is easy — just download the latest jQuery and jTemplate bits and reference them within your html or aspx file.

Next, you need to define and host your templates.  In the included sample project, I’ve defined two templates to aid in the population of my dropdown and my table respectively.  Here you will notice the dropdown template merely adds a singe “Select One” entry and then iterates over all project results adding a new option for each:

<%-- Project Dropdown Template --%>
<script type="text/html" id="TemplateProjectSelect">    
<option value="">Select One</option>
{#foreach $T.result as project}
    <option value="{$}">{$}</option>

And the following table template is a little more complex but still very to interpret.  Here, we are iterating over each task row and appending a new row to the table for each.  Notice there’s a MAIN template and a ROW template.  The MAIN template passes along the current record to the ROW template.  The ROW template sets the appropriate class (think table zebra stripes) and column values based on the current “cycle.”

<%-- Results Table Template --%>
<script type="text/html" id="TemplateResultsTable">    
{#template MAIN}
<table width="500" border="0" cellpadding="5" cellspacing="0">
    <th width="50">ID</th>
    <th width="300">Task</th>
    <th width="104">Hours</th>
  {#foreach $T.result as task}
    {#include ROW root=$T.task}
{#/template MAIN}

{#template ROW}     
<tr class="{#cycle values=['','evenRow']}">
{#/template ROW}

How’s about hosting the templates?  You have a few options.  First, you could save the templates off in their own file.  This is the approach Dave Ward took in his article. Though this approach is clean, it doesn’t perform all that well.  The preferred approach is to “embed” your templates within the html/aspx file by wrapping each of the above templates with a script tag like so:

<script type="text/html" id="TemplateResultsTable"> 

... template here ...


As shared on Rick Strahl’s post, this is the preferred approach as using <script type=”text/html”> that allows hiding any markup in the document without interfering with HTML validators. The script can be accessed by its ID and the content retrieved using the jQuery .html() syntax.

Once your template is in place, you simply need to assign your template to your container (a div) and then process the template using your Json data.  As noted above, you may reference an external template using the following:


Or you may select the template from the html/aspx itself:


Again, the preferred approach is the latter.  In either case, you process the template data (results) as follows:


A quick note on .processTemplate.  You don’t actually have to provide any data.  You can send null into the processTemplate method if, for example, no processing is required.  In the downloadable example, I create a static template which acts as a place holder when my page first loads and no table data is available. Here’s the sample template and javascript:

<%-- Emtpy Table Template --%>
<script type="text/html" id="TemplateResultsEmpty">    
Select a client and project...


Before I wrap things up, I should mention the downloadable sample project doesn’t only show off jTemplates.  It also demonstrates how to use jQuery and an “parameterized” HTTPHandler to pull back Json data which is somewhat an extension of my earlier HTTPHandler post.

Download jTemplates Sample Project:


HTTPHandler with JSON Data

As javascript libraries, particularly jQuery, increase in popularity so do web techniques using AJAX and JSON.

Have you ever seen this code?  It is front and back of an ASPX file with the single responsibility to return JSON data per an AJAX request.


<%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="GetDataPage.aspx.cs" Inherits="GetDataPage" %>
    This minimal code is here to prevent the following error:
     "Using themed css files requires a header control on the page"
     Please see 
     for more information --%>
<head id="Head1" runat="server" visible="false" />


using System;
using System.Web;
using System.Text;

public partial class GetDataPage : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        // Clear out the buffer

        // Do not cache response

        // Set the content type and encoding for JSON
        Response.ContentType = "application/json";
        Response.ContentEncoding = Encoding.UTF8;

        int page = int.Parse(Request["p"]);
        string results = DataAccess.GetResults(page);


        // Flush the response buffer

        // Complete the request.  NOTE: Do not use Response.End() here,
        // because it throws a ThreadAbortException, which cannot be caught!

You may have noticed there’s a comment for nearly every code block.  At first, one may find the comments redundant and unnecessary, but really they are call for help.  A code:comment ratio like this usually indicates you really need to focus on what’s happening with the code because if you aren’t paying attention, bad things might happen.

As you have undoubtedly concluded, there’s a lot of overhead associated with returning JSON data from an ASPX file.  This statement is especially true if you consider the alternative, an HTTPHandler.  Here’s a cleaner, best-practices approach which provides the same outcome with less code, comments and risk.


<%@ WebHandler Language="C#" Class="GetDataHandler" %>

using System.Text;
using System.Web;

public class GetDataHandler : IHttpHandler
    public bool IsReusable
        get { return false; }
    public void ProcessRequest (HttpContext context) 
        context.Response.ContentType = "application/json";
        context.Response.ContentEncoding = Encoding.UTF8;

        int page = int.Parse(context.Request["p"]);
        string results = DataAccess.GetResults(page);

If you are already accustomed to using generic handlers to stream back images, XML, JSON data, etc, this post was probably a bore. But it’s sometimes easy to forget what’s available to imageyou in the vast .NET stack, so hopefully you appreciate the friendly reminder.  In either case, it still surprises me how many examples use the ASPX approach.  In fact, the practice is common enough that I sometimes wonder if there’s an HTTPHandler gotcha to which I’m not privy .  If I am missing something, please let me know.

If you’re still interested, attached you’ll find code which populates two jQuery Flexbox controls using JSON data provided through an ASPX and ASHX files.  This may be worthwhile download if you’re interest in the generic handler code or you want a further look at Flexbox in action after last week’s post.

Download JsonHandler Sample Project: