Recently, I’ve been getting a lot of questions from people who ask how to manipulate the page from an extension in BlogEngine.NET. Most of the times the purpose has been to add a stylesheet or JavaScript reference in the page header dynamically.

It’s actually pretty easy but not that obvious so I thought I’d give an example. The following code inserts a stylesheet into the page header from an extension. Remember that the stylesheet must be placed in your theme folder.

Example


using System;

using System.Web;

using System.Web.UI.HtmlControls;

using BlogEngine.Core.Web.Controls;

using BlogEngine.Core;

 

[Extension("Test description", "1.0", "Mads Kristensen")]

public class PageTest

{

  public PageTest()

  {

    // Registers event handlers for serving both posts and pages.

    Post.Serving += new EventHandler<ServingEventArgs>(ServingHandler);

    Page.Serving += new EventHandler<ServingEventArgs>(ServingHandler);

  }

 

  private void ServingHandler(object sender, ServingEventArgs e)

  {

    HttpContext context = HttpContext.Current;

    if (context != null && !context.Items.Contains("PageTest"))

    {

      // Gets a reference to the serving page.

      System.Web.UI.Page page = context.CurrentHandler as System.Web.UI.Page;

      if (page != null)

      {

        // Creates a stylesheet link reference.

        HtmlLink link = new HtmlLink();

        link.Href = "style.css";

        link.Attributes.Add("type", "text/css");

        link.Attributes.Add("rel", "stylesheet");

 

        // Adds the stylesheet to the header of the page.

        page.Header.Controls.Add(link);

 

        // Sets a flag so only one stylesheet is added

        context.Items.Add("PageTest", 1);

      }

    }

  }

}

Last week Daniel Frost, the Danish Developer Evangelist from Microsoft came by to interview the co-founder of ZYB, Ole Kristensen and me about the semantic web and how we use it. He brought his camcorder and recorded the séance much the same way as Channel9 does – very down to earth and improvised.

It’s in Danish, but if you’re ok with that, then go take a look at the video.