Is it bad that I just acheived inbox-zero by deleting all my emails?

follow me on

An update to my Umbraco helper class

Saturday, March 28, 2009 by David Conlisk

I previously blogged about a simple Umbraco helper class to get Umbraco data into your usercontrols, but since then I've updated it quite a bit. Due to ongoing efforts to package up my code into more easily re-usable chunks, I've created a new class library, WebGarden.Utilities, that I just add to each new project. It gives me access to a number of handy functions, a few of which I'm going to share here (the more general purpose ones).

The way that I get Umbraco information to my user controls is through the use of the web.config file (see my other post for more details), so I'll assume that you understand that method. It means that there is a central location to change each setting, regardless of how many different user controls use those settings. I think this is a little easier to maintain than passing parameters - what if you are passing a settings node parameter to seven different macros in twelve different templates, and for some reason the settings node id changes? With the web.config solution, you only have to update it in one place.

Anyway, I've updated my methods so that if you've forgotten to set your values in the web.config, or if the setting is there but empty or invalid, then you get a nice big exception thrown telling you exactly what the problem is. Remember that this is only supposed to happen during development/testing phase of your project, and its supposed to explicitly tell you the problem so you can fix it quickly. These exceptions should never be thrown once the site is live. So here are my methods hope you find them interesting/thought provoking/useful. As always I'm interested in the best way to do things so if you disagree with my methods or there's a better way please let me know! Also, I'd love to hear if you use the code, or make any modifications, or whatever.

Cheers,

David

P.S. I'm pretty sure there must be a better way to implement GetImageAltText and GetImagePath let me know if you know what that is!

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.cms.businesslogic.web;
using umbraco.presentation.nodeFactory;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.member;
using System.Collections.Specialized;
using System.Xml.XPath;

namespace WebGarden.Utilities
{
    public static class UmbracoHelper
    {
        /// <summary>
        /// Get the name of the specified node
        /// from the Umbraco content section
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static string GetContentNodeName(int nodeId)
        {
            // Get the countries from the Umbraco content - children of the Countries node
            Node n = new Node(nodeId);

            return n.Name;
        }

        public static string GetContentNodeProperty(string appSettingName, string propertyName)
        {
            if (ConfigurationManager.AppSettings[appSettingName] == null)
            {
                throw new Exception(String.Format("The app setting {0} does not exist in the web.config. It should exist and contain the id of an Umbraco node.", appSettingName));
            }

            int nodeId = 0;
            if (!int.TryParse(ConfigurationManager.AppSettings[appSettingName], out nodeId))
            {
                throw new Exception(String.Format("The app setting {0} in the web.config does not contain a valid integer. It should contain the id of an Umbraco node.", appSettingName));
            }

            return GetContentNodeProperty(nodeId, propertyName);
        }

        /// <summary>
        /// Get the value of the named attribute of the specified node
        /// from the Umbraco content section
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static string GetContentNodeProperty(int nodeId, string propertyName)
        {
            // Get the countries from the Umbraco content - children of the Countries node
            Node n = new Node(nodeId);

            if (n == null || n.Id == 0)
            {
                throw new Exception(String.Format("The requested node (id {0}) was not found by WebGarden.Utilities.GetUmbracoContentNodeProperty when looking for the {1} property", nodeId, propertyName));
            }

            if (n.GetProperty(propertyName) == null)
            {
                throw new Exception(String.Format("The property {0} does not exist in the current node {1} (id {2})", propertyName, n.Name, nodeId));
            }
            return n.GetProperty(propertyName).Value;
        }

        /// <summary>
        /// Get the value of the named attribute of the CURRENT node
        /// from the Umbraco content section
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static string GetCurrentNodeProperty(string propertyName)
        {
            return GetContentNodeProperty(Node.GetCurrent().Id, propertyName);
        }

        /// <summary>
        /// Takes the name of an appsetting in the web.config and returns the umbraco nice url to the node
        /// Assumes that the App Setting exists and contains a valid Umbraco node id
        /// </summary>
        /// <param name="appSettingName"></param>
        /// <returns></returns>
        public static string GetNiceUrlFromAppSetting(string appSettingName)
        {
            if (ConfigurationManager.AppSettings[appSettingName] == null)
            {
                throw new Exception(String.Format("The app setting {0} does not exist in the web.config. It should exist and contain the id of an Umbraco node.", appSettingName));
            }

            int nodeId = 0;
            if (!int.TryParse(ConfigurationManager.AppSettings[appSettingName], out nodeId))
            {
                throw new Exception(String.Format("The app setting {0} in the web.config does not contain a valid integer. It should contain the id of an Umbraco node.", appSettingName));
            }

            return umbraco.library.NiceUrl(nodeId);
        }

