How to get foreignSecurityPrincipal from group. using DirectorySearcher
- by kain64b
What I tested with 0 results:
string queryForeignSecurityPrincipal = "(&(objectClass=foreignSecurityPrincipal)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))";
sidsForeign = GetUsersSidsByQuery(groupName,
string.Format(queryForeignSecurityPrincipal, groupPrincipal.DistinguishedName, 0, 0));
public IList<SecurityIdentifier> GetUsersSidsByQuery(string groupName, string query)
{
List<SecurityIdentifier> results = new List<SecurityIdentifier>();
try{
using (var context = new PrincipalContext(ContextType.Domain, DomainName, User, Password))
{
using (var groupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName,
groupName))
{
DirectoryEntry directoryEntry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();
do
{
directoryEntry = directoryEntry.Parent;
}
while (directoryEntry.SchemaClassName != "domainDNS");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry){
SearchScope=System.DirectoryServices.SearchScope.Subtree,
Filter=query,
PageSize=10000,
SizeLimit = 15000
};
searcher.PropertiesToLoad.Add("objectSid");
searcher.PropertiesToLoad.Add("distinguishedname");
using (SearchResultCollection result = searcher.FindAll())
{
foreach (var obj in result)
{
if (obj != null)
{
var valueProp = ((SearchResult)obj).Properties["objectSid"];
foreach (var atributeValue in valueProp)
{
SecurityIdentifier value = (new SecurityIdentifier((byte[])atributeValue, 0));
results.Add(value);
}
}
}
}
}
}
}
catch (Exception e)
{
WriteSystemError(e);
}
return results;
}
I tested it on usual users with query:
"(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))" and it is work,
I test with objectClass=* ... nothing help... But If I call groupPrincipal.GetMembers,I get all foreing user account from group. BUT groupPrincipal.GetMembers HAS MEMORY LEAK.
Any Idea how to fix my query????