I'm using the code below to modify Custom List Permission in SharePoint 2010. What I'm trying to do is to modify All Group's Permission Level to Read except for the Owners Group. My code runs fine when I manually deactivate/activate the feature in Site Settings. But an error is displayed in the ULS Log when I deploy it using Visual Studio 2010.
The error I got is
Object reference not set to an instance of an object. StackTrace: StackTrace: at SPProject.Features.ListInstance_Feature.ListInstance_FeatureEventReceiver.b_0() at Microsoft.SharePoint.SPSecurity.<>c_DisplayClass4.b__2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) at SPProject.Features.ListInstance_Feature.ListInstance_FeatureEventReceiver.UpdateList...
Here is the code I am using in FeatureActivated method
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite site = new SPSite(SPContext.Current.Site.ID)) {
using (SPWeb web = site.OpenWeb()) {
Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest();
SPGroupCollection groupCol = web.Groups;
SPList list = SPContext.Current.Web.GetList(SPHelper.GetListByURL(GDCLists.TypeDeDemande));
SPRoleDefinition contributeDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
SPRoleDefinition readDef = web.RoleDefinitions.GetByType(SPRoleType.Reader);
foreach (SPGroup group in groupCol) {
SPRoleAssignment contributeRole = new SPRoleAssignment(group);
contributeRole.RoleDefinitionBindings.Add(contributeDef);
if (!list.HasUniqueRoleAssignments) // required to make role change
list.BreakRoleInheritance(true);
SPRoleAssignment assignmentForGroup = list.RoleAssignments.GetAssignmentByPrincipal(group);
assignmentForGroup.RoleDefinitionBindings.Remove(contributeDef);
if (!assignmentForGroup.RoleDefinitionBindings.Contains(readDef))
assignmentForGroup.RoleDefinitionBindings.Add(readDef);
assignmentForGroup.Update();
}
}
}
});
I've researched through many sites and applied the suggested workaround but still it doesn't resolved the error. Please advise. Thank you.