Saturday, February 28, 2009

How To Copy Permissions Between Site Collections

Hi again,

One of the more challenging issues in MOSS is permissions, specially if we need to move them between site collections.

To add permissions to item\folder\list\site we add SPRoleAssignment that contains SPUser (as SPPincipal), and SPRoleDefinition that contain the the BasePermissions or the Types (reader/contributor...).

Each role is have diffrent parameters in each site collection, for example my user can be in one site collection 1;#elad and in the other can be 5;#elad, the same user but a diffrent id. the same is for definition, contributor for example have the same base permissions in every site collection but have a differnt ID.

So what to do... ?

It is eazy, 
1. Create a new instant of your role user like this:

// role is the role assignment from the old site collection.
SPUser user = role.Member as SPUser;

2. Than create a new role assinment

// web is the site in the new site collection
SPRoleAssignment roleAssignment = new SPRoleAssignment(
                                   web.EnsureUser(user.LoginName) as SPPrincipal); 

Why EnsureUser ? 
The EnsureUser method will chack if the user exist in the corrent site and if not will create him as Limited Access permission. (10x to Michael Assouline that show me this method).

than add the role definitions to the new role assignment,

foreach (SPRoleDefinition roleDefinition in role.RoleDefinitionBindings)
{
// we cann't add Limited Access
if (roleDefinition.Type != SPRoleType.Guest)
        {
   definition = web.RoleDefinitions.GetByType(roleDefinition.Type);
   roleAssignment.RoleDefinitionBindings.Add(definition);
}
}

3. And now just add the new role to the item,

item.RoleAssignments.Add(roleAssignment); 


1 comment:

  1. Today you suffer pain and neglect but tomorrow is an another day so worry no more because every pain has an exchange. The exchange to it is happiness and unconditional love. Visit my site for more information. Have a good day and God bless your site.

    n8fan.net

    www.n8fan.net

    ReplyDelete