        /// <summary>
        /// Takes the name of an appsetting in the web.config and returns the umbraco node
        /// Assumes that the App Setting exists and contains a valid Umbraco node id
        /// </summary>
        /// <param name="appSettingName"></param>
        /// <returns></returns>
        public static Node GetNodeFromAppSetting(string appSettingName)
        {
            if (ConfigurationManager.AppSettings[appSettingName] == null)
            {
                throw new Exception(String.Format("The app setting {0} does not exist in the web.config. It should exist and contain the id of an Umbraco node.", appSettingName));
            }

            int nodeId = 0;
            if (!int.TryParse(ConfigurationManager.AppSettings[appSettingName], out nodeId))
            {
                throw new Exception(String.Format("The app setting {0} in the web.config does not contain a valid integer. It should contain the id of an Umbraco node.", appSettingName));
            }

            return new Node(nodeId);
        }

        /// <summary>
        /// Recursive function to find a content node based on a property value
        /// Checks the propertyName property of each node, and if it matches value then returns 
        /// the id of the node
        /// If the node has children, then it recurses the tree until a match is found
        /// Returns -1 if no match is found
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <param name="rootNodeId"></param>
        /// <returns></returns>
        public static int GetNodeIdByProperty(string documentType, string propertyName, string value, int rootNodeId)
        {
            Node n = new Node(rootNodeId);
            int result = -1;

            foreach (Node child in n.Children)
            {
                // If it's a node with the correct documenttype, then check the property value.
                if (child.NodeTypeAlias.ToLower().Equals(documentType.ToLower()))
                {
                    if (child.GetProperty(propertyName).Value.Equals(value))
                    {
                        return child.Id;
                    }
                }
                else
                {
                    // If node has child nodes - recurse over them to find your required node
                    if (child.Children.Count > 0)
                    {
                        result = GetNodeIdByProperty(documentType, propertyName, value, child.Id);
                        if (result != -1)
                        {
                            return result;
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Get the value of the named attribute from the Umbraco settings node
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static string GetSettingsNodeProperty(string propertyName)
        {
            int nodeId = -1;
            if (int.TryParse(ConfigurationManager.AppSettings["UmbracoSettingsNodeId"], out nodeId))
            {
                // Get the named attribute from the Settings node in Umbraco
                Node n = new Node(nodeId);

                if (n.GetProperty(propertyName) == null)
                {
                    throw new Exception(String.Format("A property called {0} was expected in the Umbraco settings node (id: {1}). Note that this is case sensitive.", propertyName, nodeId));
                }
                return n.GetProperty(propertyName).Value;
            }
            else
            {
                throw new Exception("You must enter a valid integer for UmbracoSettingsNodeId in the web.config");
            }
        }

        /// <summary>
        /// Takes the id of an image in the media section of Umbraco and returns the alt text
        /// </summary>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public static string GetImageAltText(int mediaId)
        {
            // Get the path to the image
            XPathNodeIterator xImage = umbraco.library.GetMedia(mediaId, true);
            XPathNodeIterator nodes = xImage.Current.Select("/node/data[@alias='altText']");
            string path = string.Empty;

            while (nodes.MoveNext())
            {
                path = nodes.Current.Value;
                break;
            }
            return path;
        }

        /// <summary>
        /// Takes the id of an image in the media section of Umbraco and returns the path to that image
        /// </summary>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public static string GetImagePath(int mediaId)
        {
            // Get the path to the image
            XPathNodeIterator xImage = umbraco.library.GetMedia(mediaId, true);
            XPathNodeIterator nodes = xImage.Current.Select("/node/data[@alias='umbracoFile']");
            string path = string.Empty;

            while (nodes.MoveNext())
            {
                path = nodes.Current.Value;
                break;
            }
            return path;
        }

        /// <summary>
        /// Takes a list of nodes, a property name and a value, and returns a list of nodes 
        /// where the property value matches the value. Case insensitive.
        /// </summary>
        /// <param name="nodes"></param>
        /// <returns></returns>
        public static List<Node> TrimNodeListByProperty(List<Node> nodes, string propertyName, string value)
        {
            List<Node> results = new List<Node>();

            foreach (Node n in nodes)
            {
                if (n.GetProperty(propertyName).Value.ToLower() == value.ToLower())
                {
                    results.Add(n);
                }
            }

            return results;
        }

        /// <summary>
        /// Returns the children of a node as a list.
        /// The id of the parent node is taken from the named AppSetting in the web.config file
        /// </summary>
        /// <param name="appSettingName">The name of an AppSetting that contains the parent node id</param>
        /// <returns>A List of Nodes</returns>
        public static List<Node> GetNodeChildrenFromAppSetting(string appSettingName)
        {
            int nodeId = -1;
            List<Node> results = new List<Node>();

            if (int.TryParse(ConfigurationManager.AppSettings[appSettingName], out nodeId))
            {
                Node n = new Node(nodeId);

                foreach (Node child in n.Children)
                {
                    results.Add(child);
                }
            }
            else
            {
                throw new Exception(String.Format("You must enter a valid integer for the {0} setting in the web.config", appSettingName));
            }
            return results;
        }     
    }
}
Bookmark and Share

0 comment(s) for “An update to my Umbraco helper class”

Please leave a comment: