I want to be able to query the active directory give a list of all groups containing certain words like Users or Administrators below is what i've got so far
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.DisplayName = "Administrators";
qbeGroup.DisplayName = "Users";
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
return srch.FindAll().Select(g => g.Name).ToArray();
This code doesn't even seem to filter out the the Group names that is not Administrators or Users. But anyway what I can't figure out is how to query if the group name contains? and not if group name is equal to and how to do this of multiple strings.
I can do the same thing using DirectoryEntry so I put it here for referance
var groups = new List<string>();
var path = string.Format("LDAP://CN=Users,DC=company,DC=com");
var computerEntry = new DirectoryEntry(path);
if (computerEntry != null)
{
using (computerEntry)
{
var userNames =
from DirectoryEntry childEntry
in computerEntry.Children
where childEntry.SchemaClassName == "Group"
select childEntry.Name;
foreach (var name in userNames)
{
if (name.Contains("Administrators") || name.Contains("Users"))
{
groups.Add(name);
}
}
}
}
return groups.ToArray();
I did this by using a foreach loop But the following code still doesn't answer my question on how to do it for Principalsearcher
var groups = new List<string>();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
foreach (var group in srch.FindAll())
{
if (group.Name.Contains("Administrators") || group.Name.Contains("Users"))
{
groups.Add(group.Name);
}
}
return groups.ToArray();
Related
I am trying to get all users from Active Directory using code:
PrincipalContext ad = new PrincipalContext(contextType, adserviceName, adContext, ContextOptions.SimpleBind, username, password);
UserPrincipal u = new UserPrincipal(ad) {Name = "*"};
PrincipalSearcher search = new PrincipalSearcher { QueryFilter = u };
foreach (var principal in search.FindAll())
{
//do something
}
But it returns only first 1000 rows. How I can retrieve All users and without using DirectorySearcher.
Thanks.
I don't think you will be able to do that without using DirectorySearcher.
Code snippet -
// set the PageSize on the underlying DirectorySearcher to get all entries
((DirectorySearcher)search.GetUnderlyingSearcher()).PageSize = 1000;
Also see If an OU contains 3000 users, how to use DirectorySearcher to find all of them?
You need to get the underlying DirectorySearcher and set the PageSize property on it:
using (PrincipalContext ad = new PrincipalContext(contextType, adserviceName, adContext, ContextOptions.SimpleBind, username, password))
{
UserPrincipal u = new UserPrincipal(ad) {Name = "*"};
PrincipalSearcher search = new PrincipalSearcher { QueryFilter = u };
// get the underlying "DirectorySearcher"
DirectorySearcher ds = search.GetUnderlyingSearcher() as DirectorySearcher;
if(ds != null)
{
// set the PageSize, enabling paged searches
ds.PageSize = 500;
}
foreach (var principal in search.FindAll())
{
//do something
}
}
You can:
((DirectorySearcher)myPrincipalSearcher.GetUnderlyingSearcher()).SizeLimit = 20;
We use the secretary property of Active Directory, which is a multivalued DN property. I want to efficiently find all the groups for which a given user is a listed secretary. What is the best way to perform this query in C#/.NET?
This code will return a list of sAMAccountNames of groups in context's OU that include distinguishedName as one of the secretaries listed:
var filter = "(&(objectClass=group)(secretary=" + distinguishedName + "))";
PrincipalContext context = new PrincipalContext(...); // place to search from
var up = new GroupPrincipal(context);
var list = new List<string>();
using (var searcher = new PrincipalSearcher(up))
{
var ds = searcher.GetUnderlyingSearcher() as DirectorySearcher;
// if you only want to search in a single OU (as defined by 'context')
ds.SearchScope = SearchScope.OneLevel;
ds.Filter = filter;
ds.PropertiesToLoad.Add("sAMAccountName");
var results = ds.FindAll();
foreach (SearchResult r in results)
{
var name = r.GetDirectoryEntry().Properties["sAMAccountName"].Value as string;
list.Add(name);
}
}
I have the following code inside my asp.net mvc5 web application:-
List<DomainContext> results = new List<DomainContext>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
{
DomainContext dc = new DomainContext();
dc.DisplayName = p.DisplayName;
dc.UserPrincipalName = p.UserPrincipalName;
dc.Name = p.Name;
dc.SamAccountName = p.SamAccountName ;
dc.DistinguishedName = p.DistinguishedName;
results.Add(dc);
i am able to get these AD info such as Display Name, Name, etc but can i also get these info using the above code:-
email address.
Telephone.
Manager
Thanks?
You need the username, first, last and the smtp.
If you have them, here's the code:
var adService = new DirectorySearcher(new DirectoryEntry());
adService.Filter = "(&(objectClass=user)(anr=LOGON))";
adService.PropertiesToLoad.Add("FirstName");
adService.PropertiesToLoad.Add("LastName");
adService.PropertiesToLoad.Add("SMTP");
return adService.FindOne();
Below I have updated your existing code to use a UserPrincipal.
List<UserPrincipal> results = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
{
UserPrincipal userPrincipal = p as UserPrincipal;
if (userPrincipal != null)
results.Add(userPrincipal);
And here I have added code to show you how to get the additional properties you need at a higher level.
//Get information you need from UserPrincipal..
var matchingUsers = results.Where(p => p.DisplayName.ToLower() == "bob");
foreach (var matchedUser in matchingUsers)
{
string telephone = matchedUser.VoiceTelephoneNumber;
string email = matchedUser.EmailAddress;
var directoryEntry = matchedUser.GetUNderlyingObject() as DirectoryEntry;
string manager = directoryEntry.Properties["manager"] as string;
}
I work with the Active Directory. I write a method how I can get all Users from the Active Directory with a filter and list the Users in a ArrayList for my DropDownList.
The Code:
private ArrayList GetReceiverList(string Domain)
{
ArrayList List = new ArrayList();
DirectoryEntry Entry = new DirectoryEntry(Domain);
string filter = "(&(objectClass=user)(objectCategory=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(sn=*)(|(telephoneNumber=*)(mail=*))(cn=*))";
DirectorySearcher Searcher = new DirectorySearcher(Entry, filter);
foreach (SearchResult usr in Searcher.FindAll())
{
List.Add(GetLdapProperty(usr, "displayName"));
}
return List;
}
This work and I want now do use System.DirectoryServices.AccountManagement and for this I write a Method and this works, too. But I want do use the filter how in my first Method. How I can do this?
the code of my new method:
public static ArrayList GetAllActiveDirectoryUsersByDisplayName(string dc)
{
ArrayList list = new ArrayList();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
UserPrincipal u = new UserPrincipal(ctx);
u.Surname = "*";
PrincipalSearcher ps = new PrincipalSearcher(u);
PrincipalSearchResult<Principal> results = ps.FindAll();
foreach (UserPrincipal usr in results)
{
list.Add(usr.Name);
}
list.Sort();
return list;
}
Update:
I want di use this filter in my new method :
string filter = "(&(objectClass=user)(objectCategory=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(sn=*)(|(telephoneNumber=*)(mail=*))(cn=*))";
I wrote this to get the groups a particular user belongs to:
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntry user = AD.Children.Find(completeUserName, "user");
object obGroups = AD.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
// Create object for each group.
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
listOfMyWindowsGroups.Add(obGpEntry.Name);
}
for (int j = 0; j < listOfMyWindowsGroups.Count; j++)
{
//ex
}
How is it possible to retrieve all the groups in windows and not just for a particular user?
How about setting up a filter for groups and enumerating the results.
Try this filter:
AD.Children.SchemaFilter.Add("group");
Try this one out, it will give you all groups in a specicied OU.
public ArrayList GetGroups()
{
ArrayList myItems = new ArrayList();
// Create the principal context for the group object.
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
// Create the GroupPrincipal object and set the diplay name property.
GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext);
// Create a PrincipalSearcher object.
PrincipalSearcher oPrincipalSearcher = new PrincipalSearcher(oGroupPrincipal);
// Searches for all groups named "Administrators".
PrincipalSearchResult<Principal> oPrincipalSearchResult = oPrincipalSearcher.FindAll();
foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult.Name);
}
return myItems;
}
For a full reference you can check this one out
.Net 3.5 version - > http://anyrest.wordpress.com/2010/06/28/active-directory-c/
Older versions - > http://anyrest.wordpress.com/2010/02/01/active-directory-objects-and-c/