2

I need to create a valid jqTree JSON structure from Active Directory OUs. I'm testing with a recursive method (InfoNode) for this, but I can not get it.

The resulting json goes into the string json. The first node to process is the DirectoryEntry parent with the default domain root. The recursive method (InfoNode) gets the current child node, filter by "OU" and creates the JSON properties "label" and "path". Before checks whether this node has more children to write the end of the current JSON item. Finally, if there are more children, run the method (InfoNode) again:

public static DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
public string dom = (string)root.Properties["defaultNamingContext"].Value;

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

void InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');

    if (arr[0] == "OU")
    {
        json += "'children':[{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (nodo.Children == null)
        {
            json += "}]";
        }
        else
        {
            json += ",";
        }              
    }

    if (node.Children != null)
    {
        foreach (DirectoryEntry child in node.Children)
        {
            InfoNode(child);
        }
    }
}

1 Answers1

0

You should provide more detail on what fails with your code.

I'll give a try :-)

You may try to modify your code like below. Not optimal (using startswith before splitting, more string.Format , testing children with startswith before calling the method recursively, would be better), but I guess it should work.

Maybe you will need to load the children from the ldap source as you progress in the tree.

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    json = InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

public string InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');
    var result = string.Empty;

    if (arr[0].Equals("ou",StringComparison.InvariantCultureIgnoreCase))
    {
        result = "'{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (node.Children.Cast<DirectoryEntry>().Any())
        {
            result += String.Format(", children:[{0}]",
                                    String.Join(",\n ",
                                                node.Children.Cast<DirectoryEntry>()
                                                    .Select(InfoNode).Where(s=>!string.IsNullOrEmpty(s))
                                                    .ToArray()));
        }
        result += "}";
    }
    return result;
}
jbl
  • 15,179
  • 3
  • 34
  • 101