Interview Questions administrator

Best SharePoint administrator Interview Questions and Answers with topic wise:


Recycle Bin | MMS | ManagedVsCrawledProperties |

Wednesday, August 29, 2012

Adding/Removing users to/from the group:



Note: We have to check before adding/removing users to/from the group and also check the users already exists or not in group. 
 
public void AddDeleteUsersInGroup(User user)
        {
            string GroupName = string.Empty;
            if (user.IsAdmin.HasValue && user.IsAdmin.Value)
                GroupName = "Group Owners";
            else if (user.IsApprover.HasValue && user.IsApprover.Value)
                GroupName = " Group Members";
            else
                GroupName = " Group Visitors";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        try
                        {
                            web.AllowUnsafeUpdates = true;
                            SPUser spUser = web.EnsureUser(user.UserName);
                            if (spUser != null)
                            {
                                SPGroup spGroup = spGatingGroup(web, GroupName);
                                if (spGroup != null && (IsUserInSPGroup(spUser, GroupName.Trim())))
                                {
                                   //For adding user to the group
                                      spGroup.AddUser(spUser);
                                   //For removing user to the group
                                    spGroup.RemoveUser(spUser);
                                    spGroup.Update();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }
 
private SPGroup spGatingGroup(SPWeb spDLRWeb, string groupName)
        {
            SPGroup spGroup = null;
            try
            {
                spGroup = spWeb.SiteGroups[groupName];
                if (spGroup == null) throw new Exception("Sharepoint Group name '" + groupName + "' not found");
            }
            catch (Exception ex)
            {
                //ErrorHandling(ex);
            }
            return spGroup;
        }

private bool IsUserInSPGroup(SPUser user, string strname)
        {
            foreach (SPGroup group in user.Groups)
            {
                if (group.Name == strname)
                    return true;
            }
            return false;
        }


No comments:

Post a Comment