示例#1
0
        public void DeleteThisUser()
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain);
            UserPrincipal    up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, SamAccountName);

            up.Delete();
        }
示例#2
0
        public void Delete(string username)
        {
            UserPrincipal usr = null;

            try
            {
                pc = GetPrincipalContext();

                log.DebugFormat("Attempting to retrieve user {0}", username);
                usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, username);

                if (usr != null)
                {
                    usr.Delete();
                    log.InfoFormat("Successfully deleted user {0}", username);
                }
                else
                {
                    log.InfoFormat("Attempted to delete user {0} but could not find the user in Active Directory. Assuming user was manually deleted... continuing...", username);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Failed to delete user {0}. Exception: {1}", username, ex.ToString());
                throw;
            }
            finally
            {
                if (usr != null)
                {
                    usr.Dispose();
                }
            }
        }
示例#3
0
        public Task <Result> RemoveStaffUser(string samAccountName, SpuContext spucontext)
        {
            return(Task.Run(() =>
            {
                try
                {
                    var setup = spucontext.table_setup.FirstOrDefault();

                    PrincipalContext context = new PrincipalContext(ContextType.Domain, setup.Host, "ou=staff," + setup.Base, setup.Username, setup.Password);
                    UserPrincipal principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName);
                    if (principal == null)
                    {
                        return new Result()
                        {
                            result = false, Message = "Account has not found"
                        };
                    }
                    principal.Delete();
                    principal.Save();

                    return new Result()
                    {
                        result = true
                    };
                }
                catch (Exception ex)
                {
                    return new Result()
                    {
                        result = false, Message = ex.Message
                    };
                }
            }));
        }
示例#4
0
        public void Delete()
        {
            #if WINDOWS_USER_ACCOUNT_SUPPORT
            using (var principalContext = new PrincipalContext(ContextType.Machine))
            {
                UserPrincipal principal = null;

                try
                {
                    principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, UserName);
                    if (principal == null)
                    {
                        Console.WriteLine($"The Windows User Account named {UserName} doesn't exist, nothing to do...");
                        return;
                    }
                    Console.WriteLine($"The Windows User Account named {UserName} exists, deleting...");
                    principal.Delete();
                }
                finally
                {
                    principal?.Dispose();
                }
            }
            #endif
        }
        public void TestNegativeCases()
        {
            UserData  u1 = UserData.GenerateUserData("CoreFxUser6");
            GroupData g1 = GroupData.GenerateGroupData("CoreFXGroup6");

            DeleteUser(u1.Name);
            DeleteGroup(g1.Name);

            try
            {
                Assert.Throws <InvalidEnumArgumentException>(() => new PrincipalContext((ContextType)768, null, null, null));
                Assert.Throws <PrincipalServerDownException>(() => new PrincipalContext(ContextType.Domain, "InvalidDomainName", null, null));
                Assert.Throws <ArgumentException>(() => new PrincipalContext(ContextType.Domain, LdapConfiguration.Configuration.ServerName, "InvalidTestUserName", null));
                Assert.Throws <ArgumentException>(() => new PrincipalContext(ContextType.Domain, LdapConfiguration.Configuration.ServerName, LdapConfiguration.Configuration.UserName, null));
                Assert.Throws <ArgumentException>(() => new UserPrincipal(null));
                Assert.Throws <ArgumentException>(() => new GroupPrincipal(null));

                using (PrincipalContext context = DomainContext)
                {
                    using (UserPrincipal user = CreateUser(context, u1))
                        using (GroupPrincipal group = CreateGroup(context, g1))
                        {
                            Assert.Throws <PrincipalExistsException>(() => CreateUser(context, u1));
                            Assert.Throws <PrincipalExistsException>(() => CreateGroup(context, g1));

                            group.Members.Add(context, IdentityType.Name, user.Name);
                            group.Save();
                            Assert.Throws <PrincipalExistsException>(() => group.Members.Add(context, IdentityType.Name, user.Name));
                            group.Members.Remove(context, IdentityType.Name, user.Name);
                            group.Save();

                            user.Delete();
                            Assert.Throws <InvalidOperationException>(() => user.Delete());
                            Assert.Throws <InvalidOperationException>(() => user.Save());

                            group.Delete();
                            Assert.Throws <InvalidOperationException>(() => group.Delete());
                            Assert.Throws <InvalidOperationException>(() => group.Save());
                        }
                }
            }
            finally
            {
                DeleteUser(u1.Name);
                DeleteGroup(g1.Name);
            }
        }
