Quick tip: Using extension methods with Umbraco and .net 3.5

Ever wished that the Umbraco API had an extra method or two? The example below uses .net framework 3.5 extension methods to accomplish just that.

Extension methods allow you to add new methods to existing classes without extending them.


// Today would return 2010/02/25
string path = String.Format("{0:yyyy/MM/dd}", DateTime.Now);
Doucment parent = new Document(id);
Document newDoc = parent.MakePath(path, new DocumentType(parent.ContentType.Id), true);

// MakePath isn't an Umbraco API method, so we'll add it using extension methods.
namespace FM.Umbraco
{
    public static class DocumentExtensions
    {
        public static Document MakePath(this Document d, string path, DocumentType dt, bool publish)
        {
            Document parent = d;
            User u = new User(0);
            foreach (string component in path.Split('/'))
            {
                int parentId = parent.Id;
                Document child = parent.Child(component);

                if (child != null) { 
                    parent = child; 
                }
                else
                {
                    parent = Document.MakeNew(component, dt, u, parentId);
                }

                if (publish)
                {
                    parent.Publish(u);
                    umbraco.library.UpdateDocumentCache(parent.Id);
                }
            }
            return parent;
        }

        public static Document Child(this Document d, string name)
        {
            foreach (Document child in d.Children)
            {
                if (child.Text.Equals(name))
                {
                    return  child;
                }
            }
            return null;
        }
    }
}
Leave a comment