Madhawa Learns To Blog : C#, Java

.net, c#, java,sql, OOAD and more mad memory dumps...

  Home  |   Contact  |   Syndication    |   Login
  47 Posts | 0 Stories | 57 Comments | 15 Trackbacks

News

Archives

Post Categories

Blog Roll

Hang Outs

My old blog

Tuesday, November 18, 2008 #

        /// <summary>
        /// Add a user to a Sharepoint group
        /// </summary>
        /// <param name="userLoginName">Login name of the user to add</param>
        /// <param name="userGroupName">Group name to add</param>
        private void AddUserToAGroup(string userLoginName, string userGroupName)
        {
            //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)
                                    spGroup.AddUser(spUser);
                            }
                        }
                        catch (Exception ex)
                        {
                            //Error handling logic should go here
                        }
                        finally
                        {
                            spWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }

            });
        }

 

Here in this method you have to set "spWeb.AllowUnsafeUpdates = true" to allow updating some sharepoint lists.