Wednesday, March 26, 2014

X++ code to read the data from Active Directory in AX 2012

static void ReadingDataFromActiveDirectory(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="bosco.com";
str prefix = 'LDAP://';

int totalCount;
int counter;

str mysamaccountname;
str myusername;
str myMobileNum;
;

try
{
SearchScope = CLRInterop::parseClrEnum('System.DirectoryServices.SearchScope', 'Subtree');
DirectoryEntry = new System.DirectoryServices.DirectoryEntry(prefix + networkDomain);


DirectorySearcher = new System.DirectoryServices.DirectorySearcher(DirectoryEntry);
DirectorySearcher.set_PageSize(65535);
DirectorySearcher.set_CacheResults(false);
DirectorySearcher.set_SearchScope(searchScope);
DirectorySearcher.set_Filter(strfmt('(&(objectClass=user))'));

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('samaccountname');
mysamaccountname=PropertyValueCollection.get_Value();

PropertyValueCollection = PropertyCollection.get_Item('name');
myusername=PropertyValueCollection.get_Value();
 
PropertyValueCollection = PropertyCollection.get_Item('Mobile');
if(PropertyValueCollection.get_Value())
{
          myMobileNum=PropertyValueCollection.get_Value();
}
else
{
         myMobileNum= "";
}

info(strfmt('%1 - %2 -%3',mysamaccountname,myusername,myMobileNum));
}
}
}

DirectorySearcher.Dispose();
SearchResultCollection.Dispose();
}
catch (Exception::CLRError)
{
error("Error reading AD");
return;
}

}



You may get error while trying to access Active Directory on the below line

searchResultCollection = directorySearcher.FindAll();

Kindly check the AOS instance (In service) whether its running under a Network Service Account, which did not have all the permissions to deal with the Active Directory.

To resolve this issue kindly change the login method of your service to use the local service instead of the Network Service.

No comments:

Post a Comment