无法从活动目录c#获取完整的用户组

时间:2017-04-18 13:52:04

标签: c# active-directory

我正在尝试将一些旧代码转换为使用新命名空间从活动目录中获取用户,组,子组并将其插入到数据库中。新代码未返回用户关联的组的完整列表。新代码不会返回与用户关联的某些组。

旧代码:

       DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(directoryPath));
        searcher.PageSize = 1000;
        searcher.Filter = "(&(objectCategory=user))";

        //adding these properties assist in assuring they are returned by Active Directory
        searcher.PropertiesToLoad.Add("memberOf");
        searcher.PropertiesToLoad.Add("member");
        searcher.PropertiesToLoad.Add("samaccountname");
        searcher.PropertiesToLoad.Add("cn");
        searcher.PropertiesToLoad.Add("description");
        searcher.PropertiesToLoad.Add("whencreated");
        searcher.PropertiesToLoad.Add("mail");

        SearchResultCollection resultUsers = searcher.FindAll();
        Dictionary<string, Group> groups = new Group().GetAllGroups(); //get the list of groups that were inserted into DB
        foreach (SearchResult resultUser in resultUsers)
        {
            DirectoryEntry userEntry = resultUser.GetDirectoryEntry();

            string userName = GetProperty(userEntry, "samaccountname"); //Custom method to get samaccountname

            //make sure the username exists
            if (userName.Length != 0)
            {

                User user = new User();

                //set user properties
                user.FullName = user.Email = GetProperty(userEntry, "cn");
                user.Email = GetProperty(userEntry, "mail");
                string createdDateString = GetProperty(userEntry, "whencreated");
                user.CreatedDate = (createdDateString.Length > 0) ? DateTime.Parse(createdDateString) : DateTime.MinValue;
                user.UserName = userName;
                user.DomainName = _dataSource.UserDomainName;

                //check to see if the account is disabled
                ActiveDs.IADsUser objIADsUser = (ActiveDs.IADsUser)userEntry.NativeObject;
                user.Inactive = objIADsUser.AccountDisabled;

                //save the user
                user.SaveNew();

                userEntry.RefreshCache(new string[] { "tokenGroups" });

                //now the attribute will be available
                int count = userEntry.Properties["tokenGroups"].Count;

                IdentityReferenceCollection irc = ExpandTokenGroups(userEntry).Translate(typeof(NTAccount));

                foreach (IdentityReference ir in irc)
                {
                    NTAccount testAccount;
                    bool isNTAccount = false;
                    try
                    {
                        testAccount = (NTAccount)ir;
                        isNTAccount = true;
                    }
                    catch
                    {

                    }

                    if (isNTAccount)
                    {
                        NTAccount account = (NTAccount)ir;
                        string groupName = account.Value.Split('\\')[1];

                        if (groups.ContainsKey(groupName.ToLower()))
                        {
                            Group group = groups[groupName.ToLower()];

                            //add user to group
                            UserGroupLink userGroupLink = new UserGroupLink();
                            userGroupLink.GroupId = group.GroupId;
                            userGroupLink.UserId = user.UserID;
                            userGroupLink.SaveNew();
                        }
                    }
                }
            }
        }

        //close connection to active directory
        searcher.Dispose();

新代码:

    var section = (NameValueCollection)ConfigurationManager.GetSection("DataSource_ActiveDirectory1");
        string domainName = section["userDomainName"];
        string domainFilter = section["domainFilter"];
        PrincipalContext MyPrincipalContext = new PrincipalContext(ContextType.Domain, domainName, domainFilter); //Create your domain context
        GroupPrincipal FindAllGroups = new GroupPrincipal(MyPrincipalContext); //group principal to search for all group.
        UserPrincipal FindAllUsers = new UserPrincipal(MyPrincipalContext);    //user principal to search for all users.
        PrincipalSearcher UserSearcher = new PrincipalSearcher(FindAllUsers);  //search results for user
        PrincipalSearchResult<Principal> UserReults = UserSearcher.FindAll();  //find all users
        PrincipalSearcher MySearcher = new PrincipalSearcher(FindAllGroups);   //search results for groups
        PrincipalSearchResult<Principal> GroupResults = MySearcher.FindAll();  //search all groups
        ArrayList AllUsers = new ArrayList();
        foreach (Principal UserReult in UserReults)
        {
            UserPrincipal UserName = UserPrincipal.FindByIdentity(MyPrincipalContext, IdentityType.SamAccountName, UserReult.SamAccountName);
      //logic to save users to DB
        }
        foreach (Principal UserName in AllUsers)
        {
         foreach (Principal FindParentGroup in UserName.GetGroups())
            {
                string ParentGroupEntry = FindParentGroup.SamAccountName;

                if (ParentGroupEntry != null || ParentGroupEntry.Length > 0)
                 {
                         //Insert into DB
                 }
            }
        }

0 个答案:

没有答案