繁体   English   中英

尝试从活动目录检索数据时发生操作错误

[英]An Operations Error Occured When trying to retrieve data from active directory

我正在尝试从活动目录中获取管理器名称,但是在引发异常时收到错误“发生操作错误”。

代码如下:

public override void ItemAdding(SPItemEventProperties properties)
{
   base.ItemAdding(properties);

   try 
   {
      var requester = properties.Web.CurrentUser;

      properties.AfterProperties["Requester"] = requester;

      //Get the manager name from the active directory
      var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
   DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain);
      //Exeception occurs on this line below.
      string managerName = dir.Properties["Manager"].Value.ToString();

      properties.AfterProperties["Manager"] = managerName;

   }
   catch(Exception ex)
   {

   }
}

使用下面的代码, Edit可以弄清楚这一点:

try
    {
        // set up domain context
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

        // find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
        string samAccountName = "";


        if (user != null)
        {
            // do something here....     
            samAccountName = user.SamAccountName;
        }


        //Get the manager name from the active directory
        var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

        using(DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain))
        {
            using (DirectorySearcher ds = new DirectorySearcher(dir, "samAccountName=" + samAccountName))
            {

                SearchResult result = ds.FindOne();

                string managerName = result.Properties["manager"][0].ToString();
            }
        }


    }
    catch (Exception ex)
    {
        var message = ex.Message;
    }

您正在尝试从域而不是从请求者访问Manager。

在winform中,我会这样做,假设请求者== samAccountName:

       try
        {

            //Get the manager name from the active directory
            var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            using (DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain))
            {
                using (DirectorySearcher ds = new DirectorySearcher(dir, "samAccountName=" + requster))
                {
                    SearchResult sr = ds.FindOne();
                    //Exeception occurs on this line below, if the attribute is not set.
                    string managerName = sr.Properties["Manager"][0].ToString();
                }
            }

        }
        catch (Exception ex)
        {

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM