Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Umbraco 4.6+ - How to get all nodes by doctype in C#?

Tags:

c#

api

umbraco

Using Umbraco 4.6+, is there a way to retrieve all nodes of a specific doctype in C#? I've been looking in the umbraco.NodeFactory namespace, but haven't found anything of use yet.

like image 674
Jeremy Wiggins Avatar asked Feb 16 '11 16:02

Jeremy Wiggins


4 Answers

I was just doing this today, something like the below code should work (using umbraco.presentation.nodeFactory), call it with a nodeId of -1 to get the root node of the site and let it work it's way down:

private void DoSomethingWithAllNodesByType(int NodeId, string typeName)
{
    var node = new Node(nodeId);
    foreach (Node childNode in node.Children)
    {
        var child = childNode;
        if (child.NodeTypeAlias == typeName)
        {
            //Do something
        }

        if (child.Children.Count > 0)
            GetAllNodesByType(child, typeName);
    }
}
like image 133
sebastiaan Avatar answered Oct 27 '22 14:10

sebastiaan


Supposing you only eventually need a couple of nodes of the particular type, it would be more efficient to use the yield keyword to avoid retrieving more than you have to:

public static IEnumerable<INode> GetDescendants(this INode node)
{
    foreach (INode child in node.ChildrenAsList)
    {
        yield return child;

        foreach (INode grandChild in child.GetDescendants())
        {
            yield return grandChild;
        }
    }
    yield break;
}

So your final call to get nodes by type will be:

new Node(-1).GetDescendants().Where(x => x.NodeTypeAlias == "myNodeType")

So if you only want to get the first five, you can add .Take(5) to the end and you will only recurse through the first 5 results rather than pull out the whole tree.

like image 34
Dave B 84 Avatar answered Oct 27 '22 12:10

Dave B 84


Or a recursive approach:

using umbraco.NodeFactory;

private static List<Node> FindChildren(Node currentNode, Func<Node, bool> predicate)
{
    List<Node> result = new List<Node>();

    var nodes = currentNode
        .Children
        .OfType<Node>()
        .Where(predicate);
    if (nodes.Count() != 0)
        result.AddRange(nodes);

    foreach (var child in currentNode.Children.OfType<Node>())
    {
        nodes = FindChildren(child, predicate);
        if (nodes.Count() != 0)
            result.AddRange(nodes);
    }
    return result;
}

void Example()
{
    var nodes = FindChildren(new Node(-1), t => t.NodeTypeAlias.Equals("myDocType"));
    // Do something...
}
like image 3
Eric Boumendil Avatar answered Oct 27 '22 14:10

Eric Boumendil


If you're just creating a razor scripting file to be used by a macro (Umbraco 4.7+), I found this shorthand particularly useful...

var nodes = new Node(-1).Descendants("DocType").Where("Visible");

Hope this helps somebody!

like image 1
tcmorris Avatar answered Oct 27 '22 13:10

tcmorris