Wednesday, July 13, 2011

Sharing and Unsharing Records in CRM 2011

Hi All, Here I am going to share Account record with a user and then unsharing the account from the user in CRM 2011. Here is the logic to share and unshare records

sharing

 // Create the request object and set the target and principal access
GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target = new EntityReference(Account.EntityLogicalName, accountId),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal = new EntityReference(SystemUser.EntityLogicalName, userId),
                    AccessMask = actionRights
                }
            };

 // Execute the request.
GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grantRequest);


Unsharing


 // Create the request object and set the target and revokee.
            RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
            {
                Target = new EntityReference(Account.EntityLogicalName, accountId),
                Revokee = new EntityReference(SystemUser.EntityLogicalName, accountuserId)
            };

// Execute the request.
 RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revokeRequest);

3 comments:

  1. Is there a way to automate this script so that for example on an opportunity I can have a "secondary contact" lookup field that is an internal user I would like to automatically share the record with if there username is listed in that "Secondary Contact" field?

    ReplyDelete
    Replies
    1. Hi Carl,

      You can write a plugin to do sharing & unsharing on update of "Secondary Contact" field. that way you can automate sharing/unsharing on the opportunity.

      Thanks,
      Guru

      Delete
    2. I know it too late but Why don't you use oob relationship cascading rules.

      Delete