Impersonation in C# App for D365

We can impersonate a user in console app or any 3rd party code my passing the Guid of impersonated user in the CallerId field of CrmServiceClient object. Below is sample code:

If we are retrieving a FLS field then the impersonating user and impersonated user both should have access to the field. If either doesn’t have access then no value is returned.

static void Main(string[] args)
{
    string ConnectionStringOAuth = @"AuthType = OAuth;
                                     Username = xxxxxx@xxxxxx.onmicrosoft.com;
                                     Password = xxxxxx;
                                     Integrated Security=true;
                                     Url = https://xxxxxx.crm.dynamics.com;
                                     AppId = xxxxxx;
                                     RedirectUri = https://xxxxxxxx;
                                     LoginPrompt=Auto";
    CrmServiceClient svc = new CrmServiceClient(ConnectionStringOAuth);
    svc.CallerId = Guid.Parse("{60FBEAFB-7724-EB11-A813-000D3A569CF5}");

    var cs = svc.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 value = cs.Entities.Count != 0 ?
     (cs.Entities[0].Attributes.Contains("ps_value") ?
     cs.Entities[0].Attributes["ps_value"].ToString() : string.Empty) :
 string.Empty;

     Entity task = new Entity("task")
     {
          Attributes = new AttributeCollection()
          {
               new KeyValuePair<string, object>("regardingobjectid",
               new EntityReference("contact", Guid.Parse("{87D4EF7F-DE38-EB11-A813-0022481BFEB4}"))),
               new KeyValuePair<string, object>("subject", value)
          }
     };
     var newRecord = svc.Create(task);
     Console.ReadLine();
}

Possible Error :

contextUserId=<impersonating userid> is missing privilege <Privilege GUID>. Parameter’user’=<impersonated userid>, callerId=<impersonated userid>.

This error will occur if privilege prvActOnBehalfOfAnotherUser is missing on impersonating user.

Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: