Exemple #1
0
        /// <summary>
        /// Queries for directory entries matching a given filter up to a specified count
        /// </summary>
        /// <param name="count">The number of entries to find (-1 for no limit)</param>
        /// <returns>A SearchResultCollection containing matching directory entries</returns>
        public SearchResultCollection FindAll(int count)
        {
            // Always load ADsPath so that DirectoryEntry entities can be created
            if (!PropertiesToLoad.Contains("ADsPath"))
            {
                PropertiesToLoad.Add("ADsPath");
            }

            // Create an LDAP SearchRequest using the root's name and the provided filter, scope, and properties
            var req = new SearchRequest(SearchRoot.DistinguishedName, Filter, SearchScope, PropertiesToLoad.ToArray());

            if (count > 0)
            {
                // Limit the result size, if necessary
                req.SizeLimit = count;
            }

            // Use the SearchRoot's connection since it should already exist.
            var res = SearchRoot.Connection.SendRequest(req) as SearchResponse;

            if (res.ResultCode != ResultCode.Success)
            {
                throw new InvalidOperationException($"Error connecting to Active Directory: {res.ResultCode.ToString()}: {res.ErrorMessage}");
            }

            // Create and return a SearchResultCollection with the returned entries
            return(new SearchResultCollection(SearchRoot, res.Entries, PropertiesToLoad));
        }
Exemple #2
0
 /// <summary>
 /// Initializes a new instance of the DirectorySearcher class with
 /// SearchRoot set to its default value. Filter, PropertiesToLoad,
 /// and SearchScope are set to the specified values
 /// </summary>
 /// <param name="filter">
 /// The search filter string in Lightweight Directory Access Protocol
 /// (Ldap) format. The Filter property is initialized to this value.
 /// </param>
 /// <param name="propertiesToLoad">
 /// The set of properties to retrieve during the search. The
 /// PropertiesToLoad property is initialized to this value.
 /// </param>
 /// <param name="scope">
 /// The scope of the search that is observed by the server. The
 /// SearchScope property is initialized to this value.
 /// </param>
 public DirectorySearcher(string filter,
                          string[] propertiesToLoad,
                          SearchScope scope)
 {
     _SearchScope = scope;
     _Filter      = filter;
     PropertiesToLoad.AddRange(propertiesToLoad);
 }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the DirectorySearcher class with
 /// SearchScope set to its default value. SearchRoot, Filter, and
 /// PropertiesToLoad are set to the specified values.
 /// </summary>
 /// <param name="searchRoot">
 /// The node in the Active Directory hierarchy where the search starts.
 /// The SearchRoot property is initialized to this value
 /// </param>
 /// <param name="filter">
 /// The search filter string in Lightweight Directory Access Protocol
 /// (Ldap) format. The Filter property is initialized to this value.
 /// </param>
 /// <param name="propertiesToLoad">
 /// The set of properties retrieved during the search. The
 /// PropertiesToLoad property is initialized to this value.
 /// </param>
 public DirectorySearcher(DirectoryEntry searchRoot,
                          string filter,
                          string[] propertiesToLoad)
 {
     _SearchRoot = searchRoot;
     _Filter     = filter;
     PropertiesToLoad.AddRange(propertiesToLoad);
 }
 /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher7"]/*' />
 /// <devdoc>
 /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given
 ///    values.</para>
 /// </devdoc>
 public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
 {
     this.searchRoot = searchRoot;
     this.filter     = filter;
     if (propertiesToLoad != null)
     {
         PropertiesToLoad.AddRange(propertiesToLoad);
     }
     this.SearchScope = scope;
 }
