Thursday, September 15, 2011

ASP.NET Substitution Control and Output Caching


Ever want to use Output Caching to cache a page, but you didn't because there were some bits of the page that you just couldn't cache?

ASP.NET has a Substitution control that lets you handle that scenario...

At the top of your page, you might have this...
<%@ OutputCache Duration="10" VaryByParam="none" %>


Somewhere later in the page, you could have this...
<asp:Substitution runat="server" ID="sub" MethodName="GetTime"/>


And in your code-behind, you could have this...
public static string GetTime(HttpContext ctx)
{
    return DateTime.Now.ToString();
}

The entire page will stay cached for 10 seconds...except for the substitution control, which will update every time you refresh the page. I love it!

Linq Aggregate - one liner for comma separated lists

Here's a cool Linq function for creating a comma-separated list from a collection of strings... It even handles the case where there's only one thing in the list, and it doesn't add a final comma at the end...pretty slick!

myList.Aggregate((s1,s2) => s1 + ", " + s2)