Sunday, December 26, 2010

How to read group membership information from Active Directory

Last post I talked about reading from Active Directory. This post takes it a little further. We gonna read the user list for a specific group from a given domain.

With this group membership list, you can for example



  • add new users to Dynamics Ax according to an AD group (called 'Ax Users' fe)

  • add users from the Administrators group (AD) to the 'Admin' group in Dynamics Ax

Plenty of applications, for which you can use following job as a base. Again we'll use CLR Interop with the System.DirectoryServices namespace.



static void ReadMoreFromAD(Args _args)

{ System.DirectoryServices.DirectorySearcher DirectorySearcher;

System.DirectoryServices.SearchScope SearchScope;

System.DirectoryServices.DirectoryEntry DirectoryEntry;

System.DirectoryServices.SearchResultCollection SearchResultCollection;

System.DirectoryServices.SearchResult SearchResult;

System.DirectoryServices.PropertyCollection PropertyCollection;

System.DirectoryServices.PropertyValueCollection PropertyValueCollection;



str networkDomain="yourdomainnamehere";

str prefix = 'LDAP://';

int totalCount;

int counter;



str groupName="Administrators";

str groupCrit;



int usercount;

int ucount;

str userinfo;


;

try

{

DirectoryEntry = new System.DirectoryServices.DirectoryEntry(prefix + networkDomain);

SearchScope =CLRInterop::parseClrEnum('System.DirectoryServices.SearchScope', 'Subtree');



DirectorySearcher = new System.DirectoryServices.DirectorySearcher(DirectoryEntry);

DirectorySearcher.set_SearchScope(searchScope);

groupCrit = strfmt('(samaccountname=%1)', groupName) ;

DirectorySearcher.set_Filter(strfmt('(&(objectClass=group)%1)', groupCrit));



SearchResultCollection = DirectorySearcher.FindAll();

totalCount = SearchResultCollection.get_Count();

for (counter=0; counter < totalcount; counter++)
{
SearchResult = SearchResultCollection.get_Item(counter);
DirectoryEntry = SearchResult.GetDirectoryEntry();
if (DirectoryEntry)
{
PropertyCollection = DirectoryEntry.get_Properties();
if (PropertyCollection)
{
PropertyValueCollection = propertyCollection.get_Item('member');
usercount = PropertyValueCollection.get_Count();

for (ucount=0; ucount < usercount; ucount++)
{
userinfo = PropertyValueCollection.get_Item(ucount);
if(userinfo)
info(userinfo);
}
}
}
}

DirectorySearcher.Dispose();
SearchResultCollection.Dispose();

} catch (Exception::CLRError)
{
error("Error reading AD");
return;
}
}

No comments:

Post a Comment