Search This Blog

Friday, April 29, 2016

How to programmatically add delete modify item permissions in SharePoint 2013

Note: SPPrincipal can be either an SPUser or SPGroup Object


Breaking Inheritance
//specifies whether the item has unique security
//or inherits its role assignments from a parent object.
item.HasUniqueRoleAssignments

//Stops inheriting permissions from parent object
// if true, it will keep all existing users
// false, to remove all users
item.BreakRoleInheritance(true);

//Removes the local role assignments
//and reverts to role assignments from the parent object.
item.ResetRoleInheritance();



Adding Permissions to an item
//SPGroup group = web.Groups[0];
//SPUser user = web.Users[0];
//SPUser user2 = web.EnsureUser("mangaldas.mano");
//SPUser user3 = web.EnsureUser("Domain Users"); ;
//SPPrincipal[] principals = { group, user, user2, user3 };
public static void SetPermissions(this SPListItem item, IEnumerable principals, SPRoleType roleType)
{
 if (item != null)
 {

  foreach (SPPrincipal principal in principals)
  {
   SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
   SetPermissions(item, principal, roleDefinition);
  }
 }
}


public static void SetPermissions(this SPListItem item, SPUser user, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  SetPermissions(item, (SPPrincipal)user, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  SetPermissions(item, principal, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPUser user, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SetPermissions(item, (SPPrincipal)user, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

  roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
  item.RoleAssignments.Add(roleAssignment);
 }
}


Deleting all user Permissions from an item
public static void RemovePermissions(this SPListItem item, SPUser user)
{
 if (item != null)
 {
  RemovePermissions(item, user as SPPrincipal);
 }
}

public static void RemovePermissions(this SPListItem item, SPPrincipal principal)
{
 if (item != null)
 {
  item.RoleAssignments.Remove(principal);
  item.SystemUpdate();
 }
}


Removing specific roles from an item
public static void RemovePermissionsSpecificRole(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal);
  if (roleAssignment != null)
  {
   if (roleAssignment.RoleDefinitionBindings.Contains(roleDefinition))
   {
    roleAssignment.RoleDefinitionBindings.Remove(roleDefinition);
    roleAssignment.Update();
   }
  }
 }
}

public static void RemovePermissionsSpecificRole(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  RemovePermissionsSpecificRole(item, principal, roleDefinition);
 }
}


Updating or Modifying Permissions on an item
public static void ChangePermissions(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  ChangePermissions(item, principal, roleDefinition);
 }
}

public static void ChangePermissions(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal);
 if (roleAssignment != null)
 {
  roleAssignment.RoleDefinitionBindings.RemoveAll();
  roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
  roleAssignment.Update();
 }
}



Create Groups Programmatically in SharePoint 2013

 The code below changes the built in associated groups by using the spWeb property bag directly, rather than the properties exposed by spWeb - e.g. spWeb.AssociatedGroups.Add(group), or spWeb.AssociatedOwnerGroup = group.

using Microsoft.SharePoint;
 
namespace DevHoleDemo
{
    public static class GroupsHelper
    {
        public enum AssociatedGroupTypeEnum { Owners, Members, Vistors };
 
        public static void AddGroups(SPWeb spWeb, bool copyUsersFromParent)
        {
            spWeb.BreakRoleInheritance(false);
            SPGroup owners = AddGroup(spWeb, AssociatedGroupTypeEnum.Owners, 
                             copyUsersFromParent);
            SPGroup members = AddGroup(spWeb, AssociatedGroupTypeEnum.Members, 
                             copyUsersFromParent);
            SPGroup vistors = AddGroup(spWeb, AssociatedGroupTypeEnum.Vistors, 
                             copyUsersFromParent);
            SPGroup myGroup = AddGroup(spWeb, "My Group", "An example group.", 
            null, null, null, false);
            SetAssociatedGroups(spWeb, new SPGroup[] { owners, members, vistors,
            myGroup });
        }
 