示例#6
0
        /// <summary>
        /// Deletes a local user from the machine
        /// </summary>
        /// <param name="userName">user name to delete</param>
        /// <remarks>Has to be run as an Admin</remarks>
        public static void DeleteLocalUser(string userName)
        {
            UserPrincipal newUser = GetUser(string.Empty, userName);

            if (null != newUser)
            {
                newUser.Delete();
            }
        }
        /// <summary>
        ///     Delete user account with login name
        /// </summary>
        /// <param name="loginName">domain login name</param>
        public void DeleteAccount(string loginName)
        {
            // Find user entry by login name
            UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain,
                                                                   IdentityType.SamAccountName,
                                                                   loginName);

            userEntry.Delete();
            userEntry.Dispose();
        }
示例#8
0
      /// <summary>
      ///
      /// </summary>
      /// <param name="userName"></param>
      public void User_Remove(String userName)
      {
          PrincipalContext ctx  = new PrincipalContext(ContextType.Domain, _LDAPDomainName, _LDAPUser, _LDAPPassword);
          UserPrincipal    user = UserPrincipal.FindByIdentity(ctx, userName);

          user.Delete();
          //DirectoryEntry directoryEntry = User_Get(userName);
          //directoryEntry.Remove["member"].Remove(domainUser);
          //directoryEntry.CommitChanges();
          //directoryEntry.Close();
      }
示例#9
0
        /// <summary>
        /// Deletes user from AD
        /// </summary>
        /// <param name="person">Person object to be deleted</param>
        /// <returns>Success or error</returns>
        public string Delete(Person person)
        {
            if (VerifyToken(GetHeadertoken()).Equals("Authorized"))
            {
                PrincipalContext adContext = EstablishConnection();
                try
                {
                    if (adContext != null)
                    {
                        PrincipalSearcher searcher   = new PrincipalSearcher();
                        UserPrincipal     deleteUser = new UserPrincipal(adContext);
                        deleteUser.EmailAddress = person.Email;
                        searcher.QueryFilter    = deleteUser;
                        UserPrincipal foundUser = (UserPrincipal)searcher.FindOne();

                        if (foundUser != null)
                        {
                            try
                            {
                                foundUser.Delete();
                                log.Info("User '" + person.Email + "' deleted successfully");
                                return("200: User deleted successfully");
                            }
                            catch (Exception e)
                            {
                                log.Error("Exception in Delete user: "******"415: User deletion failed" + e.Message);
                            }
                        }
                        else
                        {
                            log.Error("User not found to delete '" + person.Email + "'");
                            return("404: User not found");
                        }
                    }
                    else
                    {
                        log.Error("Exception in Update user. AD connection failed");
                        return("403: Error while connecting to AD");
                    }
                }
                catch (Exception e)
                {
                    log.Error("Exception in Delete user: "******"Unauthorised");
            }
        }
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _principal.Delete();
            _principal.Dispose();
            _context.Dispose();
            PasswordAsSecureString.Dispose();
            _disposed = true;
        }
示例#11
0
 public void RemoveWindowsAccount(UserPrincipal user)
 {
     try
     {
         user.Delete();
         BatchState.State = UserProcessState.WIN_DELETE_OK;
     }
     catch (Exception ex)
     {
         BatchState.State = UserProcessState.WIN_DELETE_ERROR;
         throw ex;
     }
 }
示例#12
0
        /// <summary>
        /// Deletes a user in Active Directory
        /// </summary>
        /// <param name="sUserName">The username you want to delete</param>
        /// <returns>Returns true if successfully deleted</returns>
        public static bool DeleteUser(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);

                oUserPrincipal.Delete();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#13
