Improving performance of System.DirectoryServices.AccountManagement

主宰稳场 提交于 2019-12-01 06:14:46

问题


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:


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.



来源:https://stackoverflow.com/questions/2409432/improving-performance-of-system-directoryservices-accountmanagement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!