Thursday, October 4, 2012

Load Umbraco nodes by Guid and print Guid's in Razor

Umbraco internals provide methods for accessing objects by Guid instead of ID.  This is necessary when using multiple environments and moving files around with Courier.  The reason being that ID's are not unique across instances and as items are moved around they will get assigned new ID's.  The following for example will not work as expected when deployed with Courier.

@Model.NodeById("Some static pageId").myVariable

To do this properly the Guid is needed instead. The problem though is that the Razor DynamicNode object doesn't expose or let you load nodes by the Guid.  The included class can be added to your App_Code directory to allow the following code samples to work in Razor.

using JSP;
// Get a object by the Guid
@Model.NodeByGuid("someGuid").myVariable
// Print a object's Guid
@Model.UniqueId()


GuidExtensions.cs
using System;
using umbraco;
using umbraco.MacroEngines;
using umbraco.cms.businesslogic;

namespace JSP
{
    /// <summary>
    /// Extensions to the umbraco framework.
    /// </summary>
    public static class GuidExtensions
    {

        /// <summary>
        /// Get a node by the unique Guid.  This is needed for sites where courier is in use.
        /// </summary>
        /// <param name="self">Current Page</param>
        /// <param name="guid">Guid to load.</param>
        /// <returns>DynamicNode</returns>
        public static DynamicNode NodeByGuid(this DynamicNode self, string guid)
        {
            return self.NodeByGuid(new Guid(guid));
        }

        /// <summary>
        /// Get a node by the unique Guid.  This is needed for sites where courier is in use.
        /// </summary>
        /// <param name="self">Current Page</param>
        /// <param name="guid">Guid to load.</param>
        /// <returns>DynamicNode</returns>
        public static DynamicNode NodeByGuid(this DynamicNode self, Guid guid)
        {
            return self.NodeById(new CMSNode(guid).Id);
        }

        /// <summary>
        /// Get the unique ID for a selected node.
        /// </summary>
        /// <param name="self">Node</param>
        /// <returns>guid</returns>
        public static string UniqueId(this DynamicNode self)
        {
            return new CMSNode(self.Id).UniqueId.ToString();
        }
    }
}

1 comment:

Unknown said...

I know this an old post but does this still apply to Umbraco 7. I am trying to figure out a way to reference URL links in a navigation bar. What would you suggest?