Friday, December 24, 2010

Saturday, December 11, 2010

Add and Delete Sharepoint user with group name programmable.

 private void AddUserToAGroup(string userLoginName, string userGroupName,int action)
        {
            //Executes this method with Full Control rights even if the user does not otherwise have Full Control
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                //Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
                using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        try
                        {
                            //Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
                            spWeb.AllowUnsafeUpdates = true;
                            SPUser spUser = spWeb.EnsureUser(userLoginName);
                            if (spUser != null)
                            {
                                SPGroup spGroup = spWeb.Groups[userGroupName];
                                if (spGroup != null)
                                {
                                    if (action.ToString() == "0")
                                    {
                                        spGroup.AddUser(spUser);
                                    }
                                    else if (action.ToString() == "1")
                                    {
                                        spGroup.RemoveUser(spUser);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //Error handling logic should go here
                        }
                        finally
                        {
                            spWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            AddUserToAGroup("ayyappan", "Designers",1);
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            AddUserToAGroup("ayyappan", "Designers",2);
        }