Wednesday 6 January 2016

Read AD user infromation from X++

private void readCompanyInfo(NetworkAlias _alias)


 {
 InteropPermission interopPermission;
 System.DirectoryServices.DirectorySearcher directorySearcher;
 System.DirectoryServices.DirectoryEntry entry;
 System.DirectoryServices.SearchResultCollection searchResultCollection;
 System.DirectoryServices.SearchScope searchScope;
 System.DirectoryServices.SearchResult searchResult;
 System.DirectoryServices.PropertyCollection propertyCollection;
 System.DirectoryServices.PropertyValueCollection propertyValueCollection;
 str searchCriteria;

int searchCount, i, length;


 ;
 /// Search Active Directory for User details

 interopPermission = new InteropPermission(InteropKind::ClrInterop);


 interopPermission.assert();
 
 try


 {
 searchScope = System.DirectoryServices.SearchScope::Subtree;
 entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + "WIN2012SERVER"); // Change to yours

 directorySearcher = new System.DirectoryServices.DirectorySearcher(entry);

 directorySearcher.set_PageSize(65535);

 directorySearcher.set_CacheResults(false);


 directorySearcher.set_SearchScope(searchScope);
 searchCriteria = strFmt("(samaccountname=%1)", _alias);

 directorySearcher.set_Filter(strFmt('(&(objectClass=user)(objectCategory=person)%1(userAccountControl:1.2.840.113556.1.4.803:=512))', searchCriteria));


 searchResultCollection = directorySearcher.FindAll();
 searchCount = searchResultCollection.get_Count(); // In case more than 1 result is returned.

for (i = 0; i < searchCount; i++)


 {
 searchResult = searchResultCollection.get_Item(i);
 entry = searchResult.GetDirectoryEntry();
 if (entry)


 {
 propertyCollection = entry.get_Properties();
 }
 if (!propertyCollection)


 {
 entry.Dispose();
 continue;


 }
 // User properties list

try


 {
 // Company

 propertyValueCollection = propertyCollection.get_Item('Company');

if (PropertyValueCollection)


 {
 if (PropertyValueCollection.get_Value())


 {
 company = propertyValueCollection.get_Value();
 }
 }
 }
 catch (Exception::CLRError)


 {
 SRSProxy::handleClrException(Exception::Warning);
 warning(strFmt("@SYS117734"));


 }
 entry.Dispose();
 }
 searchResultCollection.Dispose();
 }
 catch (Exception::CLRError)


 {
 SRSProxy::handleClrException(Exception::Warning);
 error("@SYS117735");


 }
 CodeAccessPermission::revertAssert();
 }

No comments:

Post a Comment