Tuesday, 29 September 2015

Copy Source Web Role Definition to Destination Web SharePoint Server Object Model

public static void CopyWebRoles(SPWeb sourceWeb, SPWeb destinationWeb)
        {

          // copy Source Web Role Definitions to the Destination Web
            foreach (SPRoleDefinition roleDef in sourceWeb.RoleDefinitions)
            {
                Skip WSS base permission levels
                if (roleDef.Type != SPRoleType.Administrator
                    && roleDef.Type != SPRoleType.Contributor
                    && roleDef.Type != SPRoleType.Guest
                    && roleDef.Type != SPRoleType.Reader
                    && roleDef.Type != SPRoleType.WebDesigner
                    )
                {
                    //handle additon of existing  permission level error

                    try
                    {
                        if (destinationWeb.HasUniqueRoleDefinitions)
                        {
                            destinationWeb.RoleDefinitions.BreakInheritance(true, false);
                            destinationWeb.RoleDefinitions.Add(roleDef);

                        }

                    }
                    catch (SPException) { }
                }
            }


        }