Thursday, April 5, 2018

Dynamics 365 Share and Un-Share Records Programmatically C#

Please refer to these codes, to Share Records, and Unshare Records.
/// <summary>
/// Shares the record.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="tracingService">The tracing service.</param>
/// <param name="targetEntity">The target entity.</param>
/// <param name="targetUser">The target user.</param>
private void ShareRecord(IOrganizationService service, ITracingService tracingService, EntityReference targetEntity, EntityReference targetUser)
{
    //no delete access
    GrantAccessRequest grant = new GrantAccessRequest();
    grant.Target = targetEntity;

    PrincipalAccess principal = new PrincipalAccess();
    principal.Principal = targetUser;
    principal.AccessMask = AccessRights.ReadAccess | AccessRights.AppendAccess | AccessRights.WriteAccess | AccessRights.AppendToAccess | AccessRights.ShareAccess | AccessRights.AssignAccess;
    grant.PrincipalAccess = principal;

    try
    {
        service.Execute(grant);
    }
    catch (Exception ex)
    {
        tracingService.Trace("Exception: {0}", ex.ToString());
        throw ex;
    }
}

/// <summary>
/// Un shares the record.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="tracingService">The tracing service.</param>
/// <param name="targetEntity">The target entity.</param>
/// <param name="targetUser">The target user.</param>
private void UnShareRecord(IOrganizationService service, ITracingService tracingService, EntityReference targetEntity, EntityReference targetUser)
{
    //no delete access
    ModifyAccessRequest modif = new ModifyAccessRequest(); ;
    modif.Target = targetEntity;

    PrincipalAccess principal = new PrincipalAccess();
    principal.Principal = targetUser;
    principal.AccessMask = AccessRights.None;
    modif.PrincipalAccess = principal;

    try
    {
        service.Execute(modif); ;
    }
    catch (Exception ex)
    {
        tracingService.Trace("Exception: {0}", ex.ToString());
        throw ex;
    }
}

No comments:

Post a Comment