Skip to content

CallerImpersonationScope cast error from ServiceClient #527

Description

I'd like to perform a Dataverse (CRM) operation using impersonation.

Something like the following:

using Microsoft.Extensions.Configuration;
using Microsoft.PowerPlatform.Dataverse.Client;           //using Microsoft.PowerPlatform.Dataverse.Client v. 1.2.10
using Microsoft.Xrm.Sdk;

var configuration = new ConfigurationBuilder()
    .AddUserSecrets(typeof(Program).Assembly)
    .Build();

var connectionString = configuration["CrmConnectionString"];

var crmClient = new ServiceClient(connectionString);
var targetUser = Guid.Parse("d3324a2d-600b-ee11-8f6e-000d3adf74aa");  //substitute for valid user ID different than the one from the connection

using var _ = new CallerImpersonationScope(crmClient, targetUser);
var account = new Entity("account") { ["name"] = "Impersonated Account" };
var accountId = await crmClient.CreateAsync(account);
Console.WriteLine($"Created account with Id: {accountId}");

The above compiles and connects (assuming a valid CrmConnection string is specified via User Secrets), but crashes when instantiating a new CallerImpersonationScope with the following exception:

System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast object of type 'Microsoft.PowerPlatform.Dataverse.Client.ServiceClient' to type 'System.ServiceModel.IContextChannel'.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Runtime.CompilerServices.CastHelpers.ChkCast_Helper(Void* toTypeHnd, Object obj)
   at Microsoft.Xrm.Sdk.CallerImpersonationScope..ctor(IOrganizationService service, Guid callerId)
   at Program.<<Main>$>d__0.MoveNext() in C:\GIT\Test\Program.cs:line 14

There's no indication that a ServiceClient cannot be used with CallerImpersonationScope, as it implements the expected IOrganizationService.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions