Impersonation in CRM Plug-In and Workflow – the easy way

Some time ago I wrote a post about impersonation in dynamics crm plug-ins.

Today I found a much easier solution: use the impersonated organizationService from localcontext.

IOrganizationService service = localContext.OrganizationServiceImpersonated;

Ok, first you have to create this property. Do this in Plugin.cs, which gets generated by Visual Studio. Create the property:

internal IOrganizationService OrganizationServiceImpersonated
    private set;

Add the following line to the constructor of LocalPluginContext:

// Use the factory to generate the impersonated Organization Service.
this.OrganizationServiceImpersonated = factory.CreateOrganizationService(null);

Instead of null you can also pass a systemusers GUID. Null will impersonate as systemadministrator.

And when you are just there, also set the ServiceProvider correctly, so that it’s not null. Then the whole constructor looks like this:

internal LocalPluginContext(IServiceProvider serviceProvider)
    if (serviceProvider == null)
        throw new ArgumentNullException("serviceProvider");

    // 1. extra line: Set LocalContext ServiceProvider
    this.ServiceProvider = serviceProvider;

    // Obtain the execution context service from the service provider.
    this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    // Obtain the tracing service from the service provider.
    this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    // Obtain the Organization Service factory service from the service provider
    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    // Use the factory to generate the Organization Service.
    this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);

    // 2. extra line: Use the factory to generate the impersonated Organization Service.
    this.OrganizationServiceImpersonated = factory.CreateOrganizationService(null);

To get impersonated service in Workflows is a little easier:

var serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
var service = serviceFactory.CreateOrganizationService(null);      //Create impersonated service

A proxy type with the name account has been defined by another assembly

I wanted to display different entities from Dynamics CRM in my SharePoint site using the CRM webservice. My code worked while I only had one solution, connection to CRM, deployed on my server. When I wrote a second application that is also using the webservice, I got the following error:
“A proxy type with the name account has been defined by another assembly.”

Here’s the solution. You just have to add a new ProxyTypesBehavior:

ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new NetworkCredential(username, password, domain);
credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
IServiceConfiguration<IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri(@"[...]/XRMServices/2011/Organization.svc"));
OrganizationServiceProxy client = new OrganizationServiceProxy(orgConfigInfo, credentials);
client.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior(Assembly.GetExecutingAssembly()));

Create records in CRM 2011 using the CRM Web Service

When I began to create records in CRM using the webservice, I started with records containing simple text fields. And there was no problem. The following method creates a new contact entity in CRM:

public static Guid createCandidate(OrganizationServiceClient serviceProxy, string firstname, string lastname, string email)

Entity application = new Entity() { LogicalName = "contact" };

// Set Contact Properties
AttributeCollection Attributes = new AttributeCollection();

Attributes.Add(new KeyValuePair<string, object>("firstname", firstname));
Attributes.Add(new KeyValuePair<string, object>("lastname", lastname));
Attributes.Add(new KeyValuePair<string, object>("emailaddress2", email));

application.Attributes = Attributes;

//Create Contact
Guid appGuid = serviceProxy.Create(application);

return appGuid;

But then I also wanted to fill OptionSet fields (DropDowns) and ReferenceEntity fields (LookUp). But the Webservice always threw an exception:

Die InnerException-Nachricht war “Der Typ “*.OptionSetValue” mit dem Datenvertragsnamen “OptionSetValue:” wurde nicht erwartet. Fügen Sie alle statisch nicht bekannten Typen der Liste der bekannten Typen hinzu. Verwenden Sie dazu z. B. das Attribut “KnownTypeAttribute”, oder fügen Sie die Typen der an DataContractSerializer übergebenen Liste von bekannten Typen hinzu.”.

After a long time I found the solution here:

1. Create a new class in your project with name you prefer.

2. Keep the namespace of this class similar to your Reference.cs (This is important so do not forget it)

3. Now create partial classes as below

public partial class Entity { }

public partial class EntityCollection { }

public partial class OrganizationRequest { }

4. Now go to your actual code, and for lookup field use like this:

Attributes.Add(new KeyValuePair<string,object>("parentcustomerid", new EntityReference() {Id = t.Id, LogicalName= t.LogicalName}));

5. Build the solution

Now everything should work as expectedt!

Impersonation of Service Executions in Plug-Ins and Workflows

A service execution can be impersonated by instantiating a ServiceProxy an setting the CallerId.
The Plug-In (and maybe Workflow) has to be registered as full trust (IsolationMode=”None”) to use the DefaultNetworkCredentials, otherwise they will be null. Set the isolationmode in registerfile.
If you use Early Binding, don’t forget to enable proxy types by calling serviceProxy.EnableProxyTypes().

protected void ExecutePreAccountUpdate(LocalPluginContext localContext)
    if (localContext == null)
        throw new ArgumentNullException("localContext");

    IPluginExecutionContext context = localContext.PluginExecutionContext;

    var clientCredentials = new ClientCredentials();
    // Using custom credentials
    credentials.Windows.ClientCredential = new NetworkCredential(, , );

    // Using Default Credentials
    // credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

    var orgUrl = "http:///XRMServices/2011/Organization.svc";
    var organizationServiceUri = new Uri(orgUrl);

    // To use SSL
    if (!string.IsNullOrEmpty(orgUrl) && orgUrl.Contains("https")) {
	ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

    using (var serviceProxy = new OrganizationServiceProxy(organizationServiceUri, null, clientCredentials, null))
        serviceProxy.CallerId = new Guid("AAB4EBA7-BDD1-E211-A6C5-00155D0B2738");    //Impersonating serviceProxy

        var newTask = new Task();
        newTask.Description = "ServiceProxy created Task";
        newTask.Subject = "ServiceProxy created";

        var newTaskGuid = serviceProxy.Create(newTask);

Blog post about the different userIds, when impersonating Plug-Ins, Dialogs and Workflows: