Creating records on behalf of another user in Microsoft Dynamics CRM 2011

This post will help you guys to create records on behalf of another user in CRM 2011. Well are you thinking what is the advantage of doing this and how different is this from normal import?

Certainly there is an advantage if you want to create records on behalf of another user. The created by field will be updated by the name of the user whom you want to use instead of using your own name. This leads to the concept of impersonation in CRM 2011.

 using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
 serverConfig.HomeRealmUri,
 serverConfig.Credentials,
 serverConfig.DeviceCredentials))
 {
 // This statement is required to enable early-bound type support.
 _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
 
 // Retrieve the system user ID of the user to impersonate.
 OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
 _userId = (from user in orgContext.CreateQuery<SystemUser>()
 where user.FullName == "FirstName LastName"
 select user.SystemUserId.Value).FirstOrDefault();
 
 // To impersonate another user, set the OrganizationServiceProxy.CallerId
 // property to the ID of the other user.
 _serviceProxy.CallerId = _userId;
 Entity contact = new Entity("contact");
 contact["firstname"] = "Vishnu";
 contact["lastname"] = "Nandan";
 Guid contactId = _serviceProxy.Create(contact);
 }
   
 In this code we will update the callerid in the serviceProxy with the userid that you want to impersonate. 
  
 This will help you to create records on behalf of another user. 
 Cheers!!!