Custom Hooks by Example
This custom hook example sets a component automatically so that site contributors do not need to set the same component manually for each descendent page.
Stepping through this example:
Next Steps:
The CustomsHooks.cs file is processed whenever an event is triggered in the CMS, regardless of if it was by a user, through workflow, or by another API-related action. Given this indiscriminate behavior of custom hooks, it's important that they handle any checks for specific scenarios. An example of such code would be a function that fires only when an administrator is performing the action.
There is no access to the display when running a hook, so while an error can be thrown, it will interrupt the processing of whatever called the script that threw the error. There is currently no method for messaging, so you can't communicate what your hooks are doing to the user that triggered them. It's best to make sure that the actions are thoroughly documented and easily discoverable for other developers.
Thoroughly test all scripts intended to be used as custom hooks before implementing them in a live environment. A poorly coded custom hook could prevent users from accessing content or logging in, and it could even destroy content in a site.
Complete Code for Custom Hook Example
public class CustomHooks : ICustomHooks
{
#region ICustomHooks Members
public void OnNew(IPage page, IUserWriteSession session)
{
this.SetComponentFromAncestor(page, "SiteControl");
page.Save();
}
...
#endregion
#region CustomHooks Helpers
public void SetComponentFromAncestor(IPage page, string eltName)
{
string eltID = this.GetSiteControlId(page, eltName);
if (!string.IsNullOrWhiteSpace(eltID))
{
this.SetElementValue(page, eltName, eltID);
}
}
public string GetSiteControlId(IPage parent, string eltName)
{
IPage current = parent;
while (current != null)
{
var elt = current.Element(eltName);
if (elt != null && !string.IsNullOrWhiteSpace(elt.Value))
{
return elt.Value;
}
current = current.Parent();
}
return "";
}
public void SetElementValue(IPage page, string eltName, string eltValue)
{
var elt = page.Element(eltName);
if (elt != null)
{
elt.Value = eltValue;
}
}
#endregion
}