Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8546307
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T12:59:13+00:00 2026-06-11T12:59:13+00:00

I have the following code that takes a username and a password and then

  • 0

I have the following code that takes a username and a password and then creates the user on the machine and adds them to two specific groups. When I get to the group part it is really slow and I have no idea why. My last run according to my logs file says that adding the user to the Users group took 7 minutes, but the IIS_IUSRS was super fast.

below is my initial code that calls the methods that do the real work. I have tried using a task to help speed up the process of checking for groups, but it still runs super slow.

public void Apply(Section.User.User user, Action<string> status)
    {
        #region Sanity Checks

        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        if (status == null)
        {
            throw new ArgumentNullException("status");
        }
        #endregion
        _logger.Debug(string.Format("Starting to apply the user with name {0}", user.UserName));
        status(string.Format("Applying User {0} to the system.", user.UserName));

        using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
        {

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(pc, user.UserName);
            try
            {
                _logger.Debug("Checking if user already exists");
                if (userPrincipal == null)
                {
                    userPrincipal = CreateNewUser(user, pc);
                }

                _logger.Debug("Setting user password and applying to the system.");
                userPrincipal.SetPassword(user.UserPassword);
                userPrincipal.Save();

                Task<PrincipalSearchResult<Principal>> groups =
                    Task<PrincipalSearchResult<Principal>>.Factory.StartNew(userPrincipal.GetGroups);

                _logger.Debug("Adding user to the groups.");
                AddUserToGroups(pc, userPrincipal, groups, user.UserType.Equals(UserType.WorkerProcess.ToString()) ? "Administrators" : "Users", "IIS_IUSRS");
                AddCurrentUser(user);
            }
            finally
            {
                if (userPrincipal != null)
                {
                    userPrincipal.Dispose();
                }
            }


        }

    }

This is my private method I use to create the user if it doesn’t exist.

private UserPrincipal CreateNewUser(Section.User.User user, PrincipalContext principal)
    {
        _logger.Debug("User did not exist creating now.");
        UserPrincipal newUser = new UserPrincipal(principal)
            {
                Name = user.UserName,
                Description = user.UserDescription,
                UserCannotChangePassword = false,
                PasswordNeverExpires = true,
                PasswordNotRequired = false
            };
        _logger.Debug("User created.");
        return newUser;
    }

Below is the logic for the groups. I have made a comment above the offending code that I get hung on whenever I walk through with the debugger. Also the debug log entry is always the last one I get before the hang as well.

private void AddUserToGroups(PrincipalContext principal, UserPrincipal user, Task<PrincipalSearchResult<Principal>> userGroups, params string[] groups)
    {
        groups.AsParallel().ForAll(s =>
            {
                using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(principal, s))
                {
                    _logger.Debug(string.Format("Checking if user is alread in the group."));
                    if (gp != null && !userGroups.Result.Contains(gp))
                    {
                        _logger.Debug(string.Format("The user was not a member of {0} adding them now.", gp.Name));
                        //This is the point that the 7 minute hang starts
                        gp.Members.Add(user);
                        gp.Save();

                        _logger.Debug(string.Format("User added to {0}.", gp.Name));
                    }
                }
            });
    }

Any help with this would be greatly appreciated as this project is expected to release in October, but I can’t release with a 7 minute hang when creating a user.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T12:59:15+00:00Added an answer on June 11, 2026 at 12:59 pm

    Had the same problem. It seems that

        gp.Members.Add( user );
    

    is slow because it first enumerates groups (to get Members) and only then it adds to the collection (which adds another slowdown).

    The solution was to have it like:

        UserPrincipal user = this is your user;
        GroupPrincipal group = this is your group;
    
        // this is fast
        using ( DirectoryEntry groupEntry = group.GetUnderlyingObject() as DirectoryEntry )
        using ( DirectoryEntry userEntry = user.GetUnderlyingObject() as DirectoryEntry )
        {         
          groupEntry.Invoke( "Add", new object[] { userEntry.Path } ); 
        }
    
        //group.Members.Add(user); // and this is slow!
        //group.Save();
    

    Just a tip – creating passwords with SetPassword was also terribly slow for us. The solution was to follow the approach from “The .NET Developer’s Guide to Directory Services Programming” where they use a low level password setting using LdapConnection from System.DirectoryServices.Protocols.

    The last bottleneck we’ve discovered was caused by the User.GetGroups() method.

    Anyway, drop a note if the code for adding users to groups makes a difference for you. Also note that you don’t really need to perform this in parallel – I understand that this was your approach to speed up the code but you don’t really need this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following piece of code that takes in some words, stores them
I have a website that uses Basic Authentication (username/password). Why is the following code
I have the following code that checks the userName & userPassword is correct then
I have the following code that takes a double value and converts it to
I have the following piece of code from a function that takes the host
I have an input that takes tag names, with a space between them. Then
Ok, so I have a form that takes a username and a code. This
I have following code that I am compiling in a .NET 4.0 project namespace
I have following code that does not work due to a being a value
I have following code that does not work: I never get to goToFoodDetail .

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.