private void SetGroupInfos(string userName) { List <string> sidResult = new List <string>(); List <string> mailResult = new List <string>(); DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(); searcher.Filter = "(&((&(objectcategory=person)" + "(objectclass=user)))(sAMAccountName=*" + userName + "*))"; System.DirectoryServices.SearchResultCollection userlist = searcher.FindAll(); for (int i = 0; i < userlist.Count; i++) { var coll = userlist[i].Properties["memberOf"]; foreach (var gr in coll) { DirectoryEntry deUser = new DirectoryEntry("LDAP://" + gr); SecurityIdentifier sid = new SecurityIdentifier(deUser.Properties["objectSid"][0] as byte[], 0); sidResult.Add(sid.Value); if (deUser.Properties["mail"].Count > 0) { mailResult.Add(deUser.Properties["mail"][0].ToString()); } } } RSession.ADGroupMailAdresses = mailResult; RSession.ADGroupSIDs = sidResult; }
internal ADEntriesSet(SearchResultCollection src, ADStoreCtx storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADEntriesSet", "Ctor"); _searchResults = src; _storeCtx = storeCtx; _enumerator = src.GetEnumerator(); }
/// <summary> ///Helper method Get ActiveDirectory user from All domains /// </summary> /// <param name="UserName">Alias of user</param> /// <returns>List of active directory users</returns> private List <ADUsers> GetUserFromDifferentDomain(string userName) { List <ADUsers> userlist = new List <ADUsers>(); string user = userName.Trim('"'); int count = 0; foreach (string domain in GetDomains()) // From the domains obtained from the Forest, we search the domain subtree for the given userName. { string pathNameDomain = "LDAP://" + domain; /// this can be taken dynamically try { using (DirectoryEntry direcotyEntry = new DirectoryEntry(pathNameDomain)) { DirectorySearcher directorySearcher = new DirectorySearcher(direcotyEntry) { //need this comment for future //Filter = "(&(objectClass=user)(sAMAccountName=" + user + "))" // Filter = "(&(objectClass=user)(mail=" + user + "*))" Filter = "(&(objectClass=user)(|(mail=" + user + "*)(displayname=" + user + "*)))" }; System.DirectoryServices.SearchResultCollection results = directorySearcher.FindAll(); // If the user cannot be found, then let's check next domain. if (results == null || results.Count == 0) { continue; } // Here, we yield return for we want all of the domain which this userName is authenticated. foreach (SearchResult searchResult in results) { if (searchResult.Properties.Contains("mail")) { var email = searchResult.Properties["mail"][0].ToString(); int ispresent = userlist.Where(x => x.Email.Equals(email)).Count(); if (ispresent == 0) { userlist.Add(new ADUsers { Email = searchResult.Properties["mail"][0].ToString(), DisplayName = searchResult.Properties["displayname"][0].ToString(), UserName = searchResult.Properties["samaccountname"][0].ToString() }); count++; } } } } } catch (Exception) { throw; } } return(userlist); }
/// <summary> /// /// </summary> /// <param name="searchResultCollection"> /// </param> public SearchResultCollectionWrap(SearchResultCollection searchResultCollection) { this.searchResultCollection = searchResultCollection; this.searchResults = new List<ISearchResult>(); foreach (SearchResult searchResult in this.searchResultCollection) { this.searchResults.Add(new SearchResultWrap(searchResult)); } }
/// <summary> /// Propagate search results form directory search /// </summary> /// <param name="results">Directory search results</param> /// <returns>List of phone book search results</returns> protected virtual List<PhoneBookSearchResult> PropagateDirectoryEntryResults( SearchResultCollection results ) { var resultsPB = new List<PhoneBookSearchResult>(); foreach (SearchResult result in results) { if (!IsResultValid( result )) continue; resultsPB.Add( new PhoneBookSearchResult() { Department = result.Properties["department"][0].ToString(), FullName = result.Properties["cn"][0].ToString(), MailAddress = result.Properties["mail"][0].ToString(), TelephoneNumber = result.Properties["telephoneNumber"][0].ToString() } ); } return resultsPB; }
protected void Page_Load(object sender, EventArgs e) { string ldapQuery = HttpUtility.HtmlDecode(this.Request["LDAPQuery"]); try { try { this.searchResultCollection = DirectoryServicesWebUtils.ExecuteLDAPQuery(ldapQuery); } catch (System.Runtime.InteropServices.COMException cex) { //http://brennan.offwhite.net/blog/2005/07/22/firefox-authentication-with-ntlm/ this.ShowError("NTLM Authentication failed.\r\nIf you are using a browser like FireFox type 'about:config' in the url and add to the 'network.negotiate-auth.trusted-uris' the <IIS-Server-Name>.\r\nFinally Close and re-open your browser.\r\n\r\nError:\r\n" + cex.Message); } this.Text = String.Format("LDap Query Result: {0}", Utility.QuoteJScriptString(ldapQuery, false)); this.Title = this.Text; this.Description = this.Text; string nowaitpanel = this.Request["nowaitpanel"]; if (String.IsNullOrEmpty(nowaitpanel)) { if (!Page.IsPostBack) { this.showWaitPanelNow(this.pnlWait, this.LDAPQueryResultPanel); this.RegisterEndClientScript("window.location='" + this.Request.RawUrl + "&nowaitpanel=true'"); } } else if (nowaitpanel == "true") { this.LDAPQueryResultPanel.Visible = true; this.pnlWait.Visible = false; if (!Page.IsPostBack) { this.RefreshActiveDirectoryObjectsList(); } } } catch (Exception ex) { this.ShowError(ex.Message); } }
public static void GetListOfAdUsersByGroup(string domainName, string groupName) { DirectoryEntry entry = new DirectoryEntry("LDAP://DC=" + domainName + ",DC=com"); DirectorySearcher search = new DirectorySearcher(entry); string query = "(&(objectCategory=person)(objectClass=user)(memberOf=*))"; search.Filter = query; search.PropertiesToLoad.Add("memberOf"); search.PropertiesToLoad.Add("name"); System.DirectoryServices.SearchResultCollection mySearchResultColl = search.FindAll(); Console.WriteLine("Members of the {0} Group in the {1} Domain", groupName, domainName); foreach (SearchResult result in mySearchResultColl) { foreach (string prop in result.Properties["memberOf"]) { if (prop.Contains(groupName)) { Console.WriteLine(" " + result.Properties["name"][0].ToString()); } } } }
private bool GetNextSearchResult() { bool flag = false; do { if (this.currentMembersSearcher == null) { if (this.memberSearchersQueue.Count != 0) { this.currentMembersSearcher = this.memberSearchersQueue.Dequeue(); this.memberSearchResults = this.currentMembersSearcher.FindAll(); this.memberSearchResultsEnumerator = this.memberSearchResults.GetEnumerator(); } else { return false; } } flag = this.memberSearchResultsEnumerator.MoveNext(); if (flag) { continue; } this.currentMembersSearcher.Dispose(); this.currentMembersSearcher = null; this.memberSearchResults.Dispose(); this.memberSearchResults = null; } while (!flag); return flag; }
internal override void RestoreBookmark(ResultSetBookmark bookmark) { ADDNLinkedAttrSetBookmark aDDNLinkedAttrSetBookmark = (ADDNLinkedAttrSetBookmark)bookmark; this.usersVisited = aDDNLinkedAttrSetBookmark.usersVisited; this.groupsToVisit = aDDNLinkedAttrSetBookmark.groupsToVisit; this.groupsVisited = aDDNLinkedAttrSetBookmark.groupsVisited; this.storeCtx = aDDNLinkedAttrSetBookmark.storeCtx; this.current = aDDNLinkedAttrSetBookmark.current; this.returnedPrimaryGroup = aDDNLinkedAttrSetBookmark.returnedPrimaryGroup; this.foreignMembersCurrentGroup = aDDNLinkedAttrSetBookmark.foreignMembersCurrentGroup; this.fakePrincipalMembers = aDDNLinkedAttrSetBookmark.fakePrincipalMembers; this.foreignMembersToReturn = aDDNLinkedAttrSetBookmark.foreignMembersToReturn; this.currentForeignPrincipal = aDDNLinkedAttrSetBookmark.currentForeignPrincipal; this.currentForeignDE = aDDNLinkedAttrSetBookmark.currentForeignDE; this.foreignGroups = aDDNLinkedAttrSetBookmark.foreignGroups; if (this.queryMembersResults != null) { this.queryMembersResults.Dispose(); } this.queryMembersResults = aDDNLinkedAttrSetBookmark.queryMembersResults; this.queryMembersResultEnumerator = aDDNLinkedAttrSetBookmark.queryMembersResultEnumerator; this.memberSearchResults = aDDNLinkedAttrSetBookmark.memberSearchResults; this.memberSearchResultsEnumerator = aDDNLinkedAttrSetBookmark.memberSearchResultsEnumerator; this.atBeginning = aDDNLinkedAttrSetBookmark.atBeginning; this.expansionMode = aDDNLinkedAttrSetBookmark.expansionMode; this.members = aDDNLinkedAttrSetBookmark.members; this.membersEnum = aDDNLinkedAttrSetBookmark.membersEnum; if (this.membersQueue != null) { this.membersQueue.Clear(); if (aDDNLinkedAttrSetBookmark.membersQueue != null) { foreach (IEnumerable enumerable in aDDNLinkedAttrSetBookmark.membersQueue) { this.membersQueue.Enqueue(enumerable); } } } if (this.memberSearchersQueue != null) { foreach (DirectorySearcher directorySearcher in this.memberSearchersQueue) { directorySearcher.Dispose(); } this.memberSearchersQueue.Clear(); if (aDDNLinkedAttrSetBookmark.memberSearcherQueue != null) { foreach (DirectorySearcher directorySearcher1 in aDDNLinkedAttrSetBookmark.memberSearcherQueue) { this.memberSearchersQueue.Enqueue(directorySearcher1); } } } }
private List <ADUser> GetMembersLDAP(string groupName) { List <ADUser> users = new List <ADUser>(); try { using (System.Web.Hosting.HostingEnvironment.Impersonate()) { string dlManagerUserName = AppCredentials.Instance.UserName; string dlManagerPassword = AppCredentials.Instance.Password; int dlThreshold = Convert.ToInt32(AppCredentials.Instance.Threshold); using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName, dlManagerUserName, dlManagerPassword)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(oPrincipalContext, groupName); DirectoryEntry entry = new DirectoryEntry(); PrincipalSearcher srch = new PrincipalSearcher(); DirectorySearcher search = new DirectorySearcher(entry); string query = "(&(objectCategory=person)(objectClass=user)(memberOf=" + group.DistinguishedName + "))"; search.Filter = query; search.PropertiesToLoad.Add("memberOf"); search.PropertiesToLoad.Add("displayname"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("samaccountname"); search.PageSize = 20000; ADUser obj = null; System.DirectoryServices.SearchResultCollection mySearchResultColl = search.FindAll(); //Console.WriteLine("Members of the {0} Group in the {1} Domain", groupName, domainName); int i = 0; foreach (SearchResult result in mySearchResultColl) { foreach (string prop in result.Properties["memberOf"]) { if (prop.Contains(groupName)) { try { obj = new ADUser(); obj.Name = result.Properties["displayname"][0].ToString();// .Properties["displayname"][0] + ""; obj.Email = result.Properties["mail"][0].ToString(); obj.StaffID = result.Properties["samaccountname"][0].ToString(); users.Add(obj); if (i == dlThreshold + 1) { break; } i++; } catch { //LoggingHelper.Instance.LogAudit("Error User-" + groupName, result.Properties["samaccountname"][0].ToString()); } //Console.WriteLine(" " + result.Properties["name"][0].ToString()); } } if (i == dlThreshold + 1) { break; } } } } } catch (Exception ex) { LoggingHelper.Instance.LogError(LogOptions.GetMembers, ex); } return(users); }
public void OutputSearchResult(SearchResultCollection result, TraceListener listener) { int n = 0; foreach (SearchResult sr in result) { listener.WriteLine(string.Format("第{0}行结果开始", n)); listener.IndentLevel++; foreach (string propName in sr.Properties.PropertyNames) { string strValue = string.Empty; for (int i = 0; i < sr.Properties[propName].Count; i++) { if (strValue != string.Empty) strValue += ", "; strValue += sr.Properties[propName][i].ToString(); } listener.WriteLine(string.Format("Property Name: {0}\tProperty Value: {1}", propName, strValue)); } listener.IndentLevel--; listener.WriteLine(string.Format("第{0}行结果结束", n)); n++; } }
public string GetSearchResultDescription(SearchResultCollection result) { StringBuilder strB = new StringBuilder(1024); StringWriter sw = new StringWriter(strB); TextWriterTraceListener listener = new TextWriterTraceListener(sw); OutputSearchResult(result, listener); return strB.ToString(); }
internal ADEntriesSet(SearchResultCollection src, ADStoreCtx storeCtx, object discriminant) : this(src, storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADEntriesSet", "Ctor"); _discriminant = discriminant; }
private void ClearCachedResults() { _SrchColl = null; }
private void ImportResults(ActiveDirectorySearchParams searchParams, SearchResultCollection found) { foreach (SearchResult result in found) { if (this.CancelationPending) return; DirectoryEntry computer = result.GetDirectoryEntry(); var comp = ActiveDirectoryComputer.FromDirectoryEntry(searchParams.Domain, computer); this.FireComputerFound(comp); } }
internal ResultsEnumerator(SearchResultCollection results, string parentUserName, string parentPassword, AuthenticationTypes parentAuthenticationType) { if (parentUserName != null && parentPassword != null) _parentCredentials = new NetworkCredential(parentUserName, parentPassword); _parentAuthenticationType = parentAuthenticationType; _results = results; _initialized = false; // get the app configuration information object o = PrivilegedConfigurationManager.GetSection("system.directoryservices"); if (o != null && o is bool) { _waitForResult = (bool)o; } }
private bool CheckUserGroup(SearchResultCollection searchResults, string groupName) { var groupCount = searchResults[0].Properties["memberOf"].Count; for (var cnt = 0; cnt < groupCount; cnt++) { var grpName = (String)searchResults[0].Properties["memberOf"][cnt]; var equalsIndex = grpName.IndexOf(groupName, 1, StringComparison.Ordinal); if (equalsIndex > 0) return true; } return false; }
internal override void Reset() { if (!this.atBeginning) { this.usersVisited.Clear(); this.groupsToVisit.Clear(); string item = this.groupsVisited[0]; this.groupsVisited.Clear(); this.groupsVisited.Add(item); this.members = null; this.membersEnum = null; if (this.originalMembers != null) { this.membersQueue.Clear(); foreach (IEnumerable enumerable in enumerable) { this.membersQueue.Enqueue(enumerable); IEnumerator enumerator = enumerable.GetEnumerator(); enumerator.Reset(); } } this.expansionMode = this.originalExpansionMode; this.storeCtx = this.originalStoreCtx; this.current = null; if (this.primaryGroupDN != null) { this.returnedPrimaryGroup = false; } this.foreignMembersCurrentGroup.Clear(); this.fakePrincipalMembers.Clear(); if (this.foreignMembersToReturn != null) { this.foreignMembersToReturn.Clear(); } this.currentForeignPrincipal = null; this.currentForeignDE = null; this.foreignGroups.Clear(); this.queryMembersResultEnumerator = null; if (this.queryMembersResults != null) { this.queryMembersResults.Dispose(); this.queryMembersResults = null; } if (this.currentMembersSearcher != null) { this.currentMembersSearcher.Dispose(); this.currentMembersSearcher = null; } this.memberSearchResultsEnumerator = null; if (this.memberSearchResults != null) { this.memberSearchResults.Dispose(); this.memberSearchResults = null; } if (this.memberSearchersQueue != null) { foreach (DirectorySearcher directorySearcher in this.memberSearchersQueue) { directorySearcher.Dispose(); } this.memberSearchersQueue.Clear(); if (this.memberSearchersQueueOriginal != null) { foreach (DirectorySearcher directorySearcher1 in this.memberSearchersQueueOriginal) { this.memberSearchersQueue.Enqueue(directorySearcher1); } } } this.atBeginning = true; } }
public SearchResult FindOne() { SearchResult result = null; SearchResultCollection results = this.FindAll(false); try { foreach (SearchResult result2 in results) { if (this.directorySynchronizationSpecified) { System.DirectoryServices.DirectorySynchronization directorySynchronization = this.DirectorySynchronization; } if (this.directoryVirtualListViewSpecified) { DirectoryVirtualListView virtualListView = this.VirtualListView; } return result2; } return result; } finally { this.searchResult = null; results.Dispose(); } return result; }
internal override ResultSetBookmark BookmarkAndReset() { ADDNLinkedAttrSetBookmark aDDNLinkedAttrSetBookmark = new ADDNLinkedAttrSetBookmark(); aDDNLinkedAttrSetBookmark.usersVisited = this.usersVisited; this.usersVisited = new Dictionary<string, bool>(); aDDNLinkedAttrSetBookmark.groupsToVisit = this.groupsToVisit; this.groupsToVisit = new List<string>(); string item = this.groupsVisited[0]; aDDNLinkedAttrSetBookmark.groupsVisited = this.groupsVisited; this.groupsVisited = new List<string>(); this.groupsVisited.Add(item); aDDNLinkedAttrSetBookmark.expansionMode = this.expansionMode; aDDNLinkedAttrSetBookmark.members = this.members; aDDNLinkedAttrSetBookmark.membersEnum = this.membersEnum; this.members = null; this.membersEnum = null; if (this.membersQueue != null) { aDDNLinkedAttrSetBookmark.membersQueue = new Queue<IEnumerable>(this.membersQueue.Count); foreach (IEnumerable enumerable in this.membersQueue) { aDDNLinkedAttrSetBookmark.membersQueue.Enqueue(enumerable); } } if (this.membersQueue != null) { this.membersQueue.Clear(); if (this.originalMembers != null) { foreach (IEnumerable enumerable1 in this.originalMembers) { this.membersQueue.Enqueue(enumerable1); IEnumerator enumerator = enumerable1.GetEnumerator(); enumerator.Reset(); } } } aDDNLinkedAttrSetBookmark.storeCtx = this.storeCtx; this.expansionMode = this.originalExpansionMode; if (this.currentMembersSearcher != null) { this.currentMembersSearcher.Dispose(); this.currentMembersSearcher = null; } this.storeCtx = this.originalStoreCtx; aDDNLinkedAttrSetBookmark.current = this.current; aDDNLinkedAttrSetBookmark.returnedPrimaryGroup = this.returnedPrimaryGroup; this.current = null; if (this.primaryGroupDN != null) { this.returnedPrimaryGroup = false; } aDDNLinkedAttrSetBookmark.foreignMembersCurrentGroup = this.foreignMembersCurrentGroup; aDDNLinkedAttrSetBookmark.fakePrincipalMembers = this.fakePrincipalMembers; aDDNLinkedAttrSetBookmark.foreignMembersToReturn = this.foreignMembersToReturn; aDDNLinkedAttrSetBookmark.currentForeignPrincipal = this.currentForeignPrincipal; aDDNLinkedAttrSetBookmark.currentForeignDE = this.currentForeignDE; this.foreignMembersCurrentGroup = new List<DirectoryEntry>(); this.fakePrincipalMembers = new List<DirectoryEntry>(); this.currentForeignDE = null; aDDNLinkedAttrSetBookmark.foreignGroups = this.foreignGroups; this.foreignGroups = new List<GroupPrincipal>(); aDDNLinkedAttrSetBookmark.queryMembersResults = this.queryMembersResults; aDDNLinkedAttrSetBookmark.queryMembersResultEnumerator = this.queryMembersResultEnumerator; this.queryMembersResults = null; this.queryMembersResultEnumerator = null; aDDNLinkedAttrSetBookmark.memberSearchResults = this.memberSearchResults; aDDNLinkedAttrSetBookmark.memberSearchResultsEnumerator = this.memberSearchResultsEnumerator; this.memberSearchResults = null; this.memberSearchResultsEnumerator = null; if (this.memberSearchersQueue != null) { aDDNLinkedAttrSetBookmark.memberSearcherQueue = new Queue<DirectorySearcher>(this.memberSearchersQueue.Count); foreach (DirectorySearcher directorySearcher in this.memberSearchersQueue) { aDDNLinkedAttrSetBookmark.memberSearcherQueue.Enqueue(directorySearcher); } } if (this.memberSearchersQueueOriginal != null) { this.memberSearchersQueue.Clear(); foreach (DirectorySearcher directorySearcher1 in this.memberSearchersQueueOriginal) { this.memberSearchersQueue.Enqueue(directorySearcher1); } } aDDNLinkedAttrSetBookmark.atBeginning = this.atBeginning; this.atBeginning = true; return aDDNLinkedAttrSetBookmark; }
static void display(SearchResultCollection result, bool showProperties=false) { Console.WriteLine(result.Count); foreach (SearchResult item in result) { Console.WriteLine(item.Path); if (showProperties == false) continue; foreach (string pn in item.Properties.PropertyNames) { var pvc = item.Properties[pn]; Console.WriteLine("\t{0}", pn); foreach (var pv in pvc) { Console.WriteLine("\t\t{0}", pv); } } } }
/// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.FindOne"]/*' /> /// <devdoc> /// <para>Executes the search and returns only the first entry that is found.</para> /// </devdoc> public SearchResult FindOne() { DirectorySynchronization tempsync = null; DirectoryVirtualListView tempvlv = null; SearchResult resultEntry = null; SearchResultCollection results = FindAll(false); try { foreach (SearchResult entry in results) { // need to get the dirsync cookie if (directorySynchronizationSpecified) tempsync = DirectorySynchronization; // need to get the vlv response if (directoryVirtualListViewSpecified) tempvlv = VirtualListView; resultEntry = entry; break; } } finally { searchResult = null; // still need to properly release the resource results.Dispose(); } return resultEntry; }
private SearchResultCollection FindAll(bool findMoreThanOne) { searchResult = null; DirectoryEntry clonedRoot = null; if (_assertDefaultNamingContext == null) { clonedRoot = SearchRoot.CloneBrowsable(); } else { clonedRoot = SearchRoot.CloneBrowsable(); } UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject; if (!(adsObject is UnsafeNativeMethods.IDirectorySearch)) throw new NotSupportedException(Res.GetString(Res.DSSearchUnsupported, SearchRoot.Path)); // this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than // one reference count, one by SearchResultCollection object, one by DirectorySearcher object. In this way, when user calls // Dispose on SearchResultCollection, the connection is still there instead of reference count dropping to zero and being closed. // It is especially important for virtuallistview case, in order to reuse the vlv response, the search must be performed on the same ldap connection // only do it when vlv is used if (directoryVirtualListViewSpecified) { SearchRoot.Bind(true); } UnsafeNativeMethods.IDirectorySearch adsSearch = (UnsafeNativeMethods.IDirectorySearch)adsObject; SetSearchPreferences(adsSearch, findMoreThanOne); string[] properties = null; if (PropertiesToLoad.Count > 0) { if (!PropertiesToLoad.Contains("ADsPath")) { // if we don't get this property, we won't be able to return a list of DirectoryEntry objects! PropertiesToLoad.Add("ADsPath"); } properties = new string[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(properties, 0); } IntPtr resultsHandle; if (properties != null) adsSearch.ExecuteSearch(Filter, properties, properties.Length, out resultsHandle); else { adsSearch.ExecuteSearch(Filter, null, -1, out resultsHandle); properties = new string[0]; } SearchResultCollection result = new SearchResultCollection(clonedRoot, resultsHandle, properties, this); searchResult = result; return result; }
// sync objects from AD to portal private void SyncObjectsFromAD(SyncTree syncTree, ADObjectType objType, SearchResultCollection allADObjects, Action<DirectoryEntry, string, Guid, SyncTree> CreateNewObject, Action<DirectoryEntry, Node, SyncTree> UpdateProperties) { foreach (SearchResult result in allADObjects) { try { string nodeADpath = result.Path; if (syncTree.IsADPathExcluded(nodeADpath)) continue; AdLog.LogOuterADObject("Syncing", result.Path); var guid = Common.GetADResultGuid(result, _config.GuidProp); if (!guid.HasValue) { // no AD guid present for object AdLog.LogErrorADObject("No AD GUID present", result.Path); continue; } // új objektumok (ou, user, group) felvétele, átmozgatások // - ha létezik az adott guid-ú objektum -> path ellenőrzés, átmozgatás // - ha nem létezik, létrehozás string nodePortalParentPath = syncTree.GetPortalParentPath(nodeADpath); if (!Node.Exists(nodePortalParentPath)) { // adpath: OU=OtherOrg,OU=ExampleOrg,DC=Nativ,DC=local // portalParentPath: "/Root/IMS/NATIV/ExampleOrg" EnsurePortalPath(syncTree, syncTree.GetADParentObjectPath(result.Path), RepositoryPath.GetParentPath(nodePortalParentPath)); } SyncOneADObject(result, null, (Guid)guid, objType, nodePortalParentPath, CreateNewObject, UpdateProperties, syncTree); } catch (Exception ex) { // syncing of one object of the current tree failed AdLog.LogException(ex); } } }
// delete portal objects that have no corresponding synchronized objects in AD private void DeleteObjectsFromAD(SyncTree syncTree, ADObjectType objType, SearchResultCollection allADObjects, Action<Node> DeletePortalObject) { try { AdLog.LogOuter("Querying all portal objects..."); var portalNodes = GetAllPortalObjects(objType, syncTree); AdLog.LogOuter("Checking if portal objects exist under synchronized path in AD..."); foreach (Node node in portalNodes) { try { // check if object exists under synchronized path in AD var guid = Common.GetPortalObjectGuid(node); if ((!guid.HasValue) || (!ADObjectPathSynced((Guid)guid, allADObjects, node))) { if (!guid.HasValue) AdLog.Log(string.Format("No guid set for portal object: {0} ", node.Path)); // deleted from AD or not under synchronized path any more DeletePortalObject(node); } } catch (Exception ex) { AdLog.LogException(ex); } } } catch (Exception ex) { AdLog.LogException(ex); } }
// checks if the AD object corresponding to the given portal guid exists under synchronized path - if not, it should be deleted from portal... private bool ADObjectPathSynced(Guid guid, SearchResultCollection ADObjects, Node node) { bool exists = false; foreach (SearchResult result in ADObjects) { if (Common.GetADResultGuid(result, _config.GuidProp) == guid) { var nodeADpath = result.Path; AdLog.Log(string.Format("AD object for portal object {0} (guid {1}) found ({2}), checking synctrees", node.Path, guid.ToString(), nodeADpath)); foreach (SyncTree syncTree in _syncTrees) { if (syncTree.ContainsADPath(nodeADpath)) return true; } AdLog.Log(string.Format("No corresponding synctree for AD object ({0}) found, object should be deleted", nodeADpath)); } } return exists; }
internal ADEntriesSet(SearchResultCollection src, ADStoreCtx storeCtx) { this.searchResults = src; this.storeCtx = storeCtx; this.enumerator = src.GetEnumerator(); }
internal ADEntriesSet(SearchResultCollection src, ADStoreCtx storeCtx, object discriminant) : this(src, storeCtx) { this.discriminant = discriminant; }
private ActiveDirectoryUser[] ParseSubset(SearchResultCollection results) { List<ActiveDirectoryUser> userList = new List<ActiveDirectoryUser>(); foreach (SearchResult result in results) { ActiveDirectoryUser u = new ActiveDirectoryUser(); userList.Add(u); DirectoryEntry innerEntry = new DirectoryEntry(result.Path, CriticalResults.Properties.Settings.Default.LDAPUsername, CriticalResults.Properties.Settings.Default.LDAPPassword); List<string> proxyAddresses = new List<string>(); object[] proxyAddressesVal = (object[])innerEntry.Properties["proxyAddresses"].Value; if (proxyAddressesVal != null) { foreach (object obj in proxyAddressesVal) { //if value is an email address add it to the user object with name of 'mail_x' if (((string)obj).ToLower().Contains("smtp")) { proxyAddresses.Add(((string)obj).Replace("smtp:", "").Replace("SMTP:", "")); } } } u.proxyAddresses = proxyAddresses.ToArray(); if(innerEntry.Properties["cn"].Value != null) u.cn = innerEntry.Properties["cn"].Value.ToString(); if(innerEntry.Properties["givenName"].Value != null) u.givenName = innerEntry.Properties["givenName"].Value.ToString(); if(innerEntry.Properties["sn"].Value != null) u.sn = innerEntry.Properties["sn"].Value.ToString(); if(innerEntry.Properties["mail"].Value != null) u.mail = innerEntry.Properties["mail"].Value.ToString(); if(innerEntry.Properties["displayName"].Value != null) u.displayName = innerEntry.Properties["displayName"].Value.ToString(); if (string.IsNullOrEmpty(u.mail) && u.proxyAddresses.Length > 0) { u.mail = u.proxyAddresses[0]; } } return userList.ToArray(); }
private bool MoveNextQueryPrimaryGroupMember() { bool flag = false; if (this.primaryGroupMembersSearcher != null) { if (this.queryMembersResults == null) { this.queryMembersResults = this.primaryGroupMembersSearcher.FindAll(); this.queryMembersResultEnumerator = this.queryMembersResults.GetEnumerator(); } flag = this.queryMembersResultEnumerator.MoveNext(); if (flag) { this.current = (SearchResult)this.queryMembersResultEnumerator.Current; this.currentForeignDE = null; this.currentForeignPrincipal = null; } } return flag; }
private ActiveDirectoryUser[] ParseFull(SearchResultCollection results) { List<ActiveDirectoryUser> userList = new List<ActiveDirectoryUser>(); foreach (SearchResult result in results) { ActiveDirectoryUser u = new ActiveDirectoryUser(); userList.Add(u); DirectoryEntry innerEntry = new DirectoryEntry(result.Path, CriticalResults.Properties.Settings.Default.LDAPUsername, CriticalResults.Properties.Settings.Default.LDAPPassword); int proxyAddressCount = 0; foreach (string name in innerEntry.Properties.PropertyNames) { //Added to retrieve proxy email address from active directory to facilitate partners search //Check if value is array of objects instead of single object if (innerEntry.Properties[name].Value.GetType() == typeof(object[]) && name == "proxyAddresses") { //Get array of values object[] value = (object[])innerEntry.Properties[name].Value; foreach (object obj in value) { //if value is an email address add it to the user object with name of 'mail_x' if (((string)obj).ToLower().Contains("smtp")) { proxyAddressCount++; string property_value = obj as string; string property_name = "mail_" + proxyAddressCount.ToString(); u.AddProperty(property_name, property_value); } } } else { string value = innerEntry.Properties[name].Value.ToString(); u.AddProperty(name, value); } } u.AddProperty("Proxy_Address_Count", proxyAddressCount.ToString()); } return userList.ToArray(); }
public static List<ActiveDirectoryUser> toList(SearchResultCollection _src) { List<ActiveDirectoryUser> r = new List<ActiveDirectoryUser>(); foreach (SearchResult sr in _src) { ResultPropertyValueCollection rpcObjectSid = sr.Properties["objectSid"]; ResultPropertyValueCollection rpcDisplayName = sr.Properties["displayName"]; ResultPropertyValueCollection rpcObjectGuid = sr.Properties["objectGUID"]; String sid = "<unknown>"; String displayName = "<unknown>"; String guid = "<unknown>"; if (rpcObjectSid.Count > 0) { byte[] val = (byte[])rpcObjectSid[0]; sid = new SecurityIdentifier(val, 0).Value; } if (rpcDisplayName.Count > 0) { displayName = rpcDisplayName[0].ToString(); } if (rpcObjectGuid.Count > 0) { byte[] val = (byte[])rpcObjectGuid[0]; guid = new Guid(val).ToString(); } ActiveDirectoryUser adu = new ActiveDirectoryUser(displayName, guid, sid, sr.Path); r.Add(adu); } return r; }
private static void LoadFromActiveDirectory() { string domainName = "LDAP://ou=osl,dc=win,dc=lottery,dc=state,dc=or,dc=us"; AD.DirectoryEntry dirEntry = new AD.DirectoryEntry(); AD.DirectorySearcher searcher; dirEntry.Path = domainName; dirEntry.AuthenticationType = AD.AuthenticationTypes.Secure; searcher = new AD.DirectorySearcher(); searcher.SearchRoot = dirEntry; searcher.SearchScope = AD.SearchScope.Subtree; //searcher.Filter = "(&(objectCategory=person)(sAMAccountName=*))"; searcher.Filter = "(&(objectCategory=person))"; AD.SearchResultCollection results = searcher.FindAll(); foreach (AD.SearchResult sr in results) { string adName = ""; string adDepartment = ""; string employeeId = ""; string emailaddr = ""; AD.ResultPropertyValueCollection departments = sr.Properties["department"]; if (departments != null && departments.Count > 0) { adDepartment = departments[0].ToString(); } AD.ResultPropertyValueCollection employeeIds = sr.Properties["employeeid"]; if (employeeIds != null && employeeIds.Count > 0) { employeeId = (string)employeeIds[0]; } AD.ResultPropertyValueCollection names = sr.Properties["Name"]; if (names != null && names.Count > 0) { adName = (string)names[0]; } if (!string.IsNullOrEmpty(adName) && !string.IsNullOrEmpty(adDepartment)) // Some non-security lottery staff do NOT have employee ID in Active Directory! // ALL OSP staff do NOT have an employee ID. // ( // !string.IsNullOrEmpty(employeeId) || (adDepartment.ToLower() == "security") // ) // ) { if (!adName.ToLower().Contains("-adm")) { AD.ResultPropertyValueCollection emails = sr.Properties["mail"]; if (emails != null && emails.Count > 0) { emailaddr = (string)emails[0]; } if (!string.IsNullOrEmpty(adName)) { if (adDepartment.ToLower() == "information technology" || adDepartment.StartsWith("IT")) { _ITPersonNames.Add(adName); if (!string.IsNullOrEmpty(emailaddr)) { _ITEmailAddresses.Add(emailaddr); } } } if (!string.IsNullOrEmpty(emailaddr)) { _AllEmailAddresses.Add(emailaddr); } } } } }
private ExchangeUserDict CreateExchangeUserCollection( SearchResultCollection searchResults ) { ExchangeUserDict userCollection = new ExchangeUserDict(); if ( searchResults != null ) { /* For each result set in the result set */ foreach ( System.DirectoryServices.SearchResult result in searchResults ) { /* Extract the property collection and create a new exchange user with it * Add the new user to the result set and use the account name as the index for * the dictionary collection */ ResultPropertyCollection property = result.Properties; ExchangeUser user = new ExchangeUser( property ); if ( !user.IsValid ) { log.WarnFormat( "User '{0}' is invalid and will not be synchronized.", user.CommonName ); } else if ( userCollection.ContainsKey( user.Email.ToLower() ) ) { log.WarnFormat( "User '{0}' was returned multiple times in the LDAP query. " + "Only the first instance was added.", user.Email ); } else { userCollection.Add( user.Email.ToLower(), user ); log.InfoFormat("Found and added '{0}' as an ExchangeUser.", user.Email); } log.DebugFormat("LDAP object debug info: {0}", user); } } return userCollection; }
private SearchResultCollection FindAll(bool findMoreThanOne) { IntPtr ptr; this.searchResult = null; DirectoryEntry root = null; if (this.assertDefaultNamingContext == null) { root = this.SearchRoot.CloneBrowsable(); } else { root = this.SearchRoot.CloneBrowsable(); } System.DirectoryServices.Interop.UnsafeNativeMethods.IAds adsObject = root.AdsObject; if (!(adsObject is System.DirectoryServices.Interop.UnsafeNativeMethods.IDirectorySearch)) { throw new NotSupportedException(Res.GetString("DSSearchUnsupported", new object[] { this.SearchRoot.Path })); } if (this.directoryVirtualListViewSpecified) { this.SearchRoot.Bind(true); } System.DirectoryServices.Interop.UnsafeNativeMethods.IDirectorySearch adsSearch = (System.DirectoryServices.Interop.UnsafeNativeMethods.IDirectorySearch) adsObject; this.SetSearchPreferences(adsSearch, findMoreThanOne); string[] array = null; if (this.PropertiesToLoad.Count > 0) { if (!this.PropertiesToLoad.Contains("ADsPath")) { this.PropertiesToLoad.Add("ADsPath"); } array = new string[this.PropertiesToLoad.Count]; this.PropertiesToLoad.CopyTo(array, 0); } if (array != null) { adsSearch.ExecuteSearch(this.Filter, array, array.Length, out ptr); } else { adsSearch.ExecuteSearch(this.Filter, null, -1, out ptr); array = new string[0]; } SearchResultCollection results = new SearchResultCollection(root, ptr, array, this); this.searchResult = results; return results; }