0

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

代码如下:

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)
   {

   }
}

编辑 能够使用以下代码弄清楚这一点:

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;
    }
4

1 回答 1

1

您正在尝试从域访问管理器,而不是从请求者。

在一个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)
        {

        }
于 2013-03-21T19:39:42.523 回答