Monday, 28 July 2008

PlugIns and DataFactory Event Handlers

Inspired by great post of Allan Thraen about When and Where to attach DataFactory Event Handlers I decided to keep digging into this subject. What seems really cool about it is that you can attach to DataFactory events and moreover you can do it in a pluggable way.

In this post I wanted to show how Allan's PlugInAtttibute class can be refined to read configuration from the EPiServer.

But first of all ... real life example ... to justify existence of this post ;)

Task: I want to be able to hide some pages in edit mode, tweak left side tree to not show some of my pages. And additionally I want to have it configurable so that I can change ID of the page which will be hidden without recompiling source code, changing web.config etc.

Step 1 - Create GuiPlugIn

In our case we will use it only to store data. Class can look like this:


[GuiPlugIn(Area = PlugInArea.None, DisplayName = "Settings")]
public class PluginSettings
{
protected string pagesToHide;

[PlugInProperty(Description = "Page ID", AdminControl = typeof(TextBox))]
public string PagesToHide
{
get { return pagesToHide; }
set { pagesToHide = value; }
}
}


and thanks to that in admin mode we will be able to define page ID.



Step 2 - Attach to the FinishedLoadingChildren event

In this step we will follow Allan's approach:



public class RegisterEventsPlugIn : PlugInAttribute
{
public static void Start()
{
//Attach to the right events
DataFactory.Instance.FinishedLoadingChildren += Instance_FinishedLoadingChildren;
}


static void Instance_FinishedLoadingChildren(object sender, ChildrenEventArgs e)
{
// /UI/to/edit/EditTree.aspx
if (HttpContext.Current.Request.Url.ToString().StartsWith(Settings.Instance.UIUrl.ToString()))
{
PluginSettings settings = new PluginSettings();
PlugInSettings.AutoPopulate(settings);

foreach (PageData child in e.Children)
{
if (child.PageLink.ID.ToString() == settings.PagesToHide)
{
e.Children.Remove(child);
break;
}
}
}
}
}



One thing which might be new are those two lines:


PluginSettings settings = new PluginSettings();
PlugInSettings.AutoPopulate(settings);


Those two lines do the trick of reading the configuration. And basically that's it, everything should be working now.

I was also thinking about different scenario where this approach might be perfect -- we use SortIndex to order pages quite often, but it's a hassle for editors to remember about it. Solution might be to create plugIn which would automatically, based on some custom rules, assign correct SortIndex for newly created pages. It's definitely doable and I'm sure that editors would love it!

1 comment:

Thomas Leela said...

Thanks for the article Marek, just what I was looking for.
since you are expecting a page ID as input, you might have done like this:
[PlugInProperty(Description = "Page ID", AdminControl = typeof(EPiServer.Web.WebControls.InputPageReference), AdminControlValue = "PageLink")]
public string PagesToHide