Tip #542: Who do you think you are

One of the great features of Dynamics CRM is the ability to impersonate other users’ accounts. Just set CallerId property on CrmConnection object and go on with your business as usual. However, make sure that your code or the code that you call, do not rely on the current user identity obtained using WhoAmIRequest. As it turns out, CRM impersonates all requests with the exception of WhoAmIRequest. Store caller identity and use it explicitly.

CrmConnection connection = new CrmConnection("Xrm");
// impersonate known (to us) user account
connection.CallerId = 
      new Guid("64D74566-C903-E511-80BA-00155D003523");

using (OrganizationService service = 
   new OrganizationService(connection))
{
    // this call will return the original caller, 
    // not impersonated one
    var userId = service.Execute<WhoAmIResponse>(
       new WhoAmIRequest()).UserId;

    // account, however, will have 
    // impersonated user as createdby
    Guid accountId = service.Create(
      new Entity("account")
      {
        Attributes = { { "name", "Acme Inc" } }
      });
}

Leave a Reply

Your email address will not be published. Required fields are marked *