0
 /// <summary>
 /// Deletes the specified user account.
 /// </summary>
 /// <param name="name">The unique identifier of the user.</param>
 /// <returns>True if the user was deleted, false if not or the user doesn't exist.</returns>
 public static Boolean DeleteUser(string name)
 {
     try
     {
         UserPrincipal u = UserPrincipal.FindByIdentity(GetPrincipalContext(), name);
         u.Delete();
         u.Save();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
示例#14
0
        private void Button_Click_Remove(object sender, RoutedEventArgs e)
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain, "TEISMAS.AD", "*****@*****.**", "A.dmin123");

            if (username.Text.Length > 3)
            {
                UserPrincipal user = UserPrincipal.FindByIdentity(context, username.Text);

                if (user != null)
                {
                    user.Delete();
                    MessageBox.Show("Vartotojas istrintas sekmingai.");
                }
            }
        }
示例#15
0
 public void Delete(string accountName)
 {
     try
     {
         using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, container))
             using (UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, accountName))
                 if (up != null)
                 {
                     up.Delete();
                 }
     }
     catch (Exception)
     {
     }
 }
        public void Delete()
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
            PrincipalSearchResult <Principal> groups = principal.GetGroups(ctx);

            foreach (var group in groups)
            {
                GroupPrincipal groupPrincipal = (GroupPrincipal)group;

                groupPrincipal.Members.Remove(principal);
                groupPrincipal.Save();
            }

            principal.Delete();
        }
示例#17
0
 //Kullanıcı Silme.
 public void DeleteUser(string samAccountName)
 {
     try
     {
         using (PrincipalContext principialCon = user.BaglantiKur())
             using (UserPrincipal userPrincipial = user.SetPrincipialToFind(principialCon, samAccountName))
             {
                 userPrincipial.Delete();
                 _stateForTest = true;
             }
     }
     catch (Exception)
     {
         _stateForTest = false;
     }
 }
示例#18
0
        public void DeleteUser(string samaccountname)
        {
            if (string.IsNullOrEmpty(samaccountname))
            {
                //o parametro é obrigatorio
                return;
            }

            principalContext = new PrincipalContext(ContextType.Domain, domainName, domainContainer);

            UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, samaccountname);

            if (usr != null)
            {
                usr.Delete();
            }
        }
示例#19
0
        public IActionResult DeleteUser(string Samaccountname)
        {
            //i get the user by its SamaccountName to change his password
            PrincipalContext context = new PrincipalContext(ContextType.Domain, null);
            UserPrincipal    user    = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Samaccountname);

            if ((user.IsMemberOf(GroupPrincipal.FindByIdentity(context, "Admins du domaine"))) || (user.IsMemberOf(GroupPrincipal.FindByIdentity(context, "Administrateurs"))))
            {
                TempData["msg"] = "<script>alert('This user has high privilege ; Log out or try contact the server manager');</script>";
            }
            else
            {
                user.Delete();
                TempData["msg"] = "<script>alert('Delete confirmed');</script>";
            }

            return(RedirectToAction("GetAllUsers"));
        }
示例#20
0
        public void DeleteDomainUser(string userLogonName)
        {
            PrincipalContext principalContext = null;

            principalContext = new PrincipalContext(ContextType.Domain, "yimihaodi.net", "CN=Users,DC=yimihaodi,DC=net");


            UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName);

            if (usr == null)
            {
                return;
            }

            usr.Delete();

            usr.Save();
        }
示例#21
0
 private void DeleteUser(string userName)
 {
     try
     {
         using (PrincipalContext context = DomainContext)
             using (UserPrincipal p = FindUser(userName, context))
             {
                 if (p != null)
                 {
                     p.Delete();
                 }
             }
     }
     catch
     {
         // ignore the failure as we use this method to ensure clean up even if the user not exist
     }
 }
