Exemplo n.º 1
0
        public static void AddUsersToThisGroup(string groupName, List <string> userNames)
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain);
            GroupPrincipal   gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName);

            if (gp == null)
            {
                return;
            }

            // eerst alle gebruikers wissen uit deze groep
            gp.Members.Clear();
            gp.Save();



            // nu alle gebruikers uit de lijst opnieuw toevoegen
            foreach (string userName in userNames)
            {
                UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
                if (up == null)
                {
                    continue;
                }
                gp.Members.Add(up);
                gp.Save();
            }
        }
Exemplo n.º 2
0
        public static bool EmptyGroup(string groupname, AdAdminConfig config)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                                        config.ServerIpOrDomain,
                                                        config.AdminAccount,
                                                        config.AdminPwd);
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);

            if (group != null)
            {
                foreach (Principal p in group.GetMembers())
                {
                    UserPrincipal theUser = p as UserPrincipal;
                    if (theUser != null)
                    {
                        group.Members.Remove(theUser);
                        try
                        {
                            group.Save();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 3
0
        public ActionResult Create(UserViewModel model)
        {
            if (false == ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                Alue71UserPrincipal newUser = new Alue71UserPrincipal(_context);
                model.DisplayName    = model.GivenName;
                model.Name           = model.GivenName + " " + model.Surname;
                model.Email          = model.GivenName + "." + model.Surname + "@alue71.local";
                model.SamAccountName = model.GivenName.ToLower() + model.Surname.ToLower();
                newUser.UpdateFromModel(model);
                newUser.SetPassword("admin");
                newUser.ExpirePasswordNow();
                newUser.Enabled = true;
                newUser.Save();

                GroupPrincipal grp = GroupPrincipal.FindByIdentity(_context, "WebNormaali");

                if (grp != null)
                {
                    grp.Members.Add(newUser);
                    grp.Save();
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ViewBag.message = ex.Message;
                return(View(model));
            }
        }
Exemplo n.º 4
0
        private void AddUserToWiFi(string[] Usernames)
        {
            try
            {
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "INTERNET.LOCAL"))
                {
                    GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "Guest-WiFi");
                    foreach (string user in Usernames)
                    {
                        try
                        {
                            group.Members.Add(pc, IdentityType.SamAccountName, user);

                            //only runs if no exception caught
                            Output(string.Format("+ {0} blev tilføjet til Guest-WiFi", user));
                        }
                        catch (PrincipalExistsException)
                        {
                            Output(string.Format("- {0} er allerede medlem af Guest-WiFi", user));
                        }
                        catch (NoMatchingPrincipalException)
                        {
                            Output(string.Format("% {0} findes ikke", user));
                        }
                    }
                    group.Save();
                }
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                Output(E.Message.ToString());
            }
        }
Exemplo n.º 5
0
        public bool createGroup(string name)
        {
            using (PrincipalContext ouContex = new PrincipalContext(ContextType.Domain,
                                                                    Domain,
                                                                    "OU=Personas,DC=UCB,DC=BO",
                                                                    "ADMNALRRHH",
                                                                    "Rrhh1234"))
            {
                ouContex.ValidateCredentials("ADMNALRRHH", "Rrhh1234");
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ouContex, name);
                if (group == null)
                {
                    using (GroupPrincipal up = new GroupPrincipal(ouContex))
                    {
                        up.IsSecurityGroup = false;
                        up.Name            = name;
                        up.DisplayName     = name;
                        up.GroupScope      = GroupScope.Global;
                        up.Save();
                    }

                    return(true);
                }

                return(false);
            }
        }
Exemplo n.º 6
0
        public void ShouldAddUserToGroup()
        {
            var groupName = "CIdentityTest";

            using (var ctx = new PrincipalContext(ContextType.Machine))
            {
                using (var group = GroupPrincipal.FindByIdentity(ctx, groupName))
                {
                    if (group == null)
                    {
                        using (var newGroup = new GroupPrincipal(ctx, groupName))
                        {
                            newGroup.Description = string.Format("Group created by {0} test fixture.", typeof(IdentityTest).FullName);
                            newGroup.Save();
                        }
                    }
                }

                try
                {
                    var id = Identity.FindByName(string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName));
                    id.AddToLocalGroup(groupName);
                }
                finally
                {
                    using (var group = GroupPrincipal.FindByIdentity(ctx, "CIdentityTest"))
                        if (group != null)
                        {
                            group.Delete();
                        }
                }
            }
        }
        /// <summary>
        /// Adds the user to the specified group
        /// </summary>
        /// <param name="adUser">User to add</param>
        /// <param name="groupName">Group to which the user should be added</param>
        public void AddUserToGroup(UserPrincipal adUser, string groupName)
        {
            GroupPrincipal g = GetOrCreate(groupName);

            g.Members.Add(adUser);
            g.Save();
        }
        /// <summary>
        /// Adds the user for a given group
        /// </summary>
        /// <param name="sUserName">The user you want to add to a group</param>
        /// <param name="sGroupName">The group you want the user to be added in</param>
        /// <returns>Returns true if successful</returns>
        public bool AddUserToGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal  oUserPrincipal  = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal == null || oGroupPrincipal == null)
                {
                    return(false);
                }

                if (!IsUserGroupMember(sUserName, sGroupName))
                {
                    oGroupPrincipal.Members.Add(oUserPrincipal);
                    oGroupPrincipal.Save();
                }


                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Retire une machine dans un groupe donné.
 /// </summary>
 /// <param name="groupName"></param>
 /// <param name="computerName"></param>
 public void RemoveComputerToGroup(string groupName, string computerName)
 {
     try
     {
         using (GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName))
         {
             if (group != null)
             {
                 ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(_adConnection, IdentityType.Name, computerName);
                 if (computer != null)
                 {
                     Logger?.Info("Ajout de PC : " + computerName + " dans le groupe " + groupName);
                     group.Members.Remove(computer);
                     group.Save();
                 }
                 else
                 {
                     Logger?.Warn("Le PC : " + computerName + " n'existe pas !");
                 }
             }
             else
             {
                 Logger?.Warn("Le groupe : " + groupName + " n'existe pas !");
             }
         }
     }
     catch (Exception exception)
     {
         Logger?.Error("Error RemoveComputerToGroup - groupName : " + groupName
                       + " - computerName : " + computerName, exception);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Retire un utilisateur dans un groupe donné.
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="user"></param>
        public void RemoveUserToGroup(GroupPrincipal group, UserPrincipal user)
        {
            try
            {
                if (group.Members.Contains(user))
                {
                    Logger?.Info("Suppresion de " + user.Name + " du groupe " + group.Name);

                    group.Members.Remove(user);
                    group.Save();
                }
                else
                {
                    Logger?.Warn(user.Name + " n'est pas dans le groupe " + group.Name);
                    throw new UserNotInGroupException(user.Name + " n'est pas dans le groupe " + group.Name);
                }
            }
            catch (Exception exception)
            {
                Logger?.Error("Error RemoveUserToGroup - groupName : " + group.Name
                              + " - userName : " + user.Name, exception);

                throw;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Ajout un utilisateur dans un groupe donné.
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="user"></param>
        public void AddUserToGroup(string groupName, UserPrincipal user)
        {
            try
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName);

                if (group != null)
                {
                    if (!group.Members.Contains(user))
                    {
                        Logger?.Info("Ajout de " + user.Name + " dans le groupe " + groupName);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                    }
                    else
                    {
                        Logger?.Warn(user.Name + " est déjà dans le groupe " + groupName);
                        throw new UserExistInGroupException(user.Name + " est déjà dans le groupe " + groupName);
                    }
                }
                else
                {
                    Logger?.Warn("Le groupe : " + groupName + " n'existe pas !");
                    throw new GroupActiveDirectoryNotExistException("Le groupe : " + groupName + " n'existe pas !");
                }
            }
            catch (Exception exception)
            {
                Logger?.Error("Error AddUserToGroup - groupName : " + groupName
                              + " - userName : " + user.Name, exception);

                throw;
            }
        }
Exemplo n.º 12
0
        public void AddMember(string groupId, string userId)
        {
            using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
            {
                using (UserPrincipal user = UserPrincipal.FindByIdentity(context, userId))
                {
                    using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupId))
                    {
                        if (user == null || group == null)
                        {
                            log.Error("User or group does not exist: " + userId + " / " + groupId);
                            return;
                        }

                        log.Info("Added " + userId + " to " + group.Name);

                        try {
                            group.Members.Add(user);
                            group.Save();
                        }
                        catch (PrincipalExistsException)
                        {
                            log.Warn("User " + userId + " was already a member of the group");
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
        public void RemoveMember(string groupId, string userId)
        {
            using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
            {
                using (UserPrincipal user = UserPrincipal.FindByIdentity(context, userId))
                {
                    using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupId))
                    {
                        if (user == null || group == null)
                        {
                            log.Error("User or group does not exist: " + userId + " / " + groupId);
                            return;
                        }

                        if (group.Members.Remove(user))
                        {
                            log.Info("Removed " + userId + " from " + group.Name);
                            group.Save();
                        }
                        else
                        {
                            log.Warn("Could not remove " + userId + " from " + group.Name);
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 添加账户
        /// </summary>
        /// <param name="userName">用户</param>
        /// <param name="passWord">密码</param>
        /// <param name="displayName">名称</param>
        /// <param name="description">描述</param>
        /// <param name="groupName">组</param>
        /// <param name="canChangePwd">可以更改密码</param>
        /// <param name="pwdExpires">密码永不过期</param>
        /// <param name="ip"></param>
        /// <returns></returns>
        static Result CreateLocalWindowsAccount(string userName, string passWord, string displayName, string description, string groupName = "Users", bool canChangePwd = false, bool pwdExpires = true, string ip = null)
        {
            bool retIsSuccess = false;

            try
            {
                PrincipalContext context = new PrincipalContext(ContextType.Machine);
                UserPrincipal    user    = new UserPrincipal(context);
                user.SetPassword(passWord);
                user.DisplayName = displayName;
                user.Name        = userName;
                user.Description = description;
                user.UserCannotChangePassword = canChangePwd;
                user.PasswordNeverExpires     = pwdExpires;
                user.Save();
                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);
                group.Members.Add(user);
                group.Save();
                return(new Result()
                {
                    Status = true,
                    Message = "添加成功"
                });
            }
            catch (Exception ex)
            {
                return(new Result()
                {
                    Status = false,
                    Message = ex.Message
                });
            }
        }
Exemplo n.º 15
0
        public static bool AddUserToGroup(string samAccountName, string groupName, AdAdminConfig config)
        {
            if (IfUserExist(samAccountName, config))
            {
                if (!IfUserExistInGroup(samAccountName, groupName, config))
                {
                    try
                    {
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                                                    config.ServerIpOrDomain,
                                                                    config.AdminAccount,
                                                                    config.AdminPwd);
                        // find the group in question
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                        UserPrincipal  user  = UserPrincipal.FindByIdentity(ctx, samAccountName);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                        user.Dispose();
                        ctx.Dispose();
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }

                    return(true);
                }

                return(false);
            }

            return(false);
        }
        private static bool CreateLocalWindowsAccount(string userName, string passWord, string displayName, string description, string groupName, bool canChangePwd, bool pwdExpires)
        {
            bool retIsSuccess = false;

            try
            {
                PrincipalContext context = new PrincipalContext(ContextType.Machine);
                UserPrincipal    user    = new UserPrincipal(context);
                user.SetPassword(passWord);
                user.DisplayName = displayName;
                user.Name        = userName;
                user.Description = description;
                user.UserCannotChangePassword = canChangePwd;
                user.PasswordNeverExpires     = pwdExpires;
                user.Save();

                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);
                group.Members.Add(user);
                group.Save();
                retIsSuccess = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                retIsSuccess = false;
            }
            return(retIsSuccess);
        }
        private static GroupPrincipal CreateGroup(string groupName, Boolean isSecurityGroup)
        {
            GroupPrincipal retGroup = null;

            try
            {
                retGroup = IsGroupExist(groupName);
                if (retGroup == null)
                {
                    PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
                    GroupPrincipal   insGroupPrincipal = new GroupPrincipal(ctx);
                    insGroupPrincipal.Name            = groupName;
                    insGroupPrincipal.IsSecurityGroup = isSecurityGroup;
                    insGroupPrincipal.GroupScope      = GroupScope.Local;
                    insGroupPrincipal.Save();
                    retGroup = insGroupPrincipal;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(retGroup);
        }
Exemplo n.º 18
0
        // This method will add the users to the appropriate "computer groups" they
        // have been authorized on.
        // WARNING! The assumption is that the name of the authorization in Wild Apricot
        // is *exactly* the same name as the OU in Active Directory. In other words, if
        // the user is authorized in "Boss Authorized Users" in WA, then the name of the
        // OU in Active Directory *must* be "Boss Authorized Users".
        private void addUserToGroups(string sectionName, ref UserPrincipal userPrincipal, Member member)
        {
            FieldValue authGroups = getValueForKey(member, sectionName);

            if (authGroups != null)
            {
                JArray authsObj = (JArray)authGroups.Value;
                if (authsObj != null && authsObj.Count() > 0)
                {
                    for (int x = 0; x < authsObj.Count(); ++x)
                    {
                        JToken auth = authsObj[x];

                        string groupName = auth.Value <string>("Label");
                        Console.WriteLine("Going to add to the " + groupName + " group");
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(this.pc, groupName);

                        try
                        {
                            group.Members.Add(this.pc, IdentityType.SamAccountName, userPrincipal.SamAccountName);
                            group.Save();
                        }
                        catch (System.DirectoryServices.AccountManagement.PrincipalExistsException pe)
                        {
                            Console.WriteLine("...but the user is already in the group");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Removes the user from the specified group
        /// </summary>
        /// <param name="adUser">User to remove</param>
        /// <param name="groupName">Group from which the user should be removed</param>
        public void RemoveUserFromGroup(UserPrincipal adUser, string groupName)
        {
            GroupPrincipal g = GroupPrincipal.FindByIdentity(_GlobalContext, groupName);

            g.Members.Remove(adUser);
            g.Save();
        }
Exemplo n.º 20
0
        //const string USERNAME = "******"; // Machine Name!

        static void Main(string[] args)
        {
            //NetUserDel("", USERNAME);
            USER_INFO_1 newuser = new USER_INFO_1()
            {
                sComment     = DESCRIPTION,
                sUsername    = USERNAME,
                sPassword    = PASSWORD,
                sHome_Dir    = "",
                sScript_Path = "",
                uiPriv       = USER_PRIV_USER,
                uiFlags      = UF_WORKSTATION_TRUST_ACCOUNT
            };

            Console.WriteLine(string.Format("Adding {0} user to system with password {1}, please wait...", USERNAME, PASSWORD));
            NetUserAdd("", 1, newuser, out uint parm_err);
            Console.WriteLine("User added!");
            Console.WriteLine("Enumerating Administrators group, please wait...");
            GroupPrincipal gp = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine, null), "Administrators");

            Console.WriteLine("Found Administrators group.");
            Console.WriteLine("Enumerating new user, please wait...");
            UserPrincipal up = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine, null), USERNAME);

            Console.WriteLine("Found the new user.");
            Console.WriteLine(string.Format("Adding {0} to Administrators group, please wait...", USERNAME));
            gp.Members.Add(up);
            gp.Save();
            Console.WriteLine("All Done! Hack the planet!");
        }
Exemplo n.º 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            PrincipalContext context2 = new PrincipalContext(ContextType.Domain, "gbl.ad.hedani.net", "OU=BR,OU=CS,DC=gbl,DC=ad,DC=hedani,DC=net");
            PrincipalContext context  = new PrincipalContext(ContextType.Domain, "csfb.cs-group.com", "OU=GroupsLocal,OU=SAO,OU=FAO,DC=csfb,DC=cs-group,DC=com");


            foreach (var linha in richTextBox3.Lines)
            {
                UserPrincipal user = UserPrincipal.FindByIdentity(context2, richTextBox3.Text);
                foreach (var line in richTextBox1.Lines)
                {
                    if (line != "")
                    {
                        try
                        {
                            GroupPrincipal group = GroupPrincipal.FindByIdentity(context, line);
                            group.Members.Add(user);
                            group.Save();
                            richTextBox2.AppendText("Usuario: " + user + " adicionado ao grupo" + line + "\n");
                        }
                        catch (Exception x)
                        {
                            MessageBox.Show(x.Message);
                        }
                    }
                    Microsoft.Office.Interop.Outlook.Application app      = new Microsoft.Office.Interop.Outlook.Application();
                    Microsoft.Office.Interop.Outlook.MailItem    mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                    mailItem.To      = "*****@*****.**";
                    mailItem.Subject = "AD Log - " + Environment.UserName + " - " + hoje;
                    mailItem.Body    = richTextBox2.Text;
                    mailItem.Send();
                }
            }
        }
Exemplo n.º 22
0
        private GroupPrincipal CreateOrGetGroupPrincipal(GroupInformation groupInfo)
        {
            GroupPrincipal group = null;

            // If we have a SID, use that, otherwise name
            group = GetGroupPrincipal(groupInfo.Name);

            if (group == null)
            {
                // We create the GroupPrincipal, but https://connect.microsoft.com/VisualStudio/feedback/details/525688/invalidoperationexception-with-groupprincipal-and-sam-principalcontext-for-setting-any-property-always
                // prevents us from then setting stuff on it.. so we then have to locate its relative DE
                // and modify *that* instead.  Oi.
                using (group = new GroupPrincipal(m_machinePrincipal))
                {
                    group.Name = groupInfo.Name;
                    group.Save();

                    using (DirectoryEntry newGroupDe = m_sam.Children.Add(groupInfo.Name, "Group"))
                    {
                        if (!string.IsNullOrEmpty(groupInfo.Description))
                        {
                            newGroupDe.Properties["Description"].Value = groupInfo.Description;
                            newGroupDe.CommitChanges();
                        }
                    }

                    // We have to re-fetch to get changes made via underlying DE
                    return(GetGroupPrincipal(group.Name));
                }
            }

            return(group);
        }
Exemplo n.º 23
0
        public void TestUpdateUserAndGroupData()
        {
            UserData  u1 = UserData.GenerateUserData("CoreFxUser7");
            GroupData g1 = GroupData.GenerateGroupData("CoreFXGroup7");

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

            try
            {
                using (PrincipalContext context = DomainContext)
                    using (UserPrincipal user = CreateUser(context, u1))
                        using (GroupPrincipal group = CreateGroup(context, g1))
                        {
                            using (UserPrincipal up = FindUser(u1.Name, context)) { Assert.Equal(user.DisplayName, up.DisplayName); }
                            using (GroupPrincipal gp = FindGroup(g1.Name, context)) { Assert.Equal(group.DisplayName, gp.DisplayName); }

                            user.DisplayName = "Updated CoreFx Test Child User 4";

                            user.Save();
                            group.DisplayName = "Updated CoreFX Test Group Container 4";
                            group.Save();

                            using (UserPrincipal up = FindUser(u1.Name, context)) { Assert.Equal("Updated CoreFx Test Child User 4", up.DisplayName); }
                            using (GroupPrincipal gp = FindGroup(g1.Name, context)) { Assert.Equal("Updated CoreFX Test Group Container 4", gp.DisplayName); }
                        }
            }
            finally
            {
                DeleteUser(u1.Name);
                DeleteGroup(g1.Name);
            }
        }
 public static bool CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
 {
     try
     {
         PrincipalContext context = new PrincipalContext(ContextType.Machine);
         UserPrincipal    user    = new UserPrincipal(context);
         user.SetPassword(password);
         user.DisplayName = displayName;
         user.Name        = username;
         user.Description = description;
         user.UserCannotChangePassword = canChangePwd;
         user.PasswordNeverExpires     = pwdExpires;
         user.Save();
         //now add user to "Users" group so it displays in Control Panel
         GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users");
         group.Members.Add(user);
         group.Save();
         return(true);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error creating account: {0}", ex.Message);
         return(false);
     }
 }
Exemplo n.º 25
0
 private void RemoveUserFromGroup(string domainName, string userId, string groupName)
 {
     if (userId == "")
     {
         MessageBox.Show("BlankUsername");
     }
     try
     {
         using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName))
         {
             GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
             group.Members.Remove(pc, IdentityType.SamAccountName, userId);
             group.Save();
         }
     }
     catch (System.DirectoryServices.AccountManagement.NoMatchingPrincipalException e)
     {
         MessageBox.Show("cant find that user");
     }
     catch (UnauthorizedAccessException e)
     {
         MessageBox.Show(Properties.Resources.ErrorMsg, e.Message);
     }
     catch (System.DirectoryServices.DirectoryServicesCOMException E)
     {
         MessageBox.Show(Properties.Resources.ErrorMsg, E.Message);
     }
 }
Exemplo n.º 26
0
        private void btnEditGroup_Click(object sender, EventArgs e)
        {
            if (lbGroups.SelectedItem == null)
            {
                MessageBox.Show("Please select a group");
                return;
            }
            GroupPrincipal insGroupPrincipal = (GroupPrincipal)lbGroups.SelectedItem;
            frmProperties  insFrmProperties  = new frmProperties(insGroupPrincipal, ActionTypes.Save);

            insFrmProperties.ShowDialog();
            if (insFrmProperties.DialogResult == DialogResult.OK)
            {
                try
                {
                    insGroupPrincipal.Save();
                    insGroupPrincipal.Dispose();
                    MessageBox.Show("Group updated.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                ListGroups();
            }
        }
        public static void UpdateExistingUserGroupMembership(string sAMAccountName, List <string> groepnamen)
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain);
            UserPrincipal    up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, sAMAccountName);

            // eerst gebruiker uit al zijn groepen verwijderen
            foreach (GroupPrincipal gp in up.GetGroups())
            {
                if (gp.Name == "Domain Users")
                {
                    continue;
                }
                gp.Members.Remove(up);
                try
                {
                    gp.Save();
                }
                catch { }
            }
            // gebruiker terug toevoegen aan de groepen waartoe hij hoort
            foreach (string groepnaam in groepnamen)
            {
                GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groepnaam);
                if (gp != null)
                {
                    gp.Members.Add(up);
                    try
                    {
                        gp.Save();
                    }
                    catch { }
                }
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            setComputerRestrictions.MouseLeftButtonDown += new MouseButtonEventHandler(computerRestrictions_Click);
            scheduleUpdate.MouseLeftButtonDown          += new MouseButtonEventHandler(scheduleUpdate_Click);
            protectDisk.MouseLeftButtonDown             += new MouseButtonEventHandler(protectDisk_Click);
            ctx = new PrincipalContext(ContextType.Machine);

            //Sprawdź czy jest grupa Shared jak nie to stwórz
            if ((groupPrincipal = GroupPrincipal.FindByIdentity(ctx, "Shared")) == null)
            {
                groupPrincipal             = new GroupPrincipal(ctx, "Shared");
                groupPrincipal.Description = "Group for shared profiles";

                try
                {
                    groupPrincipal.Save();
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show("Application must be run with administrator priviliges!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }

            Refresh();
        }
Exemplo n.º 29
0
        public string AddUserToAdmin(string samAccountName, string groupName)
        {
            try
            {
                if (principalContext == null)

                {
                    principalContext = new PrincipalContext(ContextType.Domain, domain, userName, userPassword);
                }

                GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, groupName);
                group.Members.Add(principalContext, IdentityType.UserPrincipalName, samAccountName);
                group.Save();
            }
            catch (DirectoryServicesCOMException ex)
            {
                return(ex.Message);
            }

            catch (Exception exc)
            {
                return(exc.Message);
            }

            return("Başarıyla Eklendi");
        }
Exemplo n.º 30
0
        public void AddUser2Group(Label status, string userId, string groupName)
        {
            try
            {
                using (var ctx = new PrincipalContext(ContextType.Domain, _domainName))
                {
                    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                    if (group != null)
                    {
                        group.Members.Add(ctx, IdentityType.SamAccountName, userId);
                        group.Save();
                    }
                }

                status.Content = "Пользователь " + userId + " добавлен в группу";

                //логируем добавление
                NLog.OperationToLog("AddUser: "******"Пользователь " + userId + " уже есть в группе";

                NLog.ExceptionToLog("Error adding user: "******"");
            }

            catch (Exception e)
            {
                NLog.ExceptionToLog("Error adding user: "******"");
            }
        }