//Gets the top OU from the Domain public static OrganizationalUnit GetRoot(Connection connection) { DirectoryEntry entry = new DirectoryEntry("LDAP://" + connection.Credentials.Domain, connection.Credentials.UserName, connection.Credentials.Password); OrganizationalUnit ou = GetDirectory(null, entry); return(ou); }
//Fills the tree-view with the directory items recursively private void GetView(OrganizationalUnit directory, TreeNodeCollection parentNode) { foreach (DirectoryEntity entity in directory.entries) { string prefix = ""; int imageIndex = 0; //Icon if (entity.GetType() == typeof(OrganizationalUnit)) { prefix = "OU"; imageIndex = 0; } else if (entity.GetType() == typeof(Group)) { prefix = "Group"; imageIndex = 1; } else if (entity.GetType() == typeof(User)) { prefix = "User"; imageIndex = 2; } TreeNode node = parentNode.Add(prefix + " - " + entity.Name); node.ImageIndex = imageIndex; node.SelectedImageIndex = imageIndex; node.Tag = entity; if (entity.GetType() == typeof(OrganizationalUnit)) { GetView((OrganizationalUnit)entity, node.Nodes); } } }
//Fills the tree-view with the directory items recursively and allows search private void GetView(string search, OrganizationalUnit directory, TreeNodeCollection parentNode) { string comboText = comboBox1.Text.ToLower(); foreach (DirectoryEntity entity in directory.entries) { string prefix = ""; int imageIndex = 0; //Icon if (entity.GetType() == typeof(OrganizationalUnit)) { prefix = "OU"; imageIndex = 0; } else if (entity.GetType() == typeof(Group)) { prefix = "Group"; imageIndex = 1; } else if (entity.GetType() == typeof(User)) { prefix = "User"; imageIndex = 2; } bool isProperGroup = false; if (comboText.Equals("all")) { isProperGroup = true; } else { if (comboText.Substring(0, comboText.Length - 1).Equals(prefix.ToLower())) { isProperGroup = true; } } if (entity.Name.ToLower().Contains(search) && isProperGroup) { TreeNode node = parentNode.Add(prefix + " - " + entity.Name); node.ImageIndex = imageIndex; node.SelectedImageIndex = imageIndex; node.Tag = entity; } if (entity.GetType() == typeof(OrganizationalUnit)) { GetView(search, (OrganizationalUnit)entity, parentNode); } } }
/*Iterates over the whole Active Directory starting from the parent and loops recursively. * It initializes an OU and adds users/groups/OU*/ private static OrganizationalUnit GetDirectory(OrganizationalUnit parentEntity, DirectoryEntry parent) { OrganizationalUnit ou = new OrganizationalUnit(parentEntity, parent.Properties); foreach (DirectoryEntry entry in parent.Children) { string name = parent.Properties["name"][0].ToString(); string typeName = entry.SchemaEntry.Name; if (typeName.StartsWith("group")) { ou.entries.Add(new Group(ou, entry.Properties)); } else if (typeName.StartsWith("user")) { ou.entries.Add(new User(ou, entry.Properties)); } else if (typeName.StartsWith("organization")) { ou.entries.Add(GetDirectory(new OrganizationalUnit(ou, entry.Properties), entry)); } } return(ou); }