Saturday, November 8, 2014

Programmatically Adding User to Site - SPRoleAssignment & RoleDefinitionBindings


In this post I'm adding a domain user to a SharePoint 2010 site programmatically.
I am using a simple console application for this purpose. The code is as below:

using Microsoft.SharePoint;

namespace SPTestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            AddUser();
        }

        static void AddUser()
        {
            string siteUrl = "http://localhost:1000/SitePages/Home.aspx";

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPRoleDefinitionCollection collroleDefinitions = web.RoleDefinitions;
                        SPRoleAssignmentCollection colllroleAssignments = web.RoleAssignments;

                        SPRoleAssignment oRoleAssignment = new SPRoleAssignment("DOMAIN\\username","user@company.lk", "UserName","Notes");
                        SPRoleDefinitionBindingCollection collRoleDefBinding=oRoleAssignment.RoleDefinitionBindings;
                        collRoleDefBinding.Add(collroleDefinitions["Read"]);
                        colllroleAssignments.Add(oRoleAssignment);
                    }
                }
            });
        }
    }
}


Roll Assignments -> are the permissions in the site &
RoleDefinition -> are the permission levels in the site

No comments:

Post a Comment