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 656293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:41:56+00:00 2026-05-13T22:41:56+00:00

I have a program that will let me manage users on our terminal server

  • 0

I have a program that will let me manage users on our terminal server that we use to demo our software. I have been trying to improve the performace of adding users to the system (It adds the main account then it adds sub accounts if needed, for example if I had a user of Demo1 and 3 sub users it would create Demo1, Demo1a, Demo1b, and Demo1c.)

private void AddUsers(UserInfo userInfo, InfinityInfo infinityInfo, int subUserStart)
{
    using (GroupPrincipal r = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users"))
    using (GroupPrincipal u = GroupPrincipal.FindByIdentity(context, "Users"))
    for(int i = subUserStart; i < userInfo.SubUsers; ++i)
    {
        string username = userInfo.Username;
        if (i >= 0)
        {
            username += (char)('a' + i);
        }
        UserPrincipal user = null;
        try
        {
            if (userInfo.NewPassword == null)
                throw new ArgumentNullException("userInfo.NewPassword", "userInfo.NewPassword was null");
            if (userInfo.NewPassword == "")
                throw new ArgumentOutOfRangeException("userInfo.NewPassword", "userInfo.NewPassword was empty");

            user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
            if (user == null)
            {
                user = new UserPrincipal(context, username, userInfo.NewPassword, true);
                user.UserCannotChangePassword = true;
                user.PasswordNeverExpires = true;
                user.Save();
                r.Members.Add(user);
                u.Members.Add(user);
            }
            else
            {
                user.Enabled = true;
                user.SetPassword(userInfo.NewPassword);
            }
            IADsTSUserEx iad = (IADsTSUserEx)((DirectoryEntry)user.GetUnderlyingObject()).NativeObject;
            iad.TerminalServicesInitialProgram = GenerateProgramString(infinityInfo);
            iad.TerminalServicesWorkDirectory = Service.Properties.Settings.Default.StartInPath;
            iad.ConnectClientDrivesAtLogon = 0;
            user.Save();
            r.Save();
            u.Save();
            OperationContext.Current.GetCallbackChannel<IRemoteUserManagerCallback>().FinishedChangingUser(username);

        }
        catch (Exception e)
        {
            string errorString = String.Format("Could not Add User:{0} Sub user:{1}", userInfo.Username, i);
            try
            {
                if (user != null)
                    errorString += "\nSam Name: " + user.SamAccountName;
            }
            catch { }
            OperationContext.Current.GetCallbackChannel<IRemoteUserManagerCallback>().UserException(errorString, e);
        }
        finally
        {
            if (user != null)
                user.Dispose();
        }
    }
}

Stepping through the code I have found that user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); is the expensive call, taking 5-10 seconds per loop.

I found I was having another 5-10 second hit on every GroupPrincipal.FindByIdentity() call too so I moved it out of the loop, the Save() is not expensive. Do you have any other recommendations to help speed this up?

Edit —
The normal case would be the user will exist but it is likely that the sub-user does not exist, but it can exist.

  • 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-05-13T22:41:56+00:00Added an answer on May 13, 2026 at 10:41 pm

    I found a soulution

    private void AddUsers(UserInfo userInfo, InfinityInfo infinityInfo, int subUserStart)
    {
        var userSerach = new UserPrincipal(context);
        userSerach.SamAccountName = userInfo.Username + '*';
        var ps = new PrincipalSearcher(userSerach);
        var pr = ps.FindAll().ToList().Where(a =>
                    Regex.IsMatch(a.SamAccountName, String.Format(@"{0}\D", userInfo.Username))).ToDictionary(a => a.SamAccountName); // removes results like conversons12 from the search conversions1*
        pr.Add(userInfo.Username, Principal.FindByIdentity(context, IdentityType.SamAccountName, userInfo.Username));
        using (GroupPrincipal r = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users"))
        using (GroupPrincipal u = GroupPrincipal.FindByIdentity(context, "Users"))
        for(int i = subUserStart; i < userInfo.SubUsers; ++i)
        {
            string username = userInfo.Username;
            if (i >= 0)
            {
                username += (char)('a' + i);
            }
            UserPrincipal user = null;
            try
            {
                if (userInfo.NewPassword == null)
                    throw new ArgumentNullException("userInfo.NewPassword", "userInfo.NewPassword was null");
                if (userInfo.NewPassword == "")
                    throw new ArgumentOutOfRangeException("userInfo.NewPassword", "userInfo.NewPassword was empty");
                if (pr.ContainsKey(username))
                {
                    user = (UserPrincipal)pr[username];
                    user.Enabled = true;
                    user.SetPassword(userInfo.NewPassword);
                }
                else
                {
                    user = new UserPrincipal(context, username, userInfo.NewPassword, true);
                    user.UserCannotChangePassword = true;
                    user.PasswordNeverExpires = true;
                    user.Save();
                    r.Members.Add(user);
                    u.Members.Add(user);
                    r.Save();
                    u.Save();
                }
                IADsTSUserEx iad = (IADsTSUserEx)((DirectoryEntry)user.GetUnderlyingObject()).NativeObject;
                iad.TerminalServicesInitialProgram = GenerateProgramString(infinityInfo);
                iad.TerminalServicesWorkDirectory = Service.Properties.Settings.Default.StartInPath;
                iad.ConnectClientDrivesAtLogon = 0;
                user.Save();
                OperationContext.Current.GetCallbackChannel<IRemoteUserManagerCallback>().FinishedChangingUser(username);
    
            }
            finally
            {
                if (user != null)
                {
                    user.Dispose();
                }
            }
        }
    }
    

    It adds a few more seconds on the first user but now its about .5 seconds per user after that. The odd calling of the ps.FindAll().ToList().Where(a =>Regex.IsMatch(...))).ToDictionary(a => a.SamAccountName); is because a principle searcher does not cache results. See my question from a few days ago.

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

Sidebar

Ask A Question

Stats

  • Questions 426k
  • Answers 427k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Forr you the best approach is an extension method on… May 15, 2026 at 12:47 pm
  • Editorial Team
    Editorial Team added an answer Just remove string from constructor (not supported) , it should… May 15, 2026 at 12:47 pm
  • Editorial Team
    Editorial Team added an answer printf("The dam would produce %f megawatts at %d%% efficency", &work,… May 15, 2026 at 12:47 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.