0

Dear stackoverflow community:

What we have? There is a SharePoint site with various folders and subfolders etc. Excpect for the default SharePoint groups (and their permission levels)- for some of the folders there are custom Groups created. These Groups have special/custom Permission Levels.

What I have to do is: 1. Input the web path to the folder from the console e.g xxx.sharepoint.com/teams/Global-Program-Team-SouthAfrica 2. Input the mail/ username to the C# based Console App of the user that needs to be added to the custom Group available on that address OR 3. Input the mail/ username of the user that needs to be removed from the custom Group available on that address

In a nutshell how i access given web path, remove/add users to the groups available in a given webpath. This is pretty much everyting that this tool will do.I guess that the code will have also to send my credentials to the portal in order to let it do its thing.

What I tried so far? I reveiwed several articales and posts related to that but so far I've "worked"(amateur level) only with desktop based tools that are performing local tasks and I am pretty new to the web projects, so I would need some assitance. :)

1 Answer 1

0

Here is the C# code using this we can add or remove user from SharePoint group:

Using C# SSOM - server object model

SPWebApplication g_WebApp;
SPWeb g_Web;
  try

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    SPSite site = new SPSite(“<siteUrl>”);



                    //siteName = "Payroll";

                    g_Web = site.OpenWeb(“<siteName>”);

                    g_WebApp = g_Web.Site.WebApplication;

                    g_WebApp.FormDigestSettings.Enabled = true;

                    g_Web.AllowUnsafeUpdates = true;

                    SPUser user = g_Web.AllUsers[“<username>”];

                    SPMember member = g_Web.SiteUsers[“<requestedBy>”];



                    if (user != null)

                    {

                        SPGroupCollection grpCollection = g_Web.SiteGroups;



                        bool isExists = IsGroupExists(grpCollection,

                                                      “GroupName”);



                        if (!isExists && “Add” == Action.Add)

                        {

                           g_Web.SiteGroups.Add(“GroupName”, member, user,

                                                        Constants.Messages.DESCRIPTION);



                           g_Web.AssociatedGroups.Add(g_Web.SiteGroups

                                                      [“GroupName”]);



                          g_Web.Update();

                          SPRoleAssignment assignment = new SPRoleAssignment(

                                                                  g_Web.SiteGroups[“GroupName”]);

                          SPRoleDefinition _role = g_Web.RoleDefinitions

                                                                 [Constants.PermissionLevel.CONTRIBUTE];

                         assignment.RoleDefinitionBindings.Add(_role);

                         g_Web.RoleAssignments.Add(assignment);

                      }

                      else

                      {

                        SPGroup group = g_Web.SiteGroups[“GroupName”];



                        if (group != null)

                        {

                           if (“Add”.Equals(Action.Add))

                           {

                               group.AddUser(user);

                           }

                          else if (“Remove”.Equals(Action.Remove))

                          {

                               group.RemoveUser(user);

                           }

                           group.Update();

                         }

                      }

                   }

                 }

               }

               g_Web.Update();

               g_WebApp.FormDigestSettings.Enabled = true;

             });

            }

            catch

            {

                throw;

            }

            finally

            {

                g_Web.AllowUnsafeUpdates = false;

            }




private bool IsGroupExists(SPGroupCollection grpCollection,

                                    string groupName)

        {

            bool isExists = false;

            foreach (SPGroup group in grpCollection)

            {

                if (group.Name.Equals(groupName))

                {

                    isExists = true;

                    break;

                }

            }



            return isExists;

        }



    } 



    public enum Action

    {

        Add,

        Remove

    }

Reference URL:

Add and Remove User into SharePoint group using SharePoint Server Object Model

Using C# CSOM - client object model:

ClientContext client = new ClientContext(“http://SiteUrl”);

client.ExecuteQuery();

Web website = client.Web;

client.Load(website, w => w.AllProperties, w => w.SiteGroups, w => w.SiteUserInfoList, w => w.Webs,w => w.Title);

client.ExecuteQuery();

GroupCollection groupCollection = website.SiteGroups;

client.Load(groupCollection, groups => groups.Include(grps => grps.Users, grps => grps.Title));

client.ExecuteQuery();

User user;

foreach (Group group in groupCollection)

{

   if (group.Title.Equals(“GroupName”))

   {

      UserCreationInformation userInfo = new UserCreationInformation();

      userInfo.LoginName = “UserName”;



      if (“Add”)

      {

         user = group.Users.Add(userInfo);

         group.Users.AddUser(user);

       }

       else if (“Remove”)

       {

         user = group.Users.GetByLoginName(“UserName”);

         group.Users.Remove(user);

        }

        group.Update();

        website.Update();

        client.ExecuteQuery();



     }

  }

Code reference is here:

Add and remove User into SharePoint group Using Client Object Model

3
  • many thanks for your reply, I forgot to mention that the code would have to run on Client Object Model and not Server Object Model. The tool with work with the corporate Sharepoint where I have a dedicated SharePoint site. So each line have to be executed on my pc and the request send trought the web. I tried this one link. When i try to execute it it returns: "Unhandled Exception: System.Net.WebException: The remote server returned an error: (403) Forbidden". Do you have any snippets for CSOM?
    – o.y
    Jan 4, 2020 at 17:37
  • I guess that the reason for this exception is the way i am managing the credentials - when i am using link the autetication goes fine, still I am keep trying to implement this to alrady available code for add/remove.
    – o.y
    Jan 4, 2020 at 18:06
  • Please use this link for CSOM c# code : c-sharpcorner.com/blogs/…
    – SP 2022
    Jan 4, 2020 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.