Impersonation in a plugin D365

We can impersonate any user in plugin code by passing user GUID to CreateOrganizationService of IOrganizationServiceFactory. Below is sample plugin code. The code is impersonating with user GUID and then creating task.

public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service;

                try
                {
                    service = serviceFactory.CreateOrganizationService(new Guid("60FBEAFB7724EB11A813000D3A569CF5"));
                    CreateTask(service, context);
                }

                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("Error: {0}", ex.ToString());
                    throw;
                }
            }
        }

In create task function, we are retrieving value from FLS field and then creating a task with that description. If user which we are impersonating doesn’t have access to FLS, we will get ‘Access Denied’ in description.

public void CreateTask(IOrganizationService service, IPluginExecutionContext context)
{
       var cs = service.RetrieveMultiple(new QueryExpression("ps_configurationsetting")
       {
            ColumnSet = new ColumnSet(true),
            Criteria =   {
                                Filters =
                                {
                                    new FilterExpression
                                    {
                                        FilterOperator = LogicalOperator.And,
                                        Conditions = {
                                            new ConditionExpression("ps_key", ConditionOperator.Equal, "azurekey")
                                        }
                                    }
                                }
                    }
        });

        string securevalue = cs.Entities.Count != 0 ?
            (cs.Entities[0].Attributes.Contains("ps_securevalue") ?
            cs.Entities[0].Attributes["ps_securevalue"].ToString() : "Access Denied") :
            string.Empty;

        Entity followupTask = new Entity("task");
        followupTask["subject"] = "Send e-mail .";
        followupTask["description"] = securevalue;
        followupTask["scheduledstart"] = DateTime.Now.AddDays(7);
        followupTask["scheduledend"] = DateTime.Now.AddDays(7);
        followupTask["category"] = context.PrimaryEntityName;
        if (context.OutputParameters.Contains("id"))
        {
            Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
            string regardingobjectidType = "contact";
            followupTask["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
        }
        service.Create(followupTask);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: