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);

      }

    }

  }

}

Today, I finally deployed the new widget framework of BlogEngine.NEXT to my blog. It’s been under development for some months now, so it’s nice to see it in action for the first time on a live site.

For some time now, I’ve wanted to write new widgets but didn’t have any places to put them. Before now that is. The first thing that came to my mind was to write a Twitter widget displaying my last Twits. You can see the result on the side panel to the right. The widget just took about an hour to write.

The video

If you are interested in seeing how the Twitter widget works or to get a sneak peak of the widget framework, then here is a new video that explains the Twitter widget. If you watched the video displaying the early prototype of the widget framework, you might notice a lot of the changes and improvements we’ve done so far.

Download the video 

The code

If you run the latest and greatest build of BlogEngine.NET available from CodePlex, then you can add the Twitter widget to your own blog. Just download the zip file below, and put the Twitter folder into your blog’s widget folder.

Twitter.zip (2,82 kb)