I need to loop through all RoleDefinitiona of ProjectSite and get all users related to each one and add those users to a RoleDefinition of a ProjectSite in another SiteCollection
I can loop through RoleDefinitions like :
using (var src_ctx = new ClientContext(Root))
{
RoleDefinitionCollection role_definition_collection = src_ctx.Web.RoleDefinitions;
src_ctx.Load(role_definition_collection);
src_ctx.ExecuteQuery();
foreach (RoleDefinition role_definition in role_definition_collection)
{
}
}
also I can loop through all groups and read users of each group then get RoleAssignment of each user:
GroupCollection group_collection = src_ctx.Web.SiteGroups;
src_ctx.Load(group_collection);
src_ctx.ExecuteQuery();
foreach (Group group in group_collection)
{
UserCollection user_collection = group.Users;
foreach (User user in user_collection)
{
RoleAssignment role_assignment = src_ctx.Web.RoleAssignments.GetByPrincipal(user);
RoleDefinitionBindingCollection role_definition_binding_collection = role_assignment.RoleDefinitionBindings;
}
}
but how can I link between RoleDefinition and users ?
the following class used to copy users with its permissions, may help someone
public static class UserHelper
{
// static members
private static Dictionary<string, string> Levels = new Dictionary<string, string>();
private static void Prepare_Dictionary()
{
Levels["Full Control"] = "Full Control";
Levels["Design"] = "Design";
Levels["Contribute"] = "Contribute";
Levels["Read"] = "Read";
Levels["Limited Access"] = "Limited Access";
}
public static void Start_Moving_Users(string Root2010,string Root2013)
{
Prepare_Dictionary();
using (ClientContext src_ctx = new ClientContext(Root2010))
{
using (ClientContext dest_ctx = new ClientContext(Root2013))
{
dest_ctx.Web.BreakRoleInheritance(true, false);
RoleAssignmentCollection src_rac = src_ctx.Web.RoleAssignments;
src_ctx.Load(src_rac);
src_ctx.ExecuteQuery();
foreach (RoleAssignment src_ra in src_rac)
{
try
{
src_ctx.Load(src_ra.Member);
src_ctx.ExecuteQuery();
RoleDefinitionBindingCollection src_rdb = src_ra.RoleDefinitionBindings;
src_ctx.Load(src_rdb);
src_ctx.ExecuteQuery();
RoleDefinition src_rd = src_rdb[0];
src_ctx.Load(src_rd);
src_ctx.ExecuteQuery();
Principal dest_user = dest_ctx.Web.EnsureUser(src_ra.Member.LoginName);
RoleDefinition dest_rd = dest_ctx.Web.RoleDefinitions.GetByName(Levels[src_rd.Name]);
RoleDefinitionBindingCollection dest_rdb = new RoleDefinitionBindingCollection(dest_ctx);
dest_rdb.Add(dest_rd);
dest_ctx.Web.RoleAssignments.Add(dest_user, dest_rdb);
dest_ctx.ExecuteQuery();
}
catch { continue; }
}
}
}
}
}
Related
I am currently working on a sharepoint migration on a test environment, and have now come to the point where I would like to map/migrate my existing Ad groups and users from SP 2010 to SP 2013. Now when researching this I find alot of vague information but nothing very solid concerning this matter. How would I best go about this.
Let's say I have following users in a csv file representing the users on the SP 2010 environment:
c:0!.s|windows
i:0#.w|domainhere\administrator
i:0#.w|domainhere\apservice
i:0#.w|domainhere\koen
NT AUTHORITY\LOCAL SERVICE
SHAREPOINT\system
Domainhere\APService
Should I write a powershell script somehing which resembles the following
$csv = Import-CSV ".\sites-default.csv"
$web = Get-SPWeb = "https://mymachine.mydomain"
foreach($row in $csv)
{
#You could do this to format your account name if not already in the csv
$username = "Domain\" + $row.key
$web.EnsureUser($username)
$group = $web.SiteGroups |?{$_.name -eq "GROUPNAME"}
Set-SPUser -identity $username -web $web.url -group $group
}
Or are they better ways to do this kind of matter?
I have some code that works in C# using CSOM. It reads the permissions from all lists (document libraries also are lists) and the site level and writes them to an excel.
Then it reads the permissions from Excel and puts them on the new SharePoint.
The Excel uses using OfficeOpenXml;
The model
public class PermissionsToExcel
{
public string ListTitle { get; set; }
public string Gebruikersnaam { get; set; }
public string Rechten { get; set; }
public string ListUrl { get; set; }
public bool HasUniqueRoleAssignments { get; set; }
}
The code that gets the groups and their permissions from each list:
List<PermissionsToExcel> permissionsToExcelList = new List<PermissionsToExcel>();
using (ClientContext ctx = new ClientContext(#"http://yoursharepointurl.com/"))
{
Web web = ctx.Web;
ctx.Load(web, w => w.HasUniqueRoleAssignments, w => w.Url);
ctx.Load(web.RoleAssignments);
ctx.Load(web.Lists);
ctx.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.DefaultViewUrl, list => list.RoleAssignments, list => list.RoleAssignments.Groups, list => list.HasUniqueRoleAssignments));
ctx.ExecuteQuery();
//Get permissions on site level
foreach (RoleAssignment webRA in web.RoleAssignments)
{
ctx.Load(webRA.Member);
ctx.Load(webRA.RoleDefinitionBindings);
ctx.ExecuteQuery();
foreach (RoleDefinition definition in webRA.RoleDefinitionBindings)
{
ctx.Load(definition);
ctx.ExecuteQuery();
permissionsToExcelList.Add(new PermissionsToExcel() { ListTitle = "", Gebruikersnaam = webRA.Member.LoginName, Rechten = definition.Name, ListUrl = web.Url, HasUniqueRoleAssignments = web.HasUniqueRoleAssignments });
}
}
//Write down each group per list and their permissions
foreach (List list in web.Lists)
{
string listUrl = list.Context.Url + list.GetWebRelativeUrl();
foreach (RoleAssignment listRA in list.RoleAssignments)
{
ctx.Load(listRA.Member);
ctx.Load(listRA.RoleDefinitionBindings);
ctx.ExecuteQuery();
foreach (RoleDefinition definition in listRA.RoleDefinitionBindings)
{
ctx.Load(definition);
ctx.ExecuteQuery();
permissionsToExcelList.Add(new PermissionsToExcel() { ListTitle = list.Title, Gebruikersnaam = listRA.Member.LoginName, Rechten = definition.Name, ListUrl = listUrl, HasUniqueRoleAssignments = list.HasUniqueRoleAssignments });
}
}
}
}
Write the permissions to Excel using EPPlus
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Permissions");
workSheet.Cells[1, 1].LoadFromCollection(permissionsList, true);
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Permissions.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
Read the permissions from Excel
List<PermissionsToExcel> permissionslist = new List<PermissionsToExcel>();
FileInfo existingFile = new FileInfo(#"C:\path\Permissions.xlsx");
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//Get the first worksheet in the workbook
ExcelWorksheet excelWorksheet = package.Workbook.Worksheets["Permissions"];
int colCount = excelWorksheet.Dimension.End.Column; //get Column Count
int rowCount = excelWorksheet.Dimension.End.Row; //get row count
for (int row = 2; row <= rowCount; row++)//Rij 1 is de titel rij, beginnen bij rij 2
{
PermissionsToExcel permission = new PermissionsToExcel
{
ListTitle = excelWorksheet.Cells[row, 1].Value.ToString().Trim(),
Gebruikersnaam = excelWorksheet.Cells[row, 2].Value.ToString().Trim(),
Rechten = excelWorksheet.Cells[row, 3].Value.ToString().Trim(),
ListUrl = excelWorksheet.Cells[row, 4].Value.ToString().Trim(),
HasUniqueRoleAssignments = excelWorksheet.Cells[row, 5].Value.ToString().Trim().ToBoolean()
};
permissionslist.Add(permission);
}
return permissionslist;
}
Put the permissions onto a new site (which has the same library setup as the old one!!
using (ClientContext ctx = new ClientContext(#"http://newSharePointSiteUrl.com/"))
{
Web web = ctx.Web;
ctx.Load(web.Lists);
ctx.Load(web.RoleDefinitions);
ctx.ExecuteQuery();
//Ophalen rollen
RoleDefinition roleTypeOwner = ctx.Web.RoleDefinitions.GetByType(RoleType.Administrator);
RoleDefinition roleTypeEditor = ctx.Web.RoleDefinitions.GetByType(RoleType.Editor);
RoleDefinition roleTypeVisitor = ctx.Web.RoleDefinitions.GetByType(RoleType.Reader);
//RoleDefinition roleTypeNone = ctx.Web.RoleDefinitions.GetByType(RoleType.None);//Werkt niet
ctx.ExecuteQuery();
//Get groups
ctx.Load(ctx.Web.SiteGroups);
ctx.Load(ctx.Web.SiteUsers);
ctx.ExecuteQuery();
foreach (PermissionsToExcel pte in permissionslist)
{
if (pte.ListTitle == "")//If listtitle is empty, it's the site permissions
{
//Get site
User user = ctx.Web.SiteUsers.GetByLoginName(pte.Gebruikersnaam);
ctx.Load(user);
ctx.ExecuteQuery();
//Check if the site had unique permissions
if (pte.HasUniqueRoleAssignments)//Site had unique permissions, break inheritance and take away the old groups
{
RoleDefinitionBindingCollection rdbc = new RoleDefinitionBindingCollection(ctx);
switch (pte.Rechten)
{
case "Read":
rdbc.Add(roleTypeVisitor);
break;
case "Edit":
rdbc.Add(roleTypeEditor);
break;
case "Full Control":
rdbc.Add(roleTypeOwner);
break;
default:
break;
}
web.BreakRoleInheritance(false, true);
web.RoleAssignments.Add(user, rdbc);
}
else//Site had no unique permissions, inherit from above
{
//TODO: do we want that?
}
}
else if (web.ListExists(pte.ListTitle))//Go over all lists
{
//Get List
List list = web.Lists.First(t => t.Title == pte.ListTitle);
//var group = ctx.Web.SiteGroups.GetByName(pte.Gebruikersnaam);
//ctx.Load(Group);
//ctx.ExecuteQuery();
User user = ctx.Web.SiteUsers.GetByLoginName(pte.Gebruikersnaam);
ctx.Load(user);
ctx.ExecuteQuery();
//Check if list had unique permissions
if (pte.HasUniqueRoleAssignments)//List had unique permissions, stop inheritance and put back groups with their permissions
{
RoleDefinitionBindingCollection rdbc = new RoleDefinitionBindingCollection(ctx);
switch (pte.Rechten)
{
case "Read":
rdbc.Add(roleTypeVisitor);
break;
case "Edit":
rdbc.Add(roleTypeEditor);
break;
case "Full Control":
rdbc.Add(roleTypeOwner);
break;
default:
break;
}
list.BreakRoleInheritance(false, true);
//list.RoleAssignments.Add(Group, rdbc);
list.RoleAssignments.Add(user, rdbc);
}
else //List had no unique permissions, inherit from above
{
list.ResetRoleInheritance();
}
}
else
{
Debug.WriteLine("LIST NOT FOUND: PROBLEM");
}
}
}
The process you would follow is:
$user = Get-SPUser -Identity "DOM\john.smith" -Web https://siteCollectionUrl
Move-SPUser -Identity $user -NewAlias "i:0#.w|IDD\142909" -IgnoreSid
This will migrate the user farm-wide. You do not need to call EnsureUser.
If you're using the User Profile Service App, make sure your user account has explicit Full Control over the UPSA to migrate users. I also provided the example above if using Windows Claims auth. On the Get-SPUser, you don't have to specify it, but on the Move-SPUser, you do.
https://social.technet.microsoft.com/Forums/en-US/2703f6de-7a79-46b8-9184-01279a845c4b/migrating-all-users-to-a-new-domain?forum=sharepointadmin
list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}
I am trying to execute a site workflow from a console application.When the code to execute the workflow runs, it thows an error
An unhandled exception of type 'Microsoft.SharePoint.Client.ServerException' occurred in Microsoft.SharePoint.Client.Runtime.dll
Additional information:
Cannot invoke method or retrieve property from null object. Object returned by the following call stack is null. "GetWorkflowInteropService new Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager()"
string userName = "username";
string password = "password";
string siteUrl = "https://share.example.com/sites/workflowsite";
string workflowName = "MyWorkflow";
using (ClientContext clientContext = new ClientContext(siteUrl))
{
SecureString securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
clientContext.Credentials = new NetworkCredential(userName, securePassword);
Web web = clientContext.Web;
WorkflowAssociationCollection wfAssociations = web.WorkflowAssociations;
WorkflowAssociation wfAssociation = wfAssociations.GetByName(workflowName);
clientContext.Load(wfAssociation);
clientContext.ExecuteQuery();
WorkflowServicesManager manager = new WorkflowServicesManager(clientContext, web);
InteropService workflowInteropService = manager.GetWorkflowInteropService();
clientContext.Load(workflowInteropService);
clientContext.ExecuteQuery();
workflowInteropService.StartWorkflow(wfAssociation.Name, new Guid(), Guid.Empty, Guid.Empty, null);
clientContext.ExecuteQuery(
}
The code below for your reference:
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WorkflowServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace CSOMStartWorkflow {
class Program {
static void Main(string[] args) {
Console.WriteLine("Enter the Office 365 Login Name");
string loginId = Console.ReadLine();
string pwd = GetInput("Password", true);
Console.WriteLine("Web Url:");
string webUrl = Console.ReadLine();
Console.WriteLine("List Name:");
string listName = Console.ReadLine();
Console.WriteLine("Workflow Name");
string workflowName = Console.ReadLine();
var passWord = new SecureString();
foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);
using (var ctx = new ClientContext(webUrl)) {
ctx.Credentials = new SharePointOnlineCredentials(loginId, passWord);
var workflowServicesManager = new WorkflowServicesManager(ctx, ctx.Web);
var workflowInteropService = workflowServicesManager.GetWorkflowInteropService();
var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();
var workflowInstanceService = workflowServicesManager.GetWorkflowInstanceService();
var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
ctx.Load(publishedWorkflowDefinitions);
ctx.ExecuteQuery();
var def = from defs in publishedWorkflowDefinitions
where defs.DisplayName == workflowName
select defs;
WorkflowDefinition workflow = def.FirstOrDefault();
if(workflow != null) {
// get all workflow associations
var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(workflow.Id);
ctx.Load(workflowAssociations);
ctx.ExecuteQuery();
// find the first association
var firstWorkflowAssociation = workflowAssociations.First();
// start the workflow
var startParameters = new Dictionary<string, object>();
if (ctx.Web.ListExists(listName)) {
List list = ctx.Web.GetListByTitle(listName);
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = list.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
ctx.Load(items);
ctx.ExecuteQuery();
foreach (ListItem listItem in items) {
Console.WriteLine("Starting workflow for item: " + listItem.Id);
workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, listItem.Id, startParameters);
ctx.ExecuteQuery();
}
}
}
}
Console.WriteLine("Press any key to close....");
Console.ReadKey();
}
private static string GetInput(string label, bool isPassword) {
Console.ForegroundColor = ConsoleColor.White;
Console.Write("{0} : ", label);
Console.ForegroundColor = ConsoleColor.Gray;
string strPwd = "";
for (ConsoleKeyInfo keyInfo = Console.ReadKey(true); keyInfo.Key != ConsoleKey.Enter; keyInfo = Console.ReadKey(true)) {
if (keyInfo.Key == ConsoleKey.Backspace) {
if (strPwd.Length > 0) {
strPwd = strPwd.Remove(strPwd.Length - 1);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write(" ");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
} else if (keyInfo.Key != ConsoleKey.Enter) {
if (isPassword) {
Console.Write("*");
} else {
Console.Write(keyInfo.KeyChar);
}
strPwd += keyInfo.KeyChar;
}
}
Console.WriteLine("");
return strPwd;
}
}
}
Reference: Starting a SharePoint Online Workflow with the Client Side Object Model (CSOM)
Is there a way other than powershell (CSOM or JSOM) to list all external users?
I want to list all external users and "their permissions".
I ended upp doing a console application that exports all external users and their permissions on all sites, lists, files and folders in a sitecollection.
It was done quickly, so code modification could most certainly be done to fit your requirements better.
This solution exports a .csv file with the content.
Just copy paste from the "Program.class"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using Microsoft.SharePoint.Client;
using System.Net;
namespace ListExternalUsersCSOM
{
class Program
{
// Output to filesystem
private static string filePath = #"C:\Users\User\Desktop\output.csv";
// Builds the content to export to the csv file
private static StringBuilder csv = new StringBuilder();
// Groupcollection of all sitegrups and their members
// Only want one trip to the server for this
private static GroupCollection groups;
static void Main(string[] args)
{
// Sitecollection url, username and password of admin account
var webUri = new Uri("https://tenant.sharepoint.com/sites/intranet");
const string userName = "admin#tenant.com";
const string password = "Password";
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
// Create credentials and context
var credentials = new SharePointOnlineCredentials(userName, securePassword);
var ctx = new Microsoft.SharePoint.Client.ClientContext(webUri);
ctx.Credentials = credentials;
// Get rootweb and the groups for the sitecollection
var rootWeb = ctx.Web;
groups = rootWeb.SiteGroups;
// Load groupcollection and load certain properties in every group right away
ctx.Load(groups, groups => groups.Include(g => g.Title, g => g.Users, g => g.Id));
// Load rootweb, subsites, lists, relative url, title, uniqueroleassingments
// Inlcude uniqueroleassingments and title in lists, spares us a trip to the server
ctx.Load(rootWeb, w => w.Webs, w => w.ServerRelativeUrl, w => w.Title, w => w.Lists.Include(l => l.HasUniqueRoleAssignments, l => l.Title), w => w.HasUniqueRoleAssignments);
ctx.ExecuteQuery();
// First we do these checks for rootweb only, then we recursively check all subsites...
// If uniquepermissions on web, look for external users
if (rootWeb.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsWeb(rootWeb);
}
foreach (var list in rootWeb.Lists)
{
if (list.Title != "MicroFeed" | list.Title != "Delningslänkar")
{
ListHasUniqueRoleAssignment(rootWeb, list, ctx);
}
}
foreach (var subWeb in rootWeb.Webs)
{
WebHasUniqueRoleAssignmentRecursive(subWeb, ctx);
}
System.IO.File.WriteAllText(filePath, csv.ToString(), Encoding.UTF8);
}
private static void WebHasUniqueRoleAssignmentRecursive(Web spWeb, ClientContext ctx)
{
ctx.Load(spWeb, w => w.Webs, w => w.ServerRelativeUrl, w => w.Title, w => w.Lists.Include(l => l.HasUniqueRoleAssignments, l => l.Title), w => w.HasUniqueRoleAssignments);
ctx.ExecuteQuery();
if (spWeb.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsWeb(spWeb);
}
foreach (var list in spWeb.Lists)
{
if (list.Title != "MicroFeed" | list.Title != "Delningslänkar")
{
ListHasUniqueRoleAssignment(spWeb, list, ctx);
}
}
foreach (var subWeb in spWeb.Webs)
{
WebHasUniqueRoleAssignmentRecursive(subWeb, ctx);
}
}
private static void ListHasUniqueRoleAssignment(Web spWeb, List list, ClientContext ctx)
{
var listsFolders = new List<Folder>();
var listsFiles = new List<File>();
var listsItems = new List<ListItem>();
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = list.GetItems(query);
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.HasUniqueRoleAssignments, i => i.File, i => i.Folder, i => i.File.ListItemAllFields.HasUniqueRoleAssignments, i => i.Folder.ListItemAllFields.HasUniqueRoleAssignments));
ctx.ExecuteQuery();
listsItems.AddRange(items);
if (list.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsList(spWeb, list);
}
foreach (var listItem in listsItems)
{
if (listItem.FileSystemObjectType == FileSystemObjectType.File && listItem.HasUniqueRoleAssignments)
{
listsFiles.Add(listItem.File);
}
else if (listItem.FileSystemObjectType == FileSystemObjectType.Folder && listItem.HasUniqueRoleAssignments)
{
listsFolders.Add(listItem.Folder);
}
}
foreach (File file in listsFiles)
{
if (file.ListItemAllFields.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsFile(spWeb, file);
}
}
foreach (Folder folder in listsFolders)
{
if (folder.ListItemAllFields.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsFolder(spWeb, folder);
}
}
}
private static void getExternalUsersAndPermissionsWeb(Web spWeb)
{
var ctx = spWeb.Context;
var assignments = spWeb.RoleAssignments;
// Load roleassingment for web, include users and groups and their permissionslevels on this web
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
// Iterate trough all assingments
foreach (var roleAssingment in assignments)
{
// If a user loginname contains #ext# it is an external user, so print the user and the permission level
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Site \"{0}\": {1} har rättighet {2} ", spWeb.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
// If a group
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
// Go to groupcollection we got earlier, get the corresonding groups users
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
// Iterate trough users
foreach (var user in users)
{
// If a user loginname contains #ext# it is an external user, so print the user and the permission level
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Site \"{0}\": {1} har rättighet {2} ", spWeb.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsList(Web spWeb, List list)
{
var ctx = spWeb.Context;
var assignments = list.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Lista \"{0}\": {1} har rättighet {2} ", list.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Lista \"{0}\": {1} har rättighet {2} ", list.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsFile(Web spWeb, File item)
{
var ctx = spWeb.Context;
var assignments = item.ListItemAllFields.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Fil \"{0}\": {1} har rättighet {2} ", item.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Fil \"{0}\": {1} har rättighet {2} ", item.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsFolder(Web spWeb, Folder folder)
{
var ctx = spWeb.Context;
var assignments = folder.ListItemAllFields.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Mapp\\Dokumentgrupp \"{0}\": {1} har rättighet {2} ", folder.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Mapp\\Dokumentgrupp \"{0}\": {1} har rättighet {2} ", folder.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
}
}
Using object model I am updating group. The value I am setting in 'RequestToJoinLeaveEmailSetting' field is not showing when using PowerShell command. However, when I am fetching it by the object model, it is showing the new value set to 'RequestToJoinLeaveEmailSetting' field.
Using the PowerShell commands I am able to update this field. However, from the object model I am getting the value set from itself, not that is set by PowerShell.
How, can it be in sync? Any help/idea?
Thanks in advanced.
Mohak
Here is my Code:
SPSite Site = new SPSite(siteUrl);
SPWeb spWeb = Site.OpenWeb();
SPGroup spGroup = spWeb.SiteGroups[oldname];
SPRoleCollection roles = spGroup.Roles;
if (roles != null)
{
oldRoles = new ArrayList();
foreach (SPRole role in roles)
{
oldRoles.Add(role.Name);
}
}
// here we are comparing the old and new roles to be updated and separating out
// which roles to be deleted and which is to be updated.
foreach (string role in oldRoles)
{
if (newRoles.Contains(role))
{
updatedRoles.Add(role);
}
else
{
removeRoles.Add(role);
}
}
foreach (string rolenames in newRoles)
{
if (!oldRoles.Contains(rolenames))
{
updatedRoles.Add(rolenames);
}
}
if (removeRoles != null && removeRoles.Count > 0)
{
SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
foreach (string str in removeRoles)
{
SPRoleDefinition role = spWeb.RoleDefinitions[str];
//SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
roleAssignment.RoleDefinitionBindings.Remove(role);
spWeb.RoleAssignments.Remove(roleAssignment.Member);
spWeb.Update();
}
spWeb.Update();
}
if (spGroup != null)
{
spGroup.Description = description;
spGroup.Name = name;
spGroup.OnlyAllowMembersViewMembership = viewprmsn;
spGroup.AllowMembersEditMembership = edprmsn;
spGroup.AllowRequestToJoinLeave = mbrrqst;
spGroup.AutoAcceptRequestToJoinLeave = acptrqst;
spGroup.RequestToJoinLeaveEmailSetting = emailid;
if (updatedRoles != null && updatedRoles.Count > 0)
SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
// SPRoleDefinition roleDefinition = spWeb.RoleDefinitions["Contribute"];
foreach (string str in updatedRoles)
{
SPRoleDefinition roleDefinition = spWeb.RoleDefinitions[str];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
}
spWeb.RoleAssignments.Add(roleAssignment);
}
//spGroup.RequestToJoinLeaveEmailSetting = emailid;
spGroup.Update();
}
spWeb.Update();
}
catch (Exception ex)
{
SPTlogger.Error("-------------------------ERROR-------------------------");
SPTlogger.Error("Error in UpdateGroup():" + ex.Message);
throw new Exception(ex.Message);
}
finally
{
SPTlogger.Debug("<-- : UpdateGroup()");
}
}
It seems you forgot to apply changes using SPGroup.Update method when the group properties have been updated
PS example:
$web = Get-SPWeb $webUrl
$membersGroup = $web.AssociatedMemberGroup
$membersGroup.RequestToJoinLeaveEmailSetting = "admin#intranet.contoso.com"
$membersGroup.Update() #save group changes