/// <summary> /// Get all DCs in a given site. /// </summary> /// <param name="dc">The DC to talk to.</param> /// <param name="siteDn">The site to query servers from.</param> /// <returns>All servers in the site.</returns> public DsServer[] ListServersWithDcsInSite(DsServer dc, string siteDn) { SearchResultEntryCollection results = null; ResultCode re = Search( dc, siteDn, "(&(objectClass=nTDSDSA)(msDS-hasMasterNCs=*))", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedName" }, out results); if (re != ResultCode.Success) { return(null); } List <DsServer> servers = new List <DsServer>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["distinguishedName"]; string dn = (string)attr[0]; DsServer srv = new DsServer(); // We need the server DN, not its NTDS DSA object DN. srv.ServerObjectName = GetParentObjectDn(dn); srv.NtdsDsaObjectName = dn; servers.Add(srv); } return(servers.ToArray()); }
/// <summary> /// Get all site objects in the forest where the DC is located. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All site objects in the forest.</returns> public DsSite[] ListSites(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); // Forest, so start with the root of config nc string siteRoot = "CN=Sites," + rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode ret = Search( dc, siteRoot, "(objectClass=site)", System.DirectoryServices.Protocols.SearchScope.OneLevel, null, out results ); List <DsSite> sites = new List <DsSite>(); foreach (SearchResultEntry site in results) { string dn = site.DistinguishedName; sites.Add(GetSite(dc, dn)); } return(sites.ToArray()); }
private SearchResultEntryCollection DirSyncQuery(ref SearchRequestExtender reqStore) { SearchResultEntryCollection ret = null; try { SearchResponse sresponse = (SearchResponse)base.Connection.SendRequest(reqStore.Request); DirectoryControl dscontrol = GetControl(sresponse.Controls, reqStore.DirSyncControl.Type); reqStore.UpdateDirSyncCookie(dscontrol); ret = sresponse.Entries; } catch (LdapException ldapEx) { reqStore.HasError = true; reqStore.ErrorMSG = ldapEx.Message; return(null); } catch (Exception ex) { reqStore.HasError = true; reqStore.ErrorMSG = ex.Message; return(null); } return(ret); }
public static string[] GetAttributeValuesString( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { SearchResultEntryCollection results = null; ResultCode ret = Search( dc, dn, ldapFilter, searchScope, new string[] { attributeName }, out results); if (ret != ResultCode.Success) { return(null); } foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes[attributeName]; if (attr == null) { return(null); } else { return((string[])attr.GetValues(typeof(string))); } } return(null); }
public static ResultCode Search( DsServer dc, string baseDn, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, string[] attributesToReturn, out SearchResultEntryCollection results ) { SearchResponse response = null; try { SearchRequest request = new SearchRequest( baseDn, ldapFilter, searchScope, attributesToReturn ); response = (SearchResponse)dc.LdapConn.SendRequest(request); } catch (DirectoryOperationException e) { results = null; return(e.Response.ResultCode); } results = response.Entries; return(response.ResultCode); }
/// <summary> /// Get all NCs in the forest. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All NC DNs in the forest.</returns> public string[] ListNCs(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); string partitionDn = "CN=Partitions," + rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode re = LdapUtility.Search( dc, partitionDn, "(objectClass=crossRef)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "nCName" }, out results); if (re != ResultCode.Success) { return(null); } List <string> ncs = new List <string>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["nCName"]; string dn = (string)attr[0]; ncs.Add(dn); } return(ncs.ToArray()); }
internal SearchResultCollection(DirectoryEntry searchRoot, SearchResultEntryCollection entries, List <string> propertiesLoaded) { _searchRoot = searchRoot; _entries = new List <SearchResult>(); foreach (SearchResultEntry entry in entries) { // Create a search result for each entry, populating its user, auth type, and properties var result = new SearchResult(_searchRoot.GetCredentials(), _searchRoot.AuthenticationType); result.Properties["distinguishedName"] = new List <string>(new[] { entry.DistinguishedName }); // Translate SearchResultEntryCollection attribute values into SearchResult properties foreach (DirectoryAttribute attr in entry.Attributes.Values) { var properties = new List <object>(); // Use for instead of foreach because DirectoryAttribute's index // property does fancy casting to string as needed. for (var i = 0; i < attr.Count; i++) { properties.Add(attr[i]); } result.Properties[attr.Name] = properties; } _entries.Add(result); } _properties = propertiesLoaded; }
internal static IEnumerable <SearchResultEntry> GetRange(this SearchResultEntryCollection collection) { for (int i = 0; i < collection.Count; i++) { yield return(collection[i]); } }
public MutableEntryCollection(SearchResultEntryCollection results) { foreach (SearchResultEntry se in results) { _results.Add(new MutableEntry(se)); } }
static IEnumerable <SearchResultEntry> ISE(SearchResultEntryCollection results) { foreach (SearchResultEntry se in results) { yield return(se); } }
/// <summary> /// Get all domains in the forest. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All domain objects in the forest.</returns> public DsDomain[] ListDomains(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); string partitionDn = "CN=Partitions," + rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode re = LdapUtility.Search( dc, partitionDn, "(&(objectClass=crossRef)(systemFlags:1.2.840.113556.1.4.804:=2))", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "nCName" }, out results); if (re != ResultCode.Success) { return(null); } List <DsDomain> domains = new List <DsDomain>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["nCName"]; string dn = (string)attr[0]; DsDomain domain = new AddsDomain(); domain.Name = dn; domains.Add(domain); } return(domains.ToArray()); }
protected internal virtual IEnumerable <ISearchResultEntry> CastCollection(SearchResultEntryCollection searchResultEntries) { if (searchResultEntries == null) { return(null); } return(this.CastCollection(searchResultEntries.Cast <SearchResultEntry>())); }
// Token: 0x06001223 RID: 4643 RVA: 0x00057E9C File Offset: 0x0005609C protected override SearchResultEntryCollection GetNextResultCollection() { this.dirSyncRequestControl.Cookie = base.Cookie; DirectoryControl directoryControl; SearchResultEntryCollection nextResultCollection = base.GetNextResultCollection(typeof(DirSyncResponseControl), out directoryControl); DirSyncResponseControl dirSyncResponseControl = directoryControl as DirSyncResponseControl; base.Cookie = dirSyncResponseControl.Cookie; base.RetrievedAllData = new bool?(!dirSyncResponseControl.MoreData); return(nextResultCollection); }
DSNAME[] LookupAttr(DsServer dc, uint flags, string attrName, string attrValue) { if (attrName == null || attrValue == null) { return(null); } RootDSE rootDse = LdapUtility.GetRootDSE(dc); SearchResultEntryCollection results = null; ResultCode re = Search( dc, rootDse.defaultNamingContext, "(" + attrName + "=" + attrValue + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedName" }, out results); if (re == ResultCode.NoSuchObject) { // not found in default NC, try in config NC re = Search( dc, rootDse.configurationNamingContext, "(" + attrName + "=" + attrValue + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedName" }, out results); } if (re == ResultCode.NoSuchObject) { // not found in config NC, try in schema NC re = Search( dc, rootDse.schemaNamingContext, "(" + attrName + "=" + attrValue + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedName" }, out results); } if (re == ResultCode.Success && results.Count > 0) { List <DSNAME> names = new List <DSNAME>(); foreach (SearchResultEntry e in results) { names.Add(LdapUtility.CreateDSNameForObject(dc, e.DistinguishedName)); } return(names.ToArray()); } return(null); }
protected virtual TResult[] GetNextPage() { SearchResultEntryCollection nextResultCollection = this.GetNextResultCollection(); if (nextResultCollection == null) { return((TResult[])new TResult[0]); } TResult[] array = base.Session.ObjectsFromEntries <TResult>(nextResultCollection, base.PreferredServerName, this.properties, this.dummyInstance); TResult[] result = this.skipNonUniqueResults ? this.GetUniqueResults(array) : array; this.pagesReturned++; return(result); }
public static List <string> GetAllGroups(string basePath) { List <string> lstgroups = new List <string>(); try { GetAppSettings(basePath); SearchRequest request = new SearchRequest { DistinguishedName = "ou=securitygroups,o=iringtools,dc=iringug,dc=org", // Filter = filter, Scope = System.DirectoryServices.Protocols.SearchScope.Subtree, }; LdapConnection ldapConnection = Connect(); if (ldapConnection != null) { SearchResponse response = (SearchResponse)ldapConnection.SendRequest(request); UTF8Encoding utf8 = new UTF8Encoding(false, true); if (response.Entries.Count > 0) { SearchResultEntryCollection entries = response.Entries; string[] names = null; for (int i = 0; i < entries.Count; i++) { SearchResultEntry entry = entries[i]; if (entries[i].DistinguishedName.StartsWith("cn=")) { names = entry.DistinguishedName.Split(','); string groupName = names.First().Substring(names.First().IndexOf("=") + 1); if (groupName.ToLower() != "administrator") { lstgroups.Add(groupName); } } } } } } catch (Exception ex) { _logger.Error("Error in getting security groups from LDAP server: " + ex); } return(lstgroups); }
/// <summary> /// get dn from SAM account name /// </summary> /// <param name="svr">dc</param> /// <param name="sam">sam</param> /// <returns>dn</returns> public static string GetObjectDNFromSAMName(DsServer svr, string sam) { SearchResultEntryCollection srec = null; ResultCode ret = Search(svr, svr.Domain.Name, "(samaccountname=" + sam + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedname" }, out srec); if (ret != ResultCode.Success) { return(null); } if (srec.Count == 0) { return(null); } return(srec[0].Attributes["distinguishedname"][0].ToString()); }
DSNAME?LookupCanonicalName(DsServer dc, string name) { if (name == null) { return(null); } string label = null; DSNAME?curObj = null; ParseCanonicalName(name, out label, out name); curObj = DomainFromDomainDNSName(dc, label); while (name != null && curObj != null) { ParseCanonicalName(name, out label, out name); SearchResultEntryCollection results = null; ResultCode re = Search( dc, LdapUtility.ConvertUshortArrayToString(curObj.Value.StringName), "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope.OneLevel, new string[] { "name" }, out results ); foreach (SearchResultEntry e in results) { if (label == (string)e.Attributes["name"][0]) { curObj = LdapUtility.CreateDSNameForObject(dc, e.DistinguishedName); break; } } if (curObj == null) { return(null); } } return(curObj); }
private ADRawEntry[] GetNextResultCollection() { this.vlvRequestControl.ContextId = base.Cookie; DirectoryControl directoryControl; SearchResultEntryCollection nextResultCollection = base.GetNextResultCollection(typeof(VlvResponseControl), out directoryControl); ADProviderPerf.UpdateProcessCounter(Counter.ProcessRateVlv, UpdateType.Add, 1U); ADProviderPerf.UpdateDCCounter(base.PreferredServerName, Counter.DCRateVlv, UpdateType.Add, 1U); base.Cookie = null; if (directoryControl != null) { VlvResponseControl vlvResponseControl = (VlvResponseControl)directoryControl; base.Cookie = vlvResponseControl.ContextId; this.estimatedRowCount = vlvResponseControl.ContentCount; this.currentRow = vlvResponseControl.TargetPosition; } if (nextResultCollection == null) { return(null); } return(base.Session.ObjectsFromEntries <ADRawEntry>(nextResultCollection, base.PreferredServerName, this.properties, ADVirtualListView.dummyADRawEntry)); }
/// <summary> /// Get all GC servers in the forest. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All GC servers in the forest.</returns> public DsServer[] ListGcServers(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); string configNcDn = rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode re = Search( dc, configNcDn, "(&(objectClass=nTDSDSA)(invocationId=*)(options:1.2.840.113556.1.4.804:=1))", System.DirectoryServices.Protocols.SearchScope.Subtree, null, out results); if (re != ResultCode.Success) { return(null); } List <DsServer> servers = new List <DsServer>(); foreach (SearchResultEntry e in results) { string dn = e.DistinguishedName; string serverObjDn = GetParentObjectDn(dn); string siteObjDn = GetParentObjectDn(GetParentObjectDn(serverObjDn)); DsServer srv = new DsServer(); // find the dnsHostName of the server object srv.DnsHostName = (string)GetAttributeValue(dc, serverObjDn, "dNSHostName"); srv.Site = new DsSite(); // Here, the site DN is actually the RDN of the site. srv.Site.DN = siteObjDn.Split(',')[0].Remove(0, 3).Trim(); servers.Add(srv); } return(servers.ToArray()); }
DirectoryAttribute GetAttrVals( DsServer dc, DSNAME o, string attrName, bool includeDeletedLinks = false) { SearchResultEntryCollection results = null; ResultCode re = Search( dc, LdapUtility.ConvertUshortArrayToString(o.StringName), "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope.Base, new string[] { attrName }, out results); if (re == ResultCode.Success) { return(results[0].Attributes[attrName]); } return(null); }
protected override SearchResultEntryCollection GetNextResultCollection() { this.pageResultRequestControl.Cookie = base.Cookie; this.pageResultRequestControl.PageSize = base.PageSize; if (base.PagesReturned > 0) { ADProviderPerf.UpdateProcessCounter(Counter.ProcessRatePaged, UpdateType.Add, 1U); ADProviderPerf.UpdateDCCounter(base.PreferredServerName, Counter.DCRatePaged, UpdateType.Add, 1U); } DirectoryControl directoryControl; SearchResultEntryCollection nextResultCollection = base.GetNextResultCollection(typeof(PageResultResponseControl), out directoryControl); base.Cookie = ((directoryControl == null) ? null : ((PageResultResponseControl)directoryControl).Cookie); if (base.Cookie == null || base.Cookie.Length == 0 || nextResultCollection == null) { base.RetrievedAllData = new bool?(true); } else { base.RetrievedAllData = new bool?(false); } return(nextResultCollection); }
public static object[] GetAttributeValuesOfType( DsServer dc, string dn, string attributeName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, Type valuesType) { SearchResultEntryCollection results = null; ResultCode ret = Search( dc, dn, ldapFilter, searchScope, new string[] { attributeName }, out results); if (ret != ResultCode.Success) { return(null); } foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes[attributeName]; if (attr == null) { return(null); } else { return(attr.GetValues(valuesType)); } } return(null); }
public SearchResultCollection(DirectoryEntry searchRoot, SearchResultEntryCollection entries, List <string> propertiesToLoad) { _searchRoot = searchRoot; _entries = new List <SearchResult>(); foreach (SearchResultEntry entry in entries) { var result = new SearchResult(_searchRoot.GetCredentials(), _searchRoot.AuthenticationType); result.Properties["distinguishedName"] = new List <string>(new[] { entry.DistinguishedName }); foreach (DirectoryAttribute attr in entry.Attributes.Values) { var properties = new List <object>(); // Use for instead of foreach because DirectoryAttribute's index // property does fancy casting to string as needed. for (int i = 0; i < attr.Count; i++) { properties.Add(attr[i]); } result.Properties[attr.Name] = properties; } _entries.Add(result); } _propertiesToLoad = propertiesToLoad; }
public List <SearchResultEntry> Query(string dc, string searchBase, string ldapFilter, string[] propertiesToLoad, SearchScope scope, ReferralChasingOptions referralChasing, QueryControl queryInfo, string[] attributesRemebered = null, bool returnResults = false) { CancelToken = false; GlobalEventHandler.ClearSearchCancelled(); GlobalEventHandler.SearchCancelled += ReceivedCancellation; List <SearchResultEntry> ret = new List <SearchResultEntry> { }; List <SearchResultEntry> fire = new List <SearchResultEntry> { }; QueryHasConstructedAttribute(propertiesToLoad, scope, ref queryInfo); if (queryInfo.MustGetSingleObjectPath) { GetSingleObjectPaths(dc, searchBase, ldapFilter, propertiesToLoad, scope, referralChasing, queryInfo); return(ret); } ForestBase.CurrentPorts.SelectedPort = queryInfo.Port; byte[] pagingCookie = null; SearchRequestExtender reqstore = new SearchRequestExtender(searchBase, ldapFilter, propertiesToLoad, scope, pagingCookie, queryInfo); reqstore.DC = dc; reqstore.ReferralChasing = referralChasing; propertiesToLoad = reqstore.Attributes; while (true) { if (!reqstore.HasError) { reqstore.PageCount++; } SearchResultEntryCollection colresult = null; if (!CancelToken) { if (!queryInfo.PerformDirSync) { DateTime starttime = DateTime.Now; colresult = PagedQuery(ref reqstore); if (reqstore.CurrentPageSize > 0) { GlobalEventHandler.RaiseMessageOccured(String.Format("Page: {0} ({1}) [{2}] ms]", reqstore.PageCount, reqstore.CurrentPageSize, DateTime.Now.Subtract(starttime).TotalMilliseconds)); } } else { colresult = DirSyncQuery(ref reqstore); } } else { break; } if (reqstore.HasError) { break; } if ((colresult != null) && (colresult.Count > 0) && ((colresult[0].DistinguishedName.Length != 0) || (searchBase == ""))) { SearchResultEntry[] temp = new SearchResultEntry[colresult.Count]; colresult.CopyTo(temp, 0); fire = temp.ToList(); if (returnResults) { ret.AddRange(fire); } } if ((queryInfo.CurrentResultEventType == QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) && (attributesRemebered != null)) { reqstore.HandleAttributes(attributesRemebered); } if (reqstore.MoreData) { if ((fire.Count > 0) && !returnResults) { GlobalEventHandler.RaiseQueryCompleted(fire, reqstore, QUERY_RESULT_EVENT_TYPE.IS_PARTIAL | queryInfo.CurrentResultEventType); } if ((queryInfo.CurrentResultEventType == QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) && (attributesRemebered != null)) { reqstore.HandleAttributes(propertiesToLoad); } } else { break; } } if (reqstore.DoPaging) { reqstore.AddMessage(String.Format("PageSize: {0}", reqstore.CurrentPageSize)); reqstore.AddMessage(String.Format("Pages: {0}", reqstore.PageCount)); } if (!returnResults) { GlobalEventHandler.RaiseQueryCompleted(fire, reqstore, QUERY_RESULT_EVENT_TYPE.IS_COMPLETED | queryInfo.CurrentResultEventType); } Disconnect(); return(ret); }
// Token: 0x060006F4 RID: 1780 RVA: 0x00025650 File Offset: 0x00023850 protected override SearchResultEntryCollection GetNextResultCollection() { if (base.Session.NetworkCredential == null) { this.vlvRequestControl.ContextId = base.Cookie; } this.vlvRequestControl.Offset = this.offSet; if (this.searchForward) { this.vlvRequestControl.BeforeCount = 0; this.vlvRequestControl.AfterCount = (this.includeBookmarkObject ? (base.PageSize - 1) : base.PageSize); } else { this.vlvRequestControl.BeforeCount = (this.includeBookmarkObject ? (base.PageSize - 1) : base.PageSize); this.vlvRequestControl.AfterCount = 0; } DirectoryControl directoryControl = null; SearchResultEntryCollection searchResultEntryCollection = null; try { searchResultEntryCollection = base.GetNextResultCollection(typeof(VlvResponseControl), out directoryControl); } catch (ADInvalidHandleCookieException ex) { if (this.vlvRequestControl.ContextId == null || this.vlvRequestControl.ContextId.Length == 0) { throw; } ExTraceGlobals.ADFindTracer.TraceDebug <string>((long)this.GetHashCode(), "ADVlvPagedReader::GetNextResultCollection encounter an exception \"{0}\". Clear the cookie and try again.", ex.Message); this.vlvRequestControl.ContextId = null; searchResultEntryCollection = base.GetNextResultCollection(typeof(VlvResponseControl), out directoryControl); } ADProviderPerf.UpdateProcessCounter(Counter.ProcessRateVlv, UpdateType.Add, 1U); ADProviderPerf.UpdateDCCounter(base.PreferredServerName, Counter.DCRateVlv, UpdateType.Add, 1U); base.Cookie = ((directoryControl == null) ? null : ((VlvResponseControl)directoryControl).ContextId); if (!this.searchForward) { base.RetrievedAllData = new bool?(true); } if (directoryControl == null || searchResultEntryCollection.Count == 0) { base.RetrievedAllData = new bool?(true); } else { this.totalCount = ((VlvResponseControl)directoryControl).ContentCount; if (this.searchForward && base.PagesReturned == 0) { this.offSet = ((VlvResponseControl)directoryControl).TargetPosition; if (!this.includeBookmarkObject) { this.offSet++; } } if (!this.searchForward) { this.offSet = ((VlvResponseControl)directoryControl).TargetPosition - searchResultEntryCollection.Count + 1; } this.firstEntry = (string)searchResultEntryCollection[0].Attributes[ADRecipientSchema.DisplayName.LdapDisplayName].GetValues(typeof(string))[0]; this.lastEntry = (string)searchResultEntryCollection[searchResultEntryCollection.Count - 1].Attributes[ADRecipientSchema.DisplayName.LdapDisplayName].GetValues(typeof(string))[0]; if (string.Compare(this.firstEntry, this.lastEntry, new CultureInfo(base.Lcid), CompareOptions.OrdinalIgnoreCase) == 0) { base.RetrievedAllData = new bool?(true); } if (this.searchForward) { this.vlvRequestControl.Target = Encoding.UTF8.GetBytes(this.lastEntry); } else { this.vlvRequestControl.Target = Encoding.UTF8.GetBytes(this.firstEntry); } } return(searchResultEntryCollection); }
private SearchResultEntryCollection PagedQuery(ref SearchRequestExtender reqStore) { SearchResultEntryCollection ret = null; SearchResponse sresponse = null; bool goon = false; try { if ((base.IsConnected == false) || (base.Connection == null)) { Connect(reqStore.DC, reqStore.ReferralChasing, connectionLess: reqStore.QueryInfo.RootDse); } sresponse = (SearchResponse)base.Connection.SendRequest(reqStore.Request); goon = true; } catch (LdapException ldapEx) { base.SetError(ldapEx.Message); reqStore.HasError = true; reqStore.ErrorMSG = ldapEx.Message; return(null); } catch (DirectoryOperationException direx) { if (direx.Response != null) { if (direx.Response.ResultCode == ResultCode.SizeLimitExceeded) { if (reqStore.QueryInfo.AutoPage) { GlobalEventHandler.RaiseErrorOccured(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); reqStore.AddMessage(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); reqStore.PageCookie(((SearchResponse)direx.Response).Entries.Count); reqStore.MoreData = true; } else { sresponse = (SearchResponse)direx.Response; GlobalEventHandler.RaiseErrorOccured(String.Format("\tNon-PagedQuery: {0} - returned first {1} entries", direx.Response.ResultCode.ToString(), sresponse.Entries.Count)); reqStore.AddMessage(String.Format("Non-PagedQuery: {0} - returned first {1} entries", direx.Response.ResultCode.ToString(), sresponse.Entries.Count)); } goon = true; } else if ((direx.Response.ResultCode == ResultCode.UnavailableCriticalExtension) && direx.Response.ErrorMessage.StartsWith("00002040") && (reqStore.PageControl != null) && (reqStore.ReferralChasing != ReferralChasingOptions.None)) { reqStore.PageCount--; string msg = "Multiple page cookies from referrals."; msg = String.Format("{0} ({1})", msg, direx.Message); if (direx.Response.ErrorMessage != null) { msg = String.Format("{0}: ({1})", msg, direx.Response.ErrorMessage); } base.SetError(msg); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; //goon = true; } else { string msg = direx.Message; if (direx.Response.ErrorMessage != null) { msg = String.Format("{0}: ({1})", msg, direx.Response.ErrorMessage); } base.SetError(msg); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; } } else // if (!goon) { base.SetError(direx.Message); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; } } catch (Exception ex) { base.SetError(ex.Message); reqStore.HasError = true; reqStore.ErrorMSG = ex.Message; return(null); } if (goon) { if (sresponse != null) { if (reqStore.RetreiveStatistics) { DirectoryControl dcStats = GetControl(sresponse.Controls, SearchRequestExtender.STATISTCS_CONTROL_OID); if (dcStats != null) { reqStore.Statistics.Add(new StatsData(dcStats.GetValue())); } else { GlobalEventHandler.RaiseErrorOccured("WARNING: No Query Statistics data returned"); } } if (reqStore.PageControl != null) { DirectoryControl pageRespControl = GetControl(sresponse.Controls, reqStore.PageControl.Type); reqStore.UpdatePagingCookie(pageRespControl, sresponse.Entries.Count); } ret = sresponse.Entries; } } return(ret); }
public static List <string> GetUserGroups(string userName, string basePath) { List <string> lstgroups = new List <string>(); try { GetAppSettings(basePath); SearchRequest request = new SearchRequest { DistinguishedName = "ou=securitygroups,o=iringtools,dc=iringug,dc=org", // Filter = filter, Scope = System.DirectoryServices.Protocols.SearchScope.Subtree, }; LdapConnection ldapConnection = Connect(); if (ldapConnection != null) { SearchResponse response = (SearchResponse)ldapConnection.SendRequest(request); UTF8Encoding utf8 = new UTF8Encoding(false, true); if (response.Entries.Count > 0) { SearchResultEntryCollection entries = response.Entries; for (int i = 0; i < entries.Count; i++) { SearchResultEntry entry = entries[i]; if (entry.Attributes["member"] != null) { DirectoryAttribute attrib = entry.Attributes["member"]; string[] names = null; for (int ic = 0; ic < attrib.Count; ic++) { if ((attrib[ic] as string).Contains(userName)) { if (entry.DistinguishedName.Contains(",")) { names = entry.DistinguishedName.Split(','); } else { _logger.Error("Please check the group name in LDAP:" + entry.DistinguishedName); return(null); } string groupName = names.First().Substring(names.First().IndexOf("=") + 1); lstgroups.Add(groupName); break; } } } } } } return(lstgroups); } catch (Exception ex) { _logger.Error("Error in getting groups from LDAP server for the current user: " + ex); throw ex; } }
/// <summary> /// Retrive the binary file from Ldap /// </summary> public static Stream GetFile <T>(string filePath) { try { string fileName = Path.GetFileName(filePath); if (fileName.ToLower().StartsWith("configuration")) // Configuration is of dictionary type so to avoid that. { return(null); } string filter = "(cn=" + fileName + ")"; SearchRequest request = new SearchRequest { DistinguishedName = groupDN, Filter = filter, Scope = System.DirectoryServices.Protocols.SearchScope.Subtree, }; LdapConnection ldapConnection = Connect(); if (ldapConnection != null) { SearchResponse response = (SearchResponse)ldapConnection.SendRequest(request); UTF8Encoding utf8 = new UTF8Encoding(false, true); if (response.Entries.Count > 0) { SearchResultEntryCollection entries = response.Entries; for (int i = 0; i < entries.Count; i++) { SearchResultEntry entry = entries[i]; IDictionaryEnumerator attribEnum = entry.Attributes.GetEnumerator(); while (attribEnum.MoveNext()) { DirectoryAttribute subAttrib = (DirectoryAttribute)attribEnum.Value; for (int ic = 0; ic < subAttrib.Count; ic++) { attribEnum.Key.ToString(); if (attribEnum.Key.ToString().ToLower() == "javaserializeddata") { if (subAttrib[ic] is byte[]) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(subAttrib[ic] as byte[], 0, (subAttrib[ic] as byte[]).Length); memStream.Seek(0, SeekOrigin.Begin); return(memStream); } } } } } } } return(null); } catch (Exception ex) { _logger.Error("Error in retrieving file from LDAP server: " + ex); throw ex; } }
public DsSite GetSite(DsServer dc, string dn) { DsSite site = new DsSite(); site.DN = dn; // servers // find all "server" objects under the site dn SearchResultEntryCollection results = null; ResultCode ret = Search( dc, dn, "(objectClass=server)", System.DirectoryServices.Protocols.SearchScope.Subtree, null, out results ); List <DsServer> servers = new List <DsServer>(); foreach (SearchResultEntry e in results) { DsServer srv = new DsServer(); srv.NtdsDsaObjectName = e.DistinguishedName; servers.Add(srv); } site.Servers = servers.ToArray(); // Look into every NTDS DSA object to find the domain it is in. List <string> domainNcs = new List <string>(); foreach (DsServer s in site.Servers) { string[] ncs = LdapUtility.GetAttributeValuesString( dc, s.NtdsDsaObjectName, "hasMasterNCs", "(objectClass=nTDSDSA)", System.DirectoryServices.Protocols.SearchScope.Subtree); if (ncs == null) { continue; } foreach (string nc in ncs) { bool newNc = true; foreach (string oldNc in domainNcs) { if (oldNc == nc) { newNc = false; break; } } if (newNc) { domainNcs.Add(nc); } } } /* * string[] domainNcs = LdapUtility.GetAttributeValuesString( * dc, * site.DN, * "hasMasterNCs", //"msDS-HasDomainNCs", * "(objectClass=nTDSDSA)", * System.DirectoryServices.Protocols.SearchScope.Subtree); */ bool isAdlds = !EnvironmentConfig.TestDS; if (domainNcs == null && isAdlds) { return(site); } // Eliminate ConfigNC and SchemaNC List <string> filteredDomainNcs = new List <string>(); foreach (string d in domainNcs) { if (d.StartsWith("CN=Configuration") || d.StartsWith("CN=Schema")) { continue; } filteredDomainNcs.Add(d); } List <DsDomain> domains = new List <DsDomain>(); foreach (string tdn in filteredDomainNcs) { bool n = true; foreach (DsDomain d in domains) { if (d.Name == tdn) { n = false; break; } } if (n) { DsDomain nd; if (isAdlds) { nd = new AdldsDomain(); } else { nd = new AddsDomain(); } nd.Name = tdn; domains.Add(nd); } } site.Domains = domains.ToArray(); return(site); }