Programmatically moving Umbraco nodes

15 January 2009 · 2 minute read · umbraco

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

    } catch (DocTypeMissMatchException) { }
  }
}

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.


Published: 2017-10-23 19:16:31 +1100 +1100, Version: 7c4a504