        public static void SetAssociatedGroups(SPWeb spWeb, SPGroup[] groups)
        {
            string formatString = "";
            object[] ids = new object[groups.Length];
            for (int i = 0; i < groups.Length; i++)
            {
                formatString += string.Format("{{{0}}};", i);
                ids[i] = groups[i].ID;
            }
            spWeb.Properties["vti_associategroups"] = string.Format(formatString.
            TrimEnd(new char[] 
           { ';' }), ids);
            spWeb.Properties.Update();
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, AssociatedGroupTypeEnum 
        associateGroupType, 
        bool copyUsersFromParent)
        {
            switch (associateGroupType)
            {
                case AssociatedGroupTypeEnum.Owners:
                    return AddGroup(spWeb, spWeb.Name + " Owners", "Use this group to 
                    give people full control permissions to the SharePoint site: {0}", 
                   "Full Control", "vti_associateownergroup", 
                    spWeb.ParentWeb.AssociatedOwnerGroup, copyUsersFromParent);

                case AssociatedGroupTypeEnum.Members:
                    return AddGroup(spWeb, spWeb.Name + " Members", "Use this group to 
                    give people contribute permissions to the SharePoint site: {0}", 
                    "Contribute", "vti_associatemembergroup", 
                    spWeb.ParentWeb.AssociatedMemberGroup, copyUsersFromParent);

                case AssociatedGroupTypeEnum.Vistors:
                    return AddGroup(spWeb, spWeb.Name + " Vistors", "Use this group 
                    to give people read 
                    permissions to the SharePoint site: {0}", "Read", 
                   "vti_associatevisitorgroup", 
                    spWeb.ParentWeb.AssociatedVisitorGroup, copyUsersFromParent);
                default:
                    return null;
            }
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, string groupName, string 
        descriptionFormatString, string roleDefinitionName,string associatedGroupName,
        SPGroup parentAssociatedGroup, bool 
        copyUsersFromParent)
        {
            SPGroup owner = parentAssociatedGroup;
            if (associatedGroupName != "vti_associateownergroup")
            owner = spWeb.SiteGroups.GetByID(int.Parse(spWeb.Properties
                         ["vti_associateownergroup"]));
            spWeb.SiteGroups.Add(groupName, owner, null, 
                                 string.Format(descriptionFormatString, 
            spWeb.Name));
            SPGroup group = spWeb.SiteGroups[groupName];
            if (descriptionFormatString.IndexOf("{0}") != -1)
            {
                SPListItem item = spWeb.SiteUserInfoList.GetItemById(group.ID);
                item["Notes"] = string.Format(descriptionFormatString, 
                string.Format("<a href=\"{0}\">{1}</a>", spWeb.Url, spWeb.Name));
                item.Update();
            }
            if (roleDefinitionName != null)
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
                SPRoleDefinition roleDefinition = spWeb.RoleDefinitions
                [roleDefinitionName];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                spWeb.RoleAssignments.Add(roleAssignment);
            }
            if (copyUsersFromParent && parentAssociatedGroup != null)
                foreach (SPUser user in parentAssociatedGroup.Users)
                    group.AddUser(user);
            if (associatedGroupName != null)
            {
                spWeb.Properties[associatedGroupName] = group.ID.ToString();
                spWeb.Properties.Update();
            }
            spWeb.Update();
            return group;
        }
    }
}

Wednesday, April 20, 2016

Event Receivers - SharePoint 2013

An event receiver has a set of base classes that can contains one or more methods known as event handlers that are executed automatically by SharePoint in response to events such as adding or deleting item to a list/library. You can use event handlers for the different operations on different lists, document libraries and content types.


Types of Event Receivers:


  1. Synchronous - Events are executed before the action is executed on the content database.

         Events ending with -ing are named as Synchronous Event Receivers
         Ex. Item Deleting,Item Adding.
    2.  A Synchronous - Events are executed after the action is executed on the content database.

         Events ending with -ed are named as Synchronous Event Receivers
         Ex. Item Deleted,Item Added.

Different Base Classes in Event Receivers:

     There are totally 5 base classes in SharePoint 2010,
  1. SPItemEventReceiver - Event at List item Level.
  2. SPListEventReceiver - Event at List Level.
  3. SPFeatureEventReceiver - Event activation and Deactivation at list level.
    1. FeatureInstalled: Right after feature is installed.
    2. FeatureActivated: Right after feature activation through “Site Settings” or otherwise.
    3. FeatureDeactivated: Right after feature deactivation through “Site Settings” or otherwise.
    4. FeatureUninstalled: Before feature is uninstalled.
  4. SPEmailEventReceiver :Event to send mail to list
  5. SPWebEventReceiver : Event at Web Site Level.(Site added,site deleted,etc..)
Disabling and Enabling the event Receiver

If we are modifying/updating the same List item using event receiver,then the event receiver is triggered
 again and again.So you have to prevent it from firing before you update changes to the list item. 
We can implement this functionality using EnableEventFiring attribute to true/false.

Example:
   public override void ItemAdded(SPItemEventProperties properties)
    {
        //will disable the event receiver
        EventFiringEnabled = false;
        
        //do some action on list like update List.Update()
 
        //will enable the event receiver
        EventFiringEnabled = true;
    }

Best practice is to set Disable EventFiring method right before any update action and Enable EventFiring
 method right after updating action has been completed.