示例#22
0
        public static void DeleteUser(string identity, bool isDryRun = false)
        {
            if (String.IsNullOrWhiteSpace(identity))
            {
                throw new AdException("Identity is not specified.", AdStatusType.MissingInput);
            }

            UserPrincipal userPrincipal = GetUserPrincipal(identity);

            if (userPrincipal != null)
            {
                if (!isDryRun)
                {
                    userPrincipal.Delete();
                }
            }
            else
            {
                throw new AdException($"User [{identity}] cannot be found.", AdStatusType.DoesNotExist);
            }
        }
示例#23
0
        public Result DeleteUser(visual_fim_user model, SpuContext spucontext)
        {
            try
            {
                var setup    = spucontext.table_setup.FirstOrDefault();
                var oufilter = model.system_ou_lvl1.Replace("o=", "ou=") + ",";
                if (!string.IsNullOrEmpty(model.system_ou_lvl2))
                {
                    oufilter = model.system_ou_lvl2.Replace("o=", "ou=") + "," + oufilter;
                }
                if (!string.IsNullOrEmpty(model.system_ou_lvl3))
                {
                    oufilter = model.system_ou_lvl3.Replace("o=", "ou=") + "," + oufilter;
                }

                PrincipalContext context   = new PrincipalContext(ContextType.Domain, setup.Host, oufilter + setup.Base, setup.Username, setup.Password);
                UserPrincipal    principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, model.basic_uid);
                if (principal == null)
                {
                    return(new Result()
                    {
                        result = false, Message = "Account has not found"
                    });
                }
                principal.Delete();
                //principal.Save();

                return(new Result()
                {
                    result = true
                });
            }
            catch (Exception ex)
            {
                return(new Result()
                {
                    result = false, Message = ex.Message
                });
            }
        }
示例#24
0
        public void TestDeleteUserAndGroup()
        {
            UserData  u1 = UserData.GenerateUserData("CoreFxUser5");
            GroupData g1 = GroupData.GenerateGroupData("CoreFXGroup5");

            DeleteUser(u1.Name);
            DeleteGroup(g1.Name);

            try
            {
                using (PrincipalContext context = DomainContext)
                {
                    using (UserPrincipal up = FindUser(u1.Name, context)) { Assert.Null(up); }
                    using (GroupPrincipal gp = FindGroup(g1.Name, context)) { Assert.Null(gp); }

                    using (UserPrincipal user = CreateUser(context, u1))
                        using (GroupPrincipal group = CreateGroup(context, g1))
                        {
                            using (UserPrincipal up = FindUser(u1.Name, context))
                            {
                                Assert.NotNull(up);
                                up.Delete();
                            }
                            using (GroupPrincipal gp = FindGroup(g1.Name, context))
                            {
                                Assert.NotNull(gp);
                                gp.Delete();
                            }
                        }

                    using (UserPrincipal up = FindUser(u1.Name, context)) { Assert.Null(up); }
                    using (GroupPrincipal gp = FindGroup(g1.Name, context)) { Assert.Null(gp); }
                }
            }
            finally
            {
                DeleteUser(u1.Name);
                DeleteGroup(g1.Name);
            }
        }
示例#25
0
        public List <Log> DeleteUsers(List <string> users)
        {
            List <Log>     result = new List <Log>();
            GroupPrincipal group  = null;
            UserPrincipal  user   = null;
            Log            log    = null;

            try
            {
                foreach (string username in users)
                {
                    foreach (string groupname in GetUserGroupNames(username))
                    {
                        group = GroupPrincipal.FindByIdentity(context, groupname);
                        group.Delete();
                        log              = new Log();
                        log.Message      = string.Format("Group[{1}] of user[{0}] deleting complete", user.Name, groupname);
                        log.OccurredTime = DateTime.Now;
                        log.OperatorName = GetType().Name;
                        result.Add(log);
                    }
                    user = UserPrincipal.FindByIdentity(context, username);
                    user.Delete();
                    log              = new Log();
                    log.Message      = string.Format("User[{0}] deleting complete", user.Name, username);
                    log.OccurredTime = DateTime.Now;
                    log.OperatorName = GetType().Name;
                    result.Add(log);
                }
            }
            catch (Exception e)
            {
                log              = new Log();
                log.Message      = string.Format("User[{0}] deleting fault reason : ", e.Message);
                log.OccurredTime = DateTime.Now;
                log.OperatorName = GetType().Name;
                result.Add(log);
            }
            return(result);
        }
示例#26
0
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            if (lbUsers.SelectedItem == null)
            {
                MessageBox.Show("Please select a user");
                return;
            }
            UserPrincipal insUserPrincipal = (UserPrincipal)lbUsers.SelectedItem;

            try
            {
                insUserPrincipal.Delete();
                insUserPrincipal.Dispose();
                MessageBox.Show("User deleted.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            ListUsers();
        }
示例#27
0
        /// <summary>
        /// This method will remove (delete) the user, if exists.
        /// </summary>
        /// <param name="s">User information</param>
        /// <param name="login">Login information to Active Directory.</param>
        /// <returns>Deleted user's email address.</returns>
        public BaseResponse <string> RemoveUser(UserInfoModel s)
        {
            ADResponseType rt;
            string         rResult    = string.Empty;
            string         rMessage   = string.Empty;
            Exception      rException = null;
            ADLoginModel   login      = GetAdminActiveDirectoryLogin();

            try
            {
                PrincipalContext pc   = new PrincipalContext(ContextType.Domain, login.Domain, login.Username, login.Password);
                UserPrincipal    user = UserPrincipal.FindByIdentity(pc, s.DomainEmailAddress);
                if (user != null)
                {
                    user.Delete();
                    rt      = ADResponseType.OK;
                    rResult = s.DomainEmailAddress;
                }
                else
                {
                    rMessage = "User does not exist.";
                    rt       = ADResponseType.Undefined;
                }
            }
            catch (System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException E)
            {
                rMessage   = "Unable to perform operation.";
                rt         = ADResponseType.Exception;
                rException = E;
            }
            catch (System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException E)
            {
                rMessage   = "User was not found.";
                rt         = ADResponseType.Exception;
                rException = E;
            }
            return(new BaseResponse <string>(rResult, rt, rMessage, rException));
        }
        public bool DeleteLocalUserAccount(string userName)
        {
            try
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
                {
                    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);

                    if (user == null)
                    {
                        throw new ApplicationException("User " + userName + " Not Found");
                    }
                    else
                    {
                        user.Delete();
                    }
                }
            }
            catch (Exception ex)
            { SetError(ex.Message); }

            return(!IsError);
        }
示例#29
0
 public static void RemoveUserAndProfile(string user)
 {
     using (UserPrincipal userPrincipal = GetUserPrincipal(user))
     {
         // First we have to work out where the users profile is on disk.
         try
         {
             string usersProfileDir = Abstractions.Windows.User.GetProfileDir(userPrincipal.Sid);
             if (!string.IsNullOrEmpty(usersProfileDir))
             {
                 m_logger.DebugFormat("User {0} has profile in {1}, giving myself delete permission", user, usersProfileDir);
                 RecurseDelete(usersProfileDir);
                 // Now remove it from the registry as well
                 Abstractions.WindowsApi.pInvokes.DeleteProfile(userPrincipal.Sid);
             }
         }
         catch (KeyNotFoundException)
         {
             m_logger.DebugFormat("User {0} has no disk profile, just removing principal", user);
         }
         userPrincipal.Delete();
     }
 }
示例#30
0
        /// <summary>
        /// Deletes a user from the system
        /// </summary>
        /// <param name="userPrincipalName"></param>
        public void DeleteUser(string userPrincipalName)
        {
            PrincipalContext pc = null;
            UserPrincipal    up = null;

            try
            {
                pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);

                logger.Debug("Looking to see if user already exists: " + userPrincipalName);

                up = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, userPrincipalName);
                if (up != null)
                {
                    up.Delete();

                    logger.Info("Deleted user " + userPrincipalName);
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("Error deleting user " + userPrincipalName, ex);
                throw;
            }
            finally
            {
                if (up != null)
                {
                    up.Dispose();
                }

                if (pc != null)
                {
                    pc.Dispose();
                }
            }
        }