提高System.DirectoryServices.AccountManagement性能

3

我有一个程序,可以让我管理我们用于演示软件的终端服务器上的用户。我一直在努力提高将用户添加到系统中的性能(它会添加主帐户,然后如果需要,添加子帐户。例如,如果我有一个名为Demo1的用户和3个子用户,则会创建Demo1、Demo1a、Demo1b和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();
        }
    }
}

在代码中,我发现user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);这行代码很耗时,每次循环需要5-10秒。

我还发现每次调用GroupPrincipal.FindByIdentity()也要花费5-10秒的时间,因此我将它移出了循环,而Save()并不耗时。您有什么其他建议来加快速度吗?

编辑--正常情况下用户会存在,但子用户可能不存在,但有可能存在。

1个回答

3
我找到了一个解决方案。
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();
            }
        }
    }
}

在第一个用户上增加了几秒钟,但之后每个用户大约只需要0.5秒。奇怪的调用ps.FindAll().ToList().Where(a =>Regex.IsMatch(...))).ToDictionary(a => a.SamAccountName);是因为主要搜索器不会缓存结果。请参见我几天前的问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接