Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Active directory查询以比我的尝试更好地缩小结果范围_C#_Active Directory_Adsi - Fatal编程技术网

C# Active directory查询以比我的尝试更好地缩小结果范围

C# Active directory查询以比我的尝试更好地缩小结果范围,c#,active-directory,adsi,C#,Active Directory,Adsi,我的具体问题:如何缩小对未设置employeeNumber属性(不为null或空)的active directory帐户的搜索范围? 我的工作是检查结果,检查员工编号并删除这些帐户。但是,我希望我的查询能够缩小结果的范围,然后再进行手动筛选 我认为这行代码甚至没有启动过滤器:((DirectorySearcher)ps.getUnderlineSearcher()).filter=“(&(objectCategory=Person)(objectClass=User)(!employeeNumb

我的具体问题:如何缩小对未设置employeeNumber属性(不为null或空)的active directory帐户的搜索范围?

我的工作是检查结果,检查员工编号并删除这些帐户。但是,我希望我的查询能够缩小结果的范围,然后再进行手动筛选

我认为这行代码甚至没有启动过滤器:
((DirectorySearcher)ps.getUnderlineSearcher()).filter=“(&(objectCategory=Person)(objectClass=User)(!employeeNumber=*)”;//我希望它只返回设置了employeeNumber的广告帐户

 PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "myDomain");
                UserPrincipal user = new UserPrincipal(domainContext);
                user.SamAccountName = ParamSamAccountName;
                user.Enabled = true;//only enabled users
                user.PasswordNeverExpires = false; //this should get rid of service accounts

                PrincipalSearcher pS = new PrincipalSearcher();
                pS.QueryFilter = user;

                PrincipalSearcher ps = new PrincipalSearcher(user);
                ((DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500;
               ((DirectorySearcher)ps.GetUnderlyingSearcher()).Filter = "(&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*)))";//this doesnt seem to be working... bug...
                var searchResults = SafeFindAll(ps);



      private static IEnumerable<Principal> SafeFindAll(PrincipalSearcher searcher)
            {
                using (var results = searcher.FindAll())
                {
                    foreach (var result in results)
                    {
                        yield return result;
                    }
                } // SearchResultCollection will be disposed here
            }
PrincipalContext domainContext=新PrincipalContext(ContextType.Domain,“myDomain”);
UserPrincipal用户=新的UserPrincipal(域上下文);
user.SamAccountName=ParamSamAccountName;
user.Enabled=true//仅启用用户
user.PasswordNeverExpires=false//这应该可以去掉服务帐户
PrincipalSearcher pS=新PrincipalSearcher();
pS.QueryFilter=用户;
PrincipalSearcher ps=新PrincipalSearcher(用户);
((DirectorySearcher)ps.GetUnderlineSearcher()).PageSize=500;
((DirectorySearcher)ps.GetUnderlineSearcher()).Filter=“(&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*))”//这似乎不起作用。。。缺陷
var searchResults=SafeFindAll(ps);
私有静态IEnumerable SafeFindAll(PrincipalSearcher搜索器)
{
使用(var results=searcher.FindAll())
{
foreach(结果中的var结果)
{
收益结果;
}
}//SearchResultCollection将在此处处理
}

你的问题有点让人困惑。如果不需要employeeNumber集,则是正确的;如果需要employeeNumber集,则需要以下内容:(&(objectCategory=Person)(objectClass=User)(employeeNumber=*))

此外,您需要确保获得LDAP连接。下面的一些代码可能会有所帮助,另请参阅此博客:

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间LDAPCSharp
{
使用System.DirectoryServices;
使用System.DirectoryServices.ActiveDirectory;
班级计划
{
静态void Main(字符串[]参数)
{
var ldapDomain=FriendlyDomainToLdapDomain(“domainRemoved”);
var allResults=FindAllWithEmployeeNumber(ldapDomain);
foreach(所有结果中的var searchResult)
{
使用(var entry=searchResult.GetDirectoryEntry())
{
foreach(entry.Properties.PropertyNames中的var值)
{
控制台写入线(值);
}
}
}
}
/// 
///他们找到了一切。
/// 
/// 
///ldap域。
/// 
/// 
///这个。
/// 
公共静态IEnumerable FindAllWithEmployeeNumber(字符串ldapDomain)
{
string connectionPrefix=“LDAP://”+ldapDomain;
DirectoryEntry=新的DirectoryEntry(connectionPrefix);
DirectorySearcher mySearcher=新的DirectorySearcher(条目);
//所有已设置employeenumber的
mySearcher.Filter=“(&(objectCategory=Person)(objectClass=User)(employeeNumber=*)”;
//全部不带employeenumber集
//mySearcher.Filter=(&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*))”;
mySearcher.PageSize=10;
var结果=SafeFindAll(mySearcher);
Dispose();
返回结果;
}
公共静态字符串FriendlyDomainToLdapDomain(字符串friendlyDomainName)
{
字符串ldapPath=null;
尝试
{
DirectoryContext objContext=新的DirectoryContext(
DirectoryContextType.Domain,friendlyDomainName);
Domain objDomain=Domain.GetDomain(objContext);
ldapPath=objDomain.Name;
}
捕获(DirectoryServicesCOMException e)
{
ldapPath=e.Message.ToString();
}
返回ldapPath;
}
私有静态IEnumerable SafeFindAll(DirectorySearcher搜索器)
{
使用(var results=searcher.FindAll())
{
foreach(结果中的var结果)
{
产生返回(SearchResult)结果;
}
}//SearchResultCollection将在此处处理
}
}
}

你的问题有点让人困惑。如果你不想设置employeeNumber,那么你是对的,如果你想设置employeeNumber,那么你需要这个:(&(objectCategory=Person)(objectClass=User)(employeeNumber=*))

此外,您还需要确保获得LDAP连接。下面的一些代码可能会有所帮助,请参阅此博客:

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间LDAPCSharp
{
使用System.DirectoryServices;
使用System.DirectoryServices.ActiveDirectory;
班级计划
{
静态void Main(字符串[]参数)
{
var ldapDomain=FriendlyDomainToLdapDomain(“domainRemoved”);
var allResults=FindAllWithEmployeeNumber(ldapDomain);
foreach(所有结果中的var searchResult)
{
使用(var entry=searchResult.GetDirectoryEntry())
{
弗雷奇(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LDAPCSharp
{

    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;

    class Program
    {
        static void Main(string[] args)
        {
            var ldapDomain = FriendlyDomainToLdapDomain("domainRemoved");


            var allResults = FindAllWithEmployeeNumber(ldapDomain);

            foreach (var searchResult in allResults)
            {
                using (var entry = searchResult.GetDirectoryEntry())
                {
                    foreach (var value in entry.Properties.PropertyNames)
                    {
                        Console.WriteLine(value);
                    }
                }
            }
        }

        /// <summary>
        /// The find all.
        /// </summary>
        /// <param name="ldapDomain">
        /// The ldap domain.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        public static IEnumerable<SearchResult> FindAllWithEmployeeNumber(string ldapDomain)
        {
            string connectionPrefix = "LDAP://" + ldapDomain;
            DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            // all that have employeenumber set
            mySearcher.Filter = "(&(objectCategory=Person)(objectClass=User)(employeeNumber=*))";

            // all WITHOUT employeenumber set
            // mySearcher.Filter = (&(objectCategory=Person)(objectClass=User)(!(employeeNumber=*)))";
            mySearcher.PageSize = 10;

            var results = SafeFindAll(mySearcher);

            mySearcher.Dispose();
            return results;
        }

        public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
        {
            string ldapPath = null;
            try
            {
                DirectoryContext objContext = new DirectoryContext(
                    DirectoryContextType.Domain, friendlyDomainName);
                Domain objDomain = Domain.GetDomain(objContext);
                ldapPath = objDomain.Name;
            }
            catch (DirectoryServicesCOMException e)
            {
                ldapPath = e.Message.ToString();
            }
            return ldapPath;
        }

        private static IEnumerable<SearchResult> SafeFindAll(DirectorySearcher searcher)
        {
            using (var results = searcher.FindAll())
            {
                foreach (var result in results)
                {
                    yield return (SearchResult)result;
                }
            } // SearchResultCollection will be disposed here
        }
    }
}
var userName = Request.ServerVariables["LOGON_USER"];
var pc = new PrincipalContext(ContextType.Domain);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"someUserName")) 
    {
        if (user != null)
        {
            fullName = user.DisplayName;
        }
    }
}
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
    // Implement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context) { }

    // Implement the constructor with initialization parameters.    
    public UserPrincipalEx(PrincipalContext context,
                         string samAccountName,
                         string password,
                         bool enabled)
        : base(context, samAccountName, password, enabled)
    { }

    // Create the "employeeNumber" property.    
    [DirectoryProperty("!employeeNumber")]
    public bool noEmployeeNumber
    {
        get
        {
            if (ExtensionGet("!employeeNumber").Length != 1) return false;
            string empNum = (string)ExtensionGet("!employeeNumber")[0];
            if (empNum == "*") return true; else return false;
        }
        set 
        {
            ExtensionSet("!employeeNumber", "*"); 
        }
    }
    // Create the "objectCategory" property.    
    [DirectoryProperty("objectCategory")]
    public string objectCategory
    {
        get
        {
            object[] result = this.ExtensionGet("objectCategory");
            if (result != null)
            {
                return (string)result[0];
            }
            else
            {
                return string.Empty;
            }
        }
        set { this.ExtensionSet("objectCategory", value); }
    }

    // Implement the overloaded search method FindByIdentity.
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
    }

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
    }
}
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "mydomain");
UserPrincipalEx user = new UserPrincipalEx(domainContext);

// here are our new properties:
user.noEmployeeNumber = true;
user.objectCategory = "person";

user.Enabled = true; //only enabled users
user.PasswordNeverExpires = false; //this should get rid of service accounts
PrincipalSearcher ps = new PrincipalSearcher(user);
var searchResults = ps.FindAll();