Programmatically moving Umbraco nodes

Thursday, Jan 15, 2009 2 minute read Tags: umbraco
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

The other month Ruben did a post on using the new Umbraco event model and today I had to solve a problem which it seemed like it would be the best way.

I needed to have a document, when published, moved into a new folder (as we're using Umbraco to store some data used for some non-browsable data). This can be achieved with the old IActionHandler.Execute method, but it was a little problematic, you needed to have some way to check if it was running because you moved and republished, or the initial publish.

Luckily, the Umbraco v4 event model makes this really nice and easy. Well, slightly easier, there's a few things that are still a bit of a pain, but it's not a problem with Umbraco, more a by-design limitation.

So lets get into some code.

public class ActionHandler : ApplicationBase {
  public ActionHandler(){
    Document.BeforePublish += new EventHandler(Document_BeforePublish);
  }

protected void Document_BeforePublish(Document sender, PublishedEventArgs e){ try { MyDocType dt = new MyDocType(sender); if(dt.SomeField == “stillToMove”) { e.Cancel = true; dt.ParentId = 1234; dt.SomeField = “it’s moved!"; dt.Save(true); }

} <span class="keyword">catch</span> (<span class="const">DocTypeMissMatchException</span>) { }

} }

So I've used the UIL to generate a class representation of my docType (aptly named MyDocType :P) and from that I'm having to check a field on the document. This could be anything from a standard field to a the parent ID to the published state.

The really nice part about using the event handler I can stop the current publish action. This will improve performance and database hits.

You can do this without the UIL, but because of some of the built in features of the UIL it can be easily used to detect the correct docType. There's no need for magic numbers (and I'm sure a better way to pass the new parent ID can be thought up!).

So all in all I think that the new event model can have some really powerful aspects to it, it provides much more flexibility and event variety over IActionHandler.Execcute.