I'm writing an application that needs to know if anything on the users active directory object (eg group membership) has altered since the last time the app was ran.
I was looking at the whenChanged attribute but that appears only to change if the user changes their password. I just need something i can hold in my config file, and check that value in active directory the next time the app is ran.
Anyone know of anything i can reliably use?
Cheers
Luke
Given that you are primarily concerned with groups, I think you'll have to create a hash - modifying group membership won't affect the user object.
Here's a quick example I've knocked up.
public static string HashGroups(string user)
{
DirectoryEntry directoryEntry = default(DirectoryEntry);
DirectorySearcher dirSearcher = default(DirectorySearcher);
List<string> result = new List<string>();
directoryEntry = new DirectoryEntry("LDAP://<YOUR_DOMAIN>");
directoryEntry.RefreshCache();
// Get search object, specify filter and scope,
// perform search.
dirSearcher = new DirectorySearcher(directoryEntry);
dirSearcher.PropertiesToLoad.Add("memberOf");
dirSearcher.Filter = "(&(sAMAccountName=" + user + "))";
SearchResult sr = dirSearcher.FindOne();
// Enumerate groups
foreach (string group in sr.Properties["memberOf"])
{
result.Add(group);
}
// OrderBy is important! Otherwise, your hash might fail because
// the groups come back in different order.
MD5 md5 = MD5.Create();
Byte[] inputBytes = Encoding.ASCII.GetBytes(result.OrderBy(s1 => s1).SelectMany(s2 => s2).ToArray());
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
PREVIOUS (rubbish) ANSWER
According to the docs, the Modify-Time-Stamp attribute is "A computed attribute representing the date when this object was last changed." which sounds like what you want. It's available in all versions back to 2000.
EDIT It looks like this is computed from whenChanged, so if that is not working for you then this may not.
You could always check the Directory's properties for last write or modification time and maybe keep some XML or some data that keeps track of last write times of files.
Related
I need to get a list of users from Active directory whose passwords are expiring soon (say in 5 days).
I need to do this by adding a filter to the DirectorySearcher as it will be fastest. I have added the samaccountname pattern to the filter but I can't figure out how to add pwdLastSet to it. Ideally the filter would reduce the user list to only those who fulfill the password expiration criteria.
using (DirectoryEntry searchRoot = GetXYZAccountOU())
{
DirectorySearcher ds = new DirectorySearcher(searchRoot);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = "(&" +
"(samaccountname=XYZ*)"
+ ")";
SearchResultCollection result = ds.FindAll();
foreach (SearchResult searchResult in result)
{
var de = searchResult.GetDirectoryEntry();
//long pwdLastSetVal = (long)de.Properties["pwdLastSet"][0];
//Console.WriteLine(de.Properties["displayName"].Value + ": " + DateTime.FromFileTimeUtc(pwdLastSetVal));
Console.WriteLine(de.Properties["displayName"].Value);
}
Console.Read();
}
Here XYZ is the starting letters of my users' samaccountname.
If I run this code I can get the displayName and some other attributes but not the pwdLastSet or the computed attribute msDS-UserPasswordExpiryTimeComputed while I can see both of them in the Active directory browser.
You have to know in advance how long passwords are valid for, and query the pwdLastSet attribute. But of course the date is stored in a weird format.
Let's assume they're valid for 30 days. Then you can construct the query like this:
var date = DateTime.Now.AddDays(-30).ToFileTime();
var query = $"(&(objectclass=user)(objectcategory=person)(!pwdlastset=0)(pwdlastset<={date})(!userAccountControl:1.2.840.113556.1.4.803:=65536))";
Accounts can be set to never expire passwords, so you have to account for that in your query. The userAccountControl condition does that.
If you don't want to use a magic number in your code, you can look up how long passwords are valid for on the domain by looking at the maxPwdAge attribute at the root of the domain (which is stored in a different, weird format):
var domain = new DirectoryEntry("LDAP://domain.com");
Int64 pwdAge = (Int64) domain.Properties["maxPwdAge"][0];
var maxPwdAge = pwdAge / -864000000000; //convert to days
I have the following code to search the global address book by a certain string:
"CONF"
var esb = new ExchangeServiceBinding();
esb.Url = #"https://myurl.com/EWS/Exchange.asmx";
esb.Credentials = new NetworkCredential(_user,_pwd, _domain);
var rnType = new ResolveNamesType {ReturnFullContactData = true, UnresolvedEntry = "CONF"};
ResolveNamesResponseType response = esb.ResolveNames(rnType);
ArrayOfResponseMessagesType responses = resolveNamesResponse.ResponseMessages;
var responseMessage = responses.Items[0] as ResolveNamesResponseMessageType;
ResolutionType[] resolutions = responseMessage.ResolutionSet.Resolution;
the issue is that it seems to be doing a "starts with" search so I have a name called:
"CONF-123" it will show up but if i have a name "JOE-CONF" then it will not.
How can I do a partial string search on this line
var rnType = new ResolveNamesType {ReturnFullContactData = true, UnresolvedEntry = "CONF-"};
i was hoping there was something like:
var rnType = new ResolveNamesType {ReturnFullContactData = true, UnresolvedEntry = "%CONF-%"};
but that doesn't seem to work.
EDIT: Jan 4,2016 - Added sample code for searching AD.
What won't work
Searching the GAL via ResolveNames always uses prefix-string match for Ambiguous Name Resolution (ARN). Although EWS documentation does not say this explicitly, the Exchange ActiveSync documentation does. EWS and Exchange ActiveSync are just protocols; they both rely on ARN underneath, so you are stuck with prefix match, whether you use ActiveSync protocol or EWS.
Here is the relevant quote from Exchange ActiveSync documentation (https://msdn.microsoft.com/en-us/library/ee159743%28v=exchg.80%29.aspx)
The text query string that is provided to the Search command is used
in a prefix-string match
.
What will work
The best thing to do depends on your use case, but here are some ideas:
Search Active Directory in your client program (the program that contains the code you showed in your question)
Set up your own service to search the GAL. Your client program would connect both to Exchange and to your service. Or your service could proxy EWS, so that the client program needs to connect only to your service.
How would you service get the GAL data? One way would be to use EWS ResolveNames repeatedly, to get the GAL data, 100 entries at a time and cache this data in your service. First, retrieve all the "a"s, then all the "b"s, etc. Of course, there can be more than 100 "a"s in the GAL, so just getting all the "a"s could take multiple searches - you would construct your next search string, based on the last entry returned from each search. This can be slow and painful. You would probably want to cache this data in a database and refresh it periodically.
You can also get to GAL through MAPI. You can use MAPI directly (https://msdn.microsoft.com/en-us/library/cc765775%28v=office.12%29.aspx) or through a helper library like Redemption (http://www.dimastr.com/redemption/home.htm). Whether you use MAPI directly or through Redemption, you will need to install Outlook (or Exchange) on the computer where your code is running. Because of this restriction, it may be best to not use MAPI in your client program, but to stick it in a service running on some server and have your client program connect to that service.
AD Code Sample
Another answer provided sample code to search Active Directory. I am adding a code sample that may be better suited for generic use by people who may find this question through search. Compared to the other sample, the code below has the following improvements:
If the search string contains any special characters (like parenthesis), they are escaped, so that the constructed filter string is valid.
Searching by just samaccountname many not be sufficient. If "David Smith" has account name "dsmith", searching for "David" by samaccountname would not find him. My sample shows how to search by more fields and gives some of the fields one may want to search.
Starting at a root like "GC:" is more robust than trying to construct an LDAP entry from Domain.GetComputerDomain().
All IDisposables must be disposed of (usually by using them in a using construct).
// Search Active Directory users.
public static IEnumerable<DirectoryEntry> SearchADUsers(string search) {
// Escape special characters in the search string.
string escapedSearch = search.Replace("*", "\\2a").Replace("(", "\\28")
.Replace(")", "\\29").Replace("/", "\\2f").Replace("\\", "\\5c");
// Find entries where search string appears in ANY of the following fields
// (you can add or remove fields to suit your needs).
// The '|' characters near the start of the expression means "any".
string searchPropertiesExpression = string.Format(
"(|(sn=*{0}*)(givenName=*{0}*)(cn=*{0}*)(dn=*{0}*)(samaccountname=*{0}*))",
escapedSearch);
// Only want users
string filter = "(&(objectCategory=Person)(" + searchPropertiesExpression + "))";
using (DirectoryEntry gc = new DirectoryEntry("GC:")) {
foreach (DirectoryEntry root in gc.Children) {
try {
using (DirectorySearcher s = new DirectorySearcher(root, filter)) {
s.ReferralChasing = ReferralChasingOption.All;
SearchResultCollection results = s.FindAll();
foreach (SearchResult result in results) {
using (DirectoryEntry de = result.GetDirectoryEntry()) {
yield return de;
}
}
}
} finally {
root.Dispose();
}
}
}
}
Though wildcard search isn't possible in EWS, it is possible in AD search. AD Queries support wildcards. i.e., *CONF* can be searched in AD, which will return all results which contain "CONF". Based on the results, query EWS for an corresponding Exchange Object. You need to find a parameter with which you can find the corresponding EWS entry. I guess email address (username) should be sufficient to find the corresponding exchange object.
AD Search code snippet...
private SearchResultCollection SearchByName(string username, string password, string searchKeyword)
{
DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry("LDAP://" + Domain.GetComputerDomain().ToString().ToLower(), username, password));
ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=*" + searchKeyword + "*))";
ds.SearchScope = SearchScope.Subtree;
ds.ServerTimeLimit = TimeSpan.FromSeconds(90);
return ds.FindAll();
}
AD Query Example here.
An ambiguous search on an indexed text field can only be done with prefix (or suffix...). That's why Exchange probably implements the query as LIKE 'CONF%'.
I've looked over the documentation and there isn't any way you can bypass it - full table scan (which would have to be the case for %CONF%) does not seem to make sense.
I have also been trying to search the GAL from PHP using php-ews. On a web page the user starts to enter the name to be searched, once 2 chars have been entered a call to read_contacts.php is made passing the 2 chars entered. read_contacts.php uses EWS ResolveNames request to retrieve a limited list of contacts. The code then filters on some criteria and also checks that the displayName starts with the chars entered. This then returns the filtered list:
<?php
$staffName = $_GET['q'];
require_once './php-ews/EWSType.php';
require_once './php-ews/ExchangeWebServices.php';
require_once 'php-ews/EWSType/RestrictionType.php';
require_once 'php-ews/EWSType/ContainsExpressionType.php';
require_once 'php-ews/EWSType/PathToUnindexedFieldType.php';
require_once 'php-ews/EWSType/ConstantValueType.php';
require_once 'php-ews/EWSType/ContainmentModeType.php';
require_once 'php-ews/EWSType/ResolveNamesType.php';
require_once 'php-ews/EWSType/ResolveNamesSearchScopeType.php';
require_once 'php-ews/NTLMSoapClient.php';
require_once 'php-ews/NTLMSoapClient/Exchange.php';
$host = '[exchange server]';
$user = '[exchange user]';
$password = '[exchange password]';
$ews = new ExchangeWebServices($host, $user, $password);
$request = new EWSType_ResolveNamesType();
$request->ReturnFullContactData = true;
$request->UnresolvedEntry = $staffName;
$displayName = '';
$i = 0;
$staff_members = false;
$response = $ews->ResolveNames($request);
if ($response->ResponseMessages->ResolveNamesResponseMessage->ResponseClass == 'Error' && $response->ResponseMessages->ResolveNamesResponseMessage->MessageText == 'No results were found.') {
}
else {
$numNamesFound = $response->ResponseMessages->ResolveNamesResponseMessage->ResolutionSet->TotalItemsInView;
$i2=0;
for ($i=0;$i<$numNamesFound;$i++) {
if ($numNamesFound == 1) {
$displayName = $response->ResponseMessages->ResolveNamesResponseMessage->ResolutionSet->Resolution->Contact->DisplayName;
}
else {
$displayName = $response->ResponseMessages->ResolveNamesResponseMessage->ResolutionSet->Resolution[$i]->Contact->DisplayName;
}
echo "DisplayName: " . $displayName . "\n";
if (stripos($displayName, 'External') == true) {
}
else {
$searchLen = strlen($staffName);
if (strcasecmp(substr($displayName, 0, $searchLen), $staffName) == 0) {
if ($numNamesFound == 1) {
$emailAddress = $response->ResponseMessages->ResolveNamesResponseMessage->ResolutionSet->Resolution->Mailbox->EmailAddress;
}
else {
$emailAddress = $response->ResponseMessages->ResolveNamesResponseMessage->ResolutionSet->Resolution[$i]->Mailbox->EmailAddress;
}
$staff_members[$i2] = array( 'name' => $displayName,'email' => $emailAddress );
$i2++;
}
}
}
$staffJson = json_encode($staff_members);
echo $staffJson;
}
Most of the time this seems to work, ie: 'mi', 'jo' returns Mike, Michael, or Joe, John, except when I sent 'Si' or 'si', for Simon, then the ResolveNames call returns the first 100 entries from the GAL.
For the time being I have increased the minimum number of characters to be entered to 3, ie: 'sim' and this works. The problem will be when we get staff with only 2 character first names.
I just thought I would share the code to see if it helps and to see if anyone knows why my 'si' does not work properly.
I am accessing Exchange 2010
I would like to get all users with their attributes from active directory
I checked many topics includes Linq to LDAP + enter link description here
But all seems to be complicated.
I started with this:
public SearchResultCollection GetAllUsrs()
{
var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x.y.com", "DC=x,DC=y,DC=com"));
var searcher = new DirectorySearcher(dirEntry)
searcher.Filter = "(&(&(objectClass=user)(objectClass=person)))";
searcher.PageSize = 999;
return searcher.FindAll();
}
How can i use pagging since the active directory will only return 1000 record at the time
+ how can i specify the attribute?
Problem:
I want to query a domain that contain up to 60 K users with console application
I want to specify the attribute
Performance is very important.
Can you please guide me to the best way to achieve this?
Paging is not required. AD will return more than 1000 objects. Leave PageSize at 0 and set SizeLimit as required. Use int.MaxValue ;) if you're unsure.
Here's how you can do it with LINQ to LDAP:
using (var connection = new LdapConnection("x.y.com"))
{
using (var context = new DirectoryContext(connection))
{
List<IDirectoryAttributes> users = context
.Query("DC=x,DC=y,DC=com")
.Where("(&(objectClass=user)(objectClass=person))")
.InPagesOf(1000);
}
}
I am unable to display some users from LDAP. I dont know why. Here's my code
try
{
string path = "LDAP://" + Program.domain;
DirectoryEntry dEntry = new DirectoryEntry(path);
DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
dSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
//perform search on active directory
sResults = dSearcher.FindAll();
//loop through results of search
foreach (SearchResult searchResult in sResults)
{
//string view = searchResult.Properties["samaccountname"][0].ToString();
// Console.WriteLine(searchResult.Properties["userprincipalname"][0].ToString());
if (searchResult.Properties["samaccountname"][0].ToString() == Program.username)
{
Console.WriteLine("**********UserDetails******************");
foreach (Object propertyName in searchResult.Properties.PropertyNames)
{
ResultPropertyValueCollection valueCollection =
searchResult.Properties[(string)propertyName];
foreach (Object propertyvalue in valueCollection)
{
Console.WriteLine((string)propertyName + " : " + propertyvalue);
result = true;
}
}
Console.WriteLine("************************************");
}
}
This displays few users but few other users who exist in AD are not displayed.
They're also Domain Admins and Domain users. I don't see any permission issues too yet...
I seriously need some help.Can someone help me please?
Thanks
There are two likely causes:
0) Access control: You do not have the appropriate level of access to view the objects in question (or the properties required to match them in the filter (be it objectClass or objectCategory)).
1) The target objects in question do not actually match the filter specified. Users can be something other than (&(objectClass=user)(objectCategory=person)).
My suggestion is to approach the problem as follows:
0) Take one sample user that you expect to match and inspect it carefully. Check to ensure that objectClass does in fact contain user and objectCategory is set to person. If not, modify your query to be inclusive of all of the users you are trying to find. (You can consult the AD schema to see the relationship between these things)
1) Make sure the context under which you're doing the query has access to all of the objects you want to find including the attributes that you're using in your filter. AD won't return a match to a query if you don't have access to all of the attributes in the filter...if it did, it'd be a form of information disclosure.
I am looking to get a list of all of the groups that a user is a member of in Active Directory, both explicitly listed in the memberOf property list as well as implicitly through nested group membership. For example, if I examine UserA and UserA is a part of GroupA and GroupB, I also want to list GroupC if GroupB is a member of GroupC.
To give you a bit more insight into my application, I will be doing this on a limited basis. Basically, I want a security check occasionally that will list these additional memberships. I will want to differentiate the two but that shouldn't be hard.
My problem is that I have not found an efficient way to make this query work. The standard text on Active Directory (This CodeProject Article) shows a way to do this that is basically a recursive lookup. That seems terribly inefficient. Even in my small domain, a user might have 30+ group memberships. That means 30+ calls to Active Directory for one user.
I've looked into the following LDAP code to get all of the memberOf entries at once:
(memberOf:1.2.840.113556.1.4.1941:={0})
where {0} would be my LDAP path (ex: CN=UserA,OU=Users,DC=foo,DC=org). However, it does not return any records. The downside of this method, even if it worked, would be that I wouldn't know which group was explicit and which was implicit.
That is what I have so far. I would like to know if there is a better way than the CodeProject article and, if so, how that could be accomplished (actual code would be wonderful). I am using .NET 4.0 and C#. My Active Directory is at a Windows 2008 functional level (it isn't R2 yet).
Thirst thanks for this an interesting question.
Next, just a correction, you say :
I've looked into the following LDAP code to get all of the memberOf entries at once:
(memberOf:1.2.840.113556.1.4.1941:={0})
You don't make it work. I remember I make it work when I learnt about its existence, but it was in an LDIFDE.EXE filter. So I apply it to ADSI in C# and it's still working. There were too much parenthesis in the sample I took from Microsoft, but it was working (source in AD Search Filter Syntax).
According to your remark concerning the fact that we don't know if a user explicitly belongs to the group I add one more request. I know this is not very good, but it's the best I'am abable to do.
static void Main(string[] args)
{
/* Connection to Active Directory
*/
DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr");
/* To find all the groups that "user1" is a member of :
* Set the base to the groups container DN; for example root DN (dc=dom,dc=fr)
* Set the scope to subtree
* Use the following filter :
* (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)
*/
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");
SearchResultCollection srcGroups = dsLookFor.FindAll();
/* Just to know if user is explicitly in group
*/
foreach (SearchResult srcGroup in srcGroups)
{
Console.WriteLine("{0}", srcGroup.Path);
foreach (string property in srcGroup.Properties.PropertyNames)
{
Console.WriteLine("\t{0} : {1} ", property, srcGroup.Properties[property][0]);
}
DirectoryEntry aGroup = new DirectoryEntry(srcGroup.Path);
DirectorySearcher dsLookForAMermber = new DirectorySearcher(aGroup);
dsLookForAMermber.Filter = "(member=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
dsLookForAMermber.SearchScope = SearchScope.Base;
dsLookForAMermber.PropertiesToLoad.Add("cn");
SearchResultCollection memberInGroup = dsLookForAMermber.FindAll();
Console.WriteLine("Find the user {0}", memberInGroup.Count);
}
Console.ReadLine();
}
In my test tree this give :
LDAP://WM2008R2ENT:389/CN=MonGrpSec,OU=MonOu,DC=dom,DC=fr
adspath : LDAP://WM2008R2ENT:389/CN=MonGrpSec,OU=MonOu,DC=dom,DC=fr
cn : MonGrpSec
Find the user 1
LDAP://WM2008R2ENT:389/CN=MonGrpDis,OU=ForUser1,DC=dom,DC=fr
adspath : LDAP://WM2008R2ENT:389/CN=MonGrpDis,OU=ForUser1,DC=dom,DC=fr
cn : MonGrpDis
Find the user 1
LDAP://WM2008R2ENT:389/CN=MonGrpPlusSec,OU=ForUser1,DC=dom,DC=fr
adspath : LDAP://WM2008R2ENT:389/CN=MonGrpPlusSec,OU=ForUser1,DC=dom,DC=fr
cn : MonGrpPlusSec
Find the user 0
LDAP://WM2008R2ENT:389/CN=MonGrpPlusSecUniv,OU=ForUser1,DC=dom,DC=fr
adspath : LDAP://WM2008R2ENT:389/CN=MonGrpPlusSecUniv,OU=ForUser1,DC=dom,DC=fr
cn : MonGrpPlusSecUniv
Find the user 0
(edited)
'1.2.840.113556.1.4.1941' is not working in W2K3 SP1, it begins to work with SP2. I presume it's the same with W2K3 R2. It's supposed to work on W2K8. I test here with W2K8R2. I'll soon be able to test this on W2K8.
If there is no way other than recursive calls (and I don't believe there is) then at least you can let the framework do the work for you: see the UserPrincipal.GetAuthorizationGroups method (in the System.DirectoryServices.AccountManagement namespace and introduced in .Net 3.5)
This method searches all groups
recursively and returns the groups in
which the user is a member. The
returned set may also include
additional groups that system would
consider the user a member of for
authorization purposes.
Compare with the results of GetGroups ("Returns a collection of group objects that specify the groups of which the current principal is a member") to see whether the membership is explicit or implicit.
Use the ldap filter recursively but query for all groups returned after each query to reduce the number of round trips.
Ex:
Get all groups where user is a member
Get all groups where Step 1 Groups are members
Get all groups where Step 2 Groups are members
...
In my experience there are rarely more then 5 but should definitiely be much less then 30.
Also:
Make sure to only pull the properties
you are going to need back.
Caching results can significantly aid
performance but made my code much
more complicated.
Make sure to utilize connection pooling.
Primary group has to be handled seperately
you can utilize the tokenGroups and tokenGroupsGlobalAndUniversal properties if you are on Exchange server.
tokenGroups will give you all the security groups this user belongs to, including nested groups and domain users, users, etc
tokenGroupsGlobalAndUniversal will include everything from tokenGroups AND distribution groups
private void DoWorkWithUserGroups(string domain, string user)
{
var groupType = "tokenGroupsGlobalAndUniversal"; // use tokenGroups for only security groups
using (var userContext = new PrincipalContext(ContextType.Domain, domain))
{
using (var identity = UserPrincipal.FindByIdentity(userContext, IdentityType.SamAccountName, user))
{
if (identity == null)
return;
var userEntry = identity.GetUnderlyingObject() as DirectoryEntry;
userEntry.RefreshCache(new[] { groupType });
var sids = from byte[] sid in userEntry.Properties[groupType]
select new SecurityIdentifier(sid, 0);
foreach (var sid in sids)
{
using(var groupIdentity = GroupPrincipal.FindByIdentity(userContext, IdentityType.Sid, sid.ToString()))
{
if(groupIdentity == null)
continue; // this group is not in the domain, probably from sidhistory
// extract the info you want from the group
}
}
}
}
}
If you are using .NET 3.5 or higher you can use the System.DirectoryServices.AccountManagement namespace which really makes this easy.
See the related answer here: Active Directory nested groups
static List<SearchResult> ad_find_all_members(string a_sSearchRoot, string a_sGroupDN, string[] a_asPropsToLoad)
{
using (DirectoryEntry de = new DirectoryEntry(a_sSearchRoot))
return ad_find_all_members(de, a_sGroupDN, a_asPropsToLoad);
}
static List<SearchResult> ad_find_all_members(DirectoryEntry a_SearchRoot, string a_sGroupDN, string[] a_asPropsToLoad)
{
string sDN = "distinguishedName";
string sOC = "objectClass";
string sOC_GROUP = "group";
string[] asPropsToLoad = a_asPropsToLoad;
Array.Sort<string>(asPropsToLoad);
if (Array.BinarySearch<string>(asPropsToLoad, sDN) < 0)
{
Array.Resize<string>(ref asPropsToLoad, asPropsToLoad.Length+1);
asPropsToLoad[asPropsToLoad.Length-1] = sDN;
}
if (Array.BinarySearch<string>(asPropsToLoad, sOC) < 0)
{
Array.Resize<string>(ref asPropsToLoad, asPropsToLoad.Length+1);
asPropsToLoad[asPropsToLoad.Length-1] = sOC;
}
List<SearchResult> lsr = new List<SearchResult>();
using (DirectorySearcher ds = new DirectorySearcher(a_SearchRoot))
{
ds.Filter = "(&(|(objectClass=group)(objectClass=user))(memberOf=" + a_sGroupDN + "))";
ds.PropertiesToLoad.Clear();
ds.PropertiesToLoad.AddRange(asPropsToLoad);
ds.PageSize = 1000;
ds.SizeLimit = 0;
foreach (SearchResult sr in ds.FindAll())
lsr.Add(sr);
}
for(int i=0;i<lsr.Count;i++)
if (lsr[i].Properties.Contains(sOC) && lsr[i].Properties[sOC].Contains(sOC_GROUP))
lsr.AddRange(ad_find_all_members(a_SearchRoot, (string)lsr[i].Properties[sDN][0], asPropsToLoad));
return lsr;
}
static void Main(string[] args)
{
foreach (var sr in ad_find_all_members("LDAP://DC=your-domain,DC=com", "CN=your-group-name,OU=your-group-ou,DC=your-domain,DC=com", new string[] { "sAMAccountName" }))
Console.WriteLine((string)sr.Properties["distinguishedName"][0] + " : " + (string)sr.Properties["sAMAccountName"][0]);
}