Scott
Hanselman showed us how to add MicroSummaries to
a website using an .ashx file. It was clean and simple, but it would be really cool
if we could use the description meta tag instead so we don’t have to maintain two
separate files.
I played with the thought and came up with a very simple solution that uses regular
expressions to extract the description meta tag from the rendered page and outputs
it in the response stream. It works by listening for a querystring called microsummary,
and it even outputs the correct link tag to the head section of the page.
<link rel="microsummary" type="application/x.microsummary+xml" href="/currentpage.aspx?microsummary=1"
/>
The only thing you need is a <head runat=”server”> on your ASP.NET 2.0
page. Keep in mind that this solution only works if you have a description meta tag
on you page, otherwise it will just output the title of the page. It consist
of two methods – one that generates the link tag and one that outputs the description
as a MicroSummary. Then just call these methods from the Page_Load or preferably as
soon as possible in the page life cycle such as Page_PreInit. It depends on when you
set the description meta tag.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack
&& !Page.IsCallback)
{
if (Request.QueryString["microsummary"]
!= null)
{
WriteMicroSummary();
}
else
{
SetMicroSummaryLinkInHeader();
}
}
}
private void WriteMicroSummary()
{
using (StringWriter sw
= new StringWriter())
{
Page.Header.RenderControl(new HtmlTextWriter(sw));
string html
= sw.ToString();
string lookFor
= "<meta name=\"description\" content=\"";
Match match
= Regex.Match(html, lookFor
+ @"[^""]*""", RegexOptions.IgnoreCase);
if (match.Success)
{
string description
= match.Captures[0].Value.ToLower().Replace(lookFor, string.Empty);
Response.Write(description.Substring(0,
description.Length - 1));
}
else
{
Response.Write(Page.Title);
}
Response.End();
}
}
>
>
private void SetMicroSummaryLinkInHeader()
{
HtmlLink ms
= new HtmlLink();
ms.Attributes["rel"]
= "microsummary";
ms.Attributes["type"]
= "application/x.microsummary+xml";
string url
= Request.RawUrl + "{0}microsummary=1";
if (Request.RawUrl.Contains("?"))
ms.Href
= string.Format(url, "&");
else
ms.Href
= string.Format(url, "?");
Page.Header.Controls.Add(ms);
}