当前位置: 首页>>代码示例>>C#>>正文


C# UserPrincipal.Dispose方法代码示例

本文整理汇总了C#中System.DirectoryServices.AccountManagement.UserPrincipal.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# UserPrincipal.Dispose方法的具体用法?C# UserPrincipal.Dispose怎么用?C# UserPrincipal.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.DirectoryServices.AccountManagement.UserPrincipal的用法示例。


在下文中一共展示了UserPrincipal.Dispose方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ChangePassword

 // Adapted from http://www.snippetdirectory.com/csharp/changing-password-of-a-local-or-domain-user/
 public bool ChangePassword(string username, string oldpass, string newpass)
 {
     PrincipalContext insPrincipalContext = null;
     if (this.options.Keys.Contains("location") && this.options["location"] == "local")
     {
         insPrincipalContext = new PrincipalContext(ContextType.Machine);//Connecting to local computer.
     }
     else if (this.options.Keys.Contains("location") && this.options["location"] == "domain")
     {
         insPrincipalContext = new PrincipalContext(ContextType.Domain, this.options["domain"], this.options["ads"]);//Connecting to Active Directory
     }
     UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
     insUserPrincipal.Name = username;
     PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
     insUserPrincipal = insPrincipalSearcher.FindOne() as UserPrincipal;
     insUserPrincipal.SetPassword(newpass);
     insUserPrincipal.Save();
     insUserPrincipal.Dispose();
     return true;
 }
开发者ID:nadams810,项目名称:accountmanagementengine,代码行数:21,代码来源:WindowsEngine.cs

示例2: CreateUser

      internal static void CreateUser(BplIdentity id, LoginContact contact, string password, Action<RegistrationResult, string> onFinished) {
         //cleanup role
         var loginName = _getName(contact);
         if (loginName.IsEmpty() || password.IsEmpty()) {
            onFinished(RegistrationResult.InvalidInformation, null);
         } else {
            try {
               //register in AD
               using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
                  var result = RegistrationResult.Success;
                  try {
                     var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName);
                     if (up != null) {
                        result = up.Enabled == true ? RegistrationResult.ClientAlreadyRegistered : RegistrationResult.ClientBlocked;
                     } else {
                        up = new UserPrincipal(context);
                        up.SamAccountName = loginName;
                        //TK: Consider duplication on up.UserPrincipalName
                        up.Name = (string)id.LocalId; //TODO: Consider not only for drivers. Local ID can be not unique.
                        if (contact.LoginKind == LoginKind.Email) {
                           up.EmailAddress = contact.LoginValue;
                        } else { 
                           //this is phone number
                           up.VoiceTelephoneNumber = contact.LoginValue;
                        }
                        up.Save();

                        object pgid = null;

                        var gpOscar = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, _usersGroup);
                        if (gpOscar != null) {
                           var grp = (DirectoryEntry)gpOscar.GetUnderlyingObject();
                           grp.Invoke("GetInfoEx", new object[] { new object[] { "primaryGroupToken" }, 0 });
                           pgid = grp.Invoke("Get", new object[] { "primaryGroupToken" });
                           grp.Properties["member"].Add(up.DistinguishedName);
                           grp.CommitChanges();
                           grp.Close();
                        } else {
                           throw new ApplicationException("Unable to get and assign valid group {0}".Substitute(_usersGroup));
                        }                        

                        //this is how we are doing impersonation
                        using (var entry = new DirectoryEntry("LDAP://{0}/{1}".Substitute(ADServer, up.DistinguishedName), ADUsername, ADPassword)) {
                           //TK: consider using reg code -> entry.Properties["uid"].Value = request.RegistrationCode;
                           if (pgid != null) {
                              entry.Properties["primaryGroupID"].Value = pgid;
                           }

                           entry.Invoke("SetPassword", new object[] { password });
                           entry.CommitChanges();

                           using (var gContext = new PrincipalContext(ContextType.Domain, ADServer, ADGlobalContainer, ADUsername, ADPassword)) {
                              var gpUsers = GroupPrincipal.FindByIdentity(gContext, "Domain Users");
                              if (gpUsers != null) {
                                 var grp = (DirectoryEntry)gpUsers.GetUnderlyingObject();
                                 grp.Properties["member"].Remove(up.DistinguishedName);
                                 grp.CommitChanges();
                                 grp.Close();
                              } else {
                                 throw new ApplicationException("Unable to remove user from domain default group.");
                              }
                           }
                        }


                        up.Enabled = true;
                        up.Save();

                        result = up.Enabled == true ? RegistrationResult.Success : RegistrationResult.Failure;
                        up.Dispose();
                        up = null;
                        Log.Info("User {0} registered in AD", loginName);
                     }
                     onFinished(result, loginName);
                  } catch (Exception e) {
                     //check and cleanup user if it is
                     using (var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) {
                        if (up != null && up.Enabled != true) {
                           up.Delete();
                        }
                     }
                     onFinished(RegistrationResult.Failure, null);
                     Log.Exception(e, "Unable to register user in active directory");
                  }
               }
            } catch (Exception dx) {
               onFinished(RegistrationResult.Failure, null);
               Log.Exception(dx, "Unable to connect to active directory");
            }
         }

      }
开发者ID:borkaborka,项目名称:gmit,代码行数:92,代码来源:AuthServices.cs

示例3: Create

        public User Create(User user)
        {
            try
            {
                string ClientPrefix = GetClientPrefix();
                string ClientName = GetClientName(GetClientDN());

                user.UserName = ClientPrefix + '.' + ToASCII(user.FirstName.Split(' ')[0].ToLower()) + '.' + ToASCII(user.LastName.Split(' ')[0].ToLower());
                if (user.UserName.Length >= 20)
                {
                    user.UserName = user.UserName.Substring(0, 20);
                }
                user.Password = GeneratePassword();

                // Create a confined context using the client's Organization Unit 
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Domain"], GetClientDN()))
                {
                    // Create the user
                    UserPrincipal NewUser = new UserPrincipal(context);
                    NewUser.GivenName = user.FirstName;
                    NewUser.Surname = user.LastName;
                    NewUser.Name = user.FirstName + ' ' + user.LastName;
                    NewUser.DisplayName = user.FirstName + ' ' + user.LastName;
                    NewUser.SamAccountName = user.UserName;
                    NewUser.UserPrincipalName = user.UserName + '@' + ConfigurationManager.AppSettings["Domain"];
                    NewUser.EmailAddress = user.EmailAddress;
                    if (user.Description != "")
                    {
                        NewUser.Description = user.Description;
                    }
                    NewUser.SetPassword(user.Password);
                    NewUser.Enabled = user.IsEnabled;
                    NewUser.Save();
                    NewUser.Dispose();

                    // Add the user to the client's security group
                    GroupPrincipal ClientSecurityGroup = GroupPrincipal.FindByIdentity(context, ClientName);
                    ClientSecurityGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                    ClientSecurityGroup.Save();
                }

                // If the user has been marked as administrator, add it to the administrator group
                if (user.IsAdmin)
                {
                    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                    {
                        GroupPrincipal AdminGroup = GroupPrincipal.FindByIdentity(context, ConfigurationManager.AppSettings["AdminGroupName"]);
                        AdminGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                        AdminGroup.Save();
                    }
                }
                return user;
            }
            catch (Exception Error)
            {
                throw Error;
            }
        }
开发者ID:lovis-holdings,项目名称:lovis.management,代码行数:58,代码来源:User.cs

示例4: UserPrincipalConstructorTest

 public void UserPrincipalConstructorTest()
 {
     UserPrincipal user = new UserPrincipal(domainContext);
     user.Dispose();
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
开发者ID:chcosta,项目名称:corefx,代码行数:6,代码来源:UserPrincipalTest.cs

示例5: AgregarUsuario

        /// <summary>
        /// Agrega un nuevo usuario
        /// </summary>
        /// <param name="nombre">Nombre del usuario</param>
        /// <param name="contraseña">Contraseña</param>
        /// <param name="descripción">Descripción de usuario</param>
        public void AgregarUsuario(string nombre, string contraseña, string descripción)
        {
            UserPrincipal nuevoUsuario = new UserPrincipal(_dominio);

            nuevoUsuario.Name = nombre;
            nuevoUsuario.SetPassword(contraseña);
            nuevoUsuario.Description = descripción;

            nuevoUsuario.Save();
            nuevoUsuario.Dispose();
        }
开发者ID:alonsovb,项目名称:ad-manager,代码行数:17,代码来源:ADAdministrador.cs

示例6: InnerCreateUser

        private LocalPrincipalData InnerCreateUser(string userName)
        {
            string rvUserName = null;
            string rvPassword = null;
            LocalPrincipalData rv = null;

            using (var context = new PrincipalContext(ContextType.Machine))
            {
                bool userSaved = false;
                ushort tries = 0;
                UserPrincipal user = null;

                try
                {
                    do
                    {
                        try
                        {
                            if (user != null)
                            {
                                user.Dispose();
                            }

                            rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant();
                            user = new UserPrincipal(context, userName, rvPassword, true);
                            user.DisplayName = "Warden User " + userName;
                            user.Save();
                            userSaved = true;
                        }
                        catch (PasswordException ex)
                        {
                            log.DebugException(ex);
                        }

                        ++tries;
                    } while (userSaved == false && tries < 5);

                    if (userSaved)
                    {
                        rvUserName = user.SamAccountName;

                        foreach (string userGroupName in this.wardenUserGroups)
                        {
                            AddUserToGroup(rvUserName, userGroupName);
                        }

                        rv = new LocalPrincipalData(rvUserName, rvPassword);
                    }
                }
                finally
                {
                    if (user != null)
                        user.Dispose();
                }
            }

            return rv;
        }
开发者ID:stefanschneider,项目名称:IronFrame,代码行数:58,代码来源:LocalPrincipalManager.cs


注:本文中的System.DirectoryServices.AccountManagement.UserPrincipal.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。