Sometime, the default Permission Levels will not be sufficient for our application and the requirement. Here, let us see how to create a Permission Level through code. Before that, let us have a look, how to create the same on the Screen.
1. Go to the Site Settings.
2. Click on Site Permissions.
3. Click on Permission Levels on the Ribbon.
4. Click on Add a Permission Level and fill up the details on the screen shown below.
5. I have selected all the Permissions in this example. This is something similar to Full Control Permission Level.
6. Click on Create Button.
7. Now, your permission level is available to assign with any User / group.
Now, let us see, how to create the same Permission Level Programmatically.
namespace Console.Office365
{
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using Newtonsoft.Json.Linq;
using OfficeDevPnP.Core.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
CreateCustomPermissionLevel();
}
public static void CreateCustomPermissionLevel()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://*****.sharepoint.com/sites/communitysite";
string userName = "Sathish@*******.onmicrosoft.com";
string password = "****************";
using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(web.AllProperties);
clientContext.Load(web.RoleDefinitions);
clientContext.ExecuteQueryRetry();
var roleDefinitions = web.RoleDefinitions;
// Get Full Control Role Definition
var fullControlRoleDefinition = roleDefinitions.GetByName("Full Control");
clientContext.Load(fullControlRoleDefinition);
clientContext.ExecuteQuery();
// Create New Custom Permission Level
RoleDefinitionCreationInformation roleDefinitionCreationInformation = new RoleDefinitionCreationInformation();
roleDefinitionCreationInformation.BasePermissions = fullControlRoleDefinition.BasePermissions;
roleDefinitionCreationInformation.Name = "MyPermissionLevelCreatedByCode";
roleDefinitionCreationInformation.Description = "Custom Permission Level, Inherited from the Full Control";
roleDefinitions.Add(roleDefinitionCreationInformation);
clientContext.Load(roleDefinitions);
clientContext.ExecuteQuery();
}
}
}
}
8. This code will create the custom permission level as shown below.
Happy Coding,
Sathish Nadarajan.
Leave a comment