I have two dropdown list in one of my custom webpart. I want to load all users and groups from an active directory into respective dropdown list on a form. I am making use of SSOM for developing a registration form which includes these two dropdown list. DropdownUSER will load all users from Active Directory and DropdownGroup will load all groups available in that AD.
I have article where I discussed how to get all users under a particular group or OU. Try it out from here
using (var directoryInfo = new DirectoryEntry(SyncPath, UserName, Password))
{
var userFindingfilter = "(&(objectClass=user)(objectCategory=person))";
var userProperties = new string[] { "title", "whenChanged", "displayName", "department", "sAMAccountName", "userPrincipalName", "manager" };
using (var directoryInfoSearch = new DirectorySearcher(directoryInfo, userFindingfilter, userProperties, SearchScope.Subtree))
{
var directoryEntryUserSearchResults = directoryInfoSearch.FindAll();
foreach (SearchResult searchResult in directoryEntryUserSearchResults)
{
var searchResultDirectoryEntry = searchResult.GetDirectoryEntry();
if (searchResultDirectoryEntry.Properties["manager"].Value == null)
continue;
var managerDnName = searchResultDirectoryEntry.Properties["manager"].Value.ToString();
var manager = new DirectoryEntry("LDAP://" + managerDnName);
SaveItemIfNotExists(searchResultDirectoryEntry, manager);
}
}
}
SharePoint SSOM does not have methods like that. You should use System.DirectoryServices
or System.DirectoryServices.AccountManagement
namespaces instead.
You can use the FindAll() method of the PrincipalSearcher Class in the System.DirectoryServices
Here is a sample:
using (var context = new PrincipalContext(ContextType.Domain, "mydomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
DropDownUsers.Items.Add(de.Properties["givenName"].Value + " " + de.Properties["sn"].Value);
}
}
}
givenName will give you the First Name and sn will give you the Last Name