Share Records in D365 CRM by Code
Views (26)
Introduction: This blog details steps how to share entity record in D365 CRM by Code.
Scenario: We have client requirement to share record with multiple set of Users in D365 CRM based on criteria selected by User on Form and needed to be automated.
Implementation Step:
Below code to be developed for OnCreate of record.
- Create new method ShareRecords
private static void ShareRecords(IOrganizationService service, Entity entity, Entity segmentUser) { var CreatedReference = new EntityReference("systemuser", segmentUser.Id); var grantAccessRequest = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.AppendToAccess, Principal = CreatedReference }, Target = new EntityReference(entity.LogicalName, entity.Id) }; service.Execute(grantAccessRequest); }
- Retrieve User List of Users and execute ShareRecords method
EntityCollection segmentUsers = service.RetrieveMultiple(new FetchExpression(fetchXMLUsers)); foreach(Entity segmentUser in segmentUsers.Entities) { ShareRecords(service, entity, segmentUser); }
Below code to be developed for OnUpdate of record.
- Create new method UnShareRecords
private static void UnShareRecords(IOrganizationService service, Entity entity, Entity segmentUser) { var CreatedReference = new EntityReference("systemuser", segmentUser.Id); var revokeUserAccessReq = new RevokeAccessRequest { Revokee = CreatedReference, Target = entity.ToEntityReference() }; service.Execute(revokeUserAccessReq); }
- Retrieve existing shared Users and remove there Access
private static void RetrieveSharedUsers(IOrganizationService service, EntityReference entityRef) { var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest { Target = entityRef }; var accessResponse = (RetrieveSharedPrincipalsAndAccessResponse) service.Execute(accessRequest); foreach(PrincipalAccess principalAccess in accessResponse.PrincipalAccesses) { EntityReference prAcc = principalAccess.Principal; Entity entity = new Entity(entityRef.LogicalName, entityRef.Id); Entity segmentUser = new Entity(prAcc.LogicalName, prAcc.Id); UnShareRecords(service, entity, segmentUser); } }
Implement code for ShareRecords explained in step 1 & step 2.
Conclusion: Hope this blog helps you to to share and unshare records by code in D365 CRM based on custom criteria data on record dynamically.
The post Share Records in D365 CRM by Code appeared first on .

Like
Report
*This post is locked for comments