Reputation: 6911
I'm new to Umbraco and I like it so far, I understand how it works but I'd like to know how, and what is the best way, to create usercontrols that display some informations from umbraco's DB? When it's simple, I do it with XSL template but now I need more possibilities.
What I try to do is have a UC that connect to Umbraco's DB, fetch all documents of documentType "NewsItem" and list them in my UC.
I found this post : Umbraco: List Child Nodes in User Control but it's not quite it since I don't want to hardcode the nodeId, I want to find my news depending on DocumentType.
I now that there's an API to acces umbraco's data but did not find any exemple. I also watch lots of videos on umbraco.tv but still do not have a good idea of what's the best way to do it. There's also LINQ to Umbraco (http://our.umbraco.org/wiki/reference/api-cheatsheet/linq-to-umbraco) but not sure if it's a good way of doing this.
Also, is there a way to test the Usercontrol inside an other WebProject? What I mean is to connect to Umbraco's db in an other project, so that you don't have to go in umbraco's website to test it?
Thanks a lot!
Upvotes: 2
Views: 2327
Reputation: 4410
There are several areas to your question which I'll try and address one at a time.
Using umbraco.presentation.nodefactory to get Nodes of a specific type. For this example I'm going to assume all your NewsItems are children of a specific node in this case node id 1024.
using umbraco.presentation.nodeFactory;
namespace cogworks.usercontrols
{
public partial class ExampleUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var specificNode = new Node(1024);
var childNodes = specificNode.Children;
foreach(var node in childNodes)
{
if(node.NodeTypeAlias == "NewsItem")
{
//Do something with your NewsItem node!
}
}
}
}
}
This is probably not the most efficient way but is OK as an example.
An example of walking the node tree recursively and adding the found nodes to a list:
public static List<Node> SelectChildrenByNameRecursive(Node node, string docType)
{
var nodes = new List<Node>();
foreach (Node child in node.Children)
{
FindChildrenByDocType(child, docType, ref nodes);
}
return nodes;
}
private static void FindChildrenByDocType(Node node, string docType, ref List<Node> nodes)
{
if (node.NodeTypeAlias == docType)
{
nodes.Add(node);
}
foreach (Node childNode in node.Children)
{
FindChildrenByDocType(childNode, docType, ref nodes);
}
}
Again just example code...
Testing Umbraco, you'll always need to be running in a an instance of Umbraco as nodefactory is an API on top of the in memory content cache.
Further reading
http://blog.hendyracher.co.uk/umbraco-helper-class/
http://our.umbraco.org/wiki/how-tos/useful-helper-extension-methods-(linq-null-safe-access)
Upvotes: 4