Exemple #5
0
        public PrincipalSearcher(DomainPath domainPath, DirectoryEntry searchRoot, ICollection <string> additionalPropertyNames = null)
            : base(searchRoot)
        {
            this.domainPath = domainPath;
            this.additionalPropertyNames = additionalPropertyNames;

            PropertiesToLoad.Add(ActiveDirectoryProperties.ObjectGuid);
            PropertiesToLoad.Add(ActiveDirectoryProperties.DisplayName);
            PropertiesToLoad.Add(ActiveDirectoryProperties.Member);
            PropertiesToLoad.Add(ActiveDirectoryProperties.MemberOf);

            if (additionalPropertyNames != null)
            {
                foreach (string propertyName in additionalPropertyNames)
                {
                    PropertiesToLoad.Add(propertyName);
                }
            }
        }
        public SearchResultCollection FindAll(int count)
        {
            // TODO - Do something with count

            if (!PropertiesToLoad.Contains("ADsPath"))
            {
                PropertiesToLoad.Add("ADsPath");
            }

            SearchRequest req = new SearchRequest(SearchRoot.DistinguishedName, Filter, SearchScope, PropertiesToLoad.ToArray());

            // Use the SearchRoot's connection since it should already exist.
            // TODO - Learn more about AD to understand if it's better to create a new connection or to use an existing one.
            var res = SearchRoot.Connection.SendRequest(req) as SearchResponse;

            if (res.ResultCode != ResultCode.Success)
            {
                throw new InvalidOperationException($"Error connecting to Active Directory: {res.ResultCode.ToString()}: {res.ErrorMessage}");
            }

            return(new SearchResultCollection(SearchRoot, res.Entries, PropertiesToLoad));
        }
        private SearchResultCollection FindAll(bool findMoreThanOne)
        {
            //if it is not of valid searching type, then throw an exception
            if (SearchRoot == null)
            {
                Version adsVersion = GetAdsVersion();
                throw new InvalidOperationException(Res.GetString(Res.DSVersion, adsVersion.ToString()));
            }

            DirectoryEntry clonedRoot = null;

            if (assertDefaultNamingContext == null)
            {
                clonedRoot = SearchRoot.CloneBrowsable();
            }
            else
            {
                //SECREVIEW: If the SearchRoot was created by this object
                //                        it is safe to assert its browse permission to get
                //                        the inner IAds.
                DirectoryServicesPermission dsPermission = new DirectoryServicesPermission(
                    DirectoryServicesPermissionAccess.Browse, assertDefaultNamingContext);
                dsPermission.Assert();
                try {
                    clonedRoot = SearchRoot.CloneBrowsable();
                }
                finally {
                    DirectoryServicesPermission.RevertAssert();
                }
            }

            UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject;
            if (!(adsObject is UnsafeNativeMethods.IDirectorySearch))
            {
                throw new NotSupportedException(Res.GetString(Res.DSSearchUnsupported, SearchRoot.Path));
            }

            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, Filter);

            return(result);
        }
Exemple #8
0
        private void DoSearch()
        {
            InitBlock();
            String[] attrs = new String[PropertiesToLoad.Count];
            PropertiesToLoad.CopyTo(attrs, 0);

            LdapSearchConstraints cons = _conn.SearchConstraints;

            if (SizeLimit > 0)
            {
                cons.MaxResults = SizeLimit;
            }
            if (ServerTimeLimit != DefaultTimeSpan)
            {
                cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds;
            }

            int connScope = LdapConnection.SCOPE_SUB;

            switch (_SearchScope)
            {
            case SearchScope.Base:
                connScope = LdapConnection.SCOPE_BASE;
                break;

            case SearchScope.OneLevel:
                connScope = LdapConnection.SCOPE_ONE;
                break;

            case SearchScope.Subtree:
                connScope = LdapConnection.SCOPE_SUB;
                break;

            default:
                connScope = LdapConnection.SCOPE_SUB;
                break;
            }
            LdapSearchResults lsc = _conn.Search(SearchRoot.Fdn,
                                                 connScope,
                                                 Filter,
                                                 attrs,
                                                 PropertyNamesOnly, cons);

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                }
                catch (LdapException e)
                {
                    switch (e.ResultCode)
                    {
                    // in case of this return codes exception should not be thrown
                    case LdapException.SIZE_LIMIT_EXCEEDED:
                    case LdapException.TIME_LIMIT_EXCEEDED:
                    case LdapException.REFERRAL:
                        continue;

                    default:
                        throw e;
                    }
                }
                DirectoryEntry     de    = new DirectoryEntry(_conn);
                PropertyCollection pcoll = new PropertyCollection();
//				de.SetProperties();
                de.Path = DirectoryEntry.GetLdapUrlString(_Host, _Port, nextEntry.DN);
                LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                if (ienum != null)
                {
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        pcoll[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].Mbit=false;
                    }
                }
                if (!pcoll.Contains("ADsPath"))
                {
                    pcoll["ADsPath"].Add(de.Path);
                }
//				_SrchColl.Add(new SearchResult(de,PropertiesToLoad));
                _SrchColl.Add(new SearchResult(de, pcoll));
            }
            return;
        }
Exemple #9
0
 /// <summary>
 /// Initializes a new instance of the DirectorySearcher class with
 /// SearchRoot and SearchScope set to the default values. Filter and
 /// PropertiesToLoad are set to the specified values.
 /// </summary>
 /// <param name="filter">
 /// The search filter string in Lightweight Directory Access Protocol
 /// (Ldap) format. The Filter property is initialized to this value.
 /// </param>
 /// <param name="propertiesToLoad">
 /// The set of properties to retrieve during the search. The
 /// PropertiesToLoad property is initialized to this value.
 /// </param>
 public DirectorySearcher(string filter,
                          string[] propertiesToLoad)
 {
     _Filter = filter;
     PropertiesToLoad.AddRange(propertiesToLoad);
 }
Exemple #10
0
        public System.Data.DataTable GetQueryDataTable()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            List <string>         propertiesToLoad = new List <string>();

            if (PropertiesToLoad == null || PropertiesToLoad.Trim().Length == 0)
            {
                propertiesToLoad.Add("sAMAccountName");
                dt.Columns.Add(new System.Data.DataColumn("sAMAccountName", typeof(string)));
            }
            else
            {
                foreach (string propName in PropertiesToLoad.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    propertiesToLoad.Add(propName.Trim());
                    dt.Columns.Add(new System.Data.DataColumn(propName.Trim(), typeof(string)));
                }
            }

            if (QueryFilterText == null || QueryFilterText.Trim().Length == 0)
            {
                return(dt);
            }
            string formattedFilterText = FormatQueryFilter(QueryFilterText);

            if (formattedFilterText.Contains("%"))
            {
                formattedFilterText = MacroVariables.FormatVariables(formattedFilterText);
            }

            //int lineCount = 0;
            DirectoryEntry entryRoot = GetADRoot();

            using (DirectorySearcher searcher = new DirectorySearcher(entryRoot, formattedFilterText))
            {
                searcher.PropertiesToLoad.AddRange(propertiesToLoad.ToArray());
                searcher.SizeLimit = 1000;
                searcher.PageSize  = 1000;
                SearchResultCollection matches = searcher.FindAll();

                foreach (SearchResult match in matches)
                {
                    List <string> rowValues = new List <string>();
                    foreach (string propName in propertiesToLoad)
                    {
                        string propertyValue = "";
                        try
                        {
                            if (match.Properties.Contains(propName))
                            {
                                if (match.Properties[propName].Count > 0 && match.Properties[propName] != null)
                                {
                                    propertyValue = match.Properties[propName][0].ToString();
                                }
                                else
                                {
                                    propertyValue = "N/A";
                                }
                            }
                            else
                            {
                                propertyValue = "N/A";
                            }
                        }
                        catch
                        {
                            propertyValue = "err";
                        }
                        rowValues.Add(propertyValue);
                    }
                    dt.Rows.Add(rowValues.ToArray());
                    //lineCount++;
                    //if (lineCount >= MaxRowsToEvaluate)
                    //    break;
                }
            }
            return(dt);
        }
Exemple #11
0
        //For Collector testing purposes only the first MaxRowsToEvaluate number of returned records are used unless UseRowCountAsValue is true.
        public object RunQuery()
        {
            object returnValue = null;

            if (QueryFilterText == null || QueryFilterText.Trim().Length == 0)
            {
                return(null);
            }
            string formattedFilterText = FormatQueryFilter(QueryFilterText);

            if (formattedFilterText.Contains("%"))
            {
                formattedFilterText = MacroVariables.FormatVariables(formattedFilterText);
            }

            DirectoryEntry entryRoot = GetADRoot();

            using (DirectorySearcher searcher = new DirectorySearcher(entryRoot, formattedFilterText))
            {
                List <string> propertiesToLoad = new List <string>();
                if (PropertiesToLoad == null || PropertiesToLoad.Trim().Length == 0)
                {
                    propertiesToLoad.Add("sAMAccountName");
                }
                else
                {
                    foreach (string propName in PropertiesToLoad.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        propertiesToLoad.Add(propName.Trim());
                    }
                }
                searcher.PropertiesToLoad.AddRange(propertiesToLoad.ToArray());
                searcher.SizeLimit = 1000;
                searcher.PageSize  = 1000;
                SearchResultCollection matches = searcher.FindAll();
                if (UseRowCountAsValue)
                {
                    returnValue = matches.Count;
                }
                else
                {
                    StringBuilder lines     = new StringBuilder();
                    int           lineCount = 0;
                    foreach (SearchResult match in matches)
                    {
                        StringBuilder line = new StringBuilder();
                        foreach (string propName in propertiesToLoad)
                        {
                            string propertyValue = "";
                            try
                            {
                                if (match.Properties.Contains(propName))
                                {
                                    if (match.Properties[propName].Count > 0 && match.Properties[propName] != null)
                                    {
                                        propertyValue = match.Properties[propName][0].ToString();
                                    }
                                    else
                                    {
                                        propertyValue = "N/A";
                                    }
                                }
                                else
                                {
                                    propertyValue = "N/A";
                                }
                            }
                            catch
                            {
                                propertyValue = "err";
                            }
                            line.Append(propertyValue + ",");
                        }
                        lines.AppendLine(line.ToString().Trim(','));
                        lineCount++;
                        if (lineCount >= MaxRowsToEvaluate)
                        {
                            break;
                        }
                    }
                    returnValue = lines.ToString();
                }
            }
            return(returnValue);
        }
Exemple #12
0
 private void NewPropertyToLoad(string propertyName)
 {
     PropertiesToLoad.Clear();
     PropertiesToLoad.Add(propertyName);
 }