ServiceContext (Early-Bound) retrieve causing InvalidCastException in CRM 2011 Plugin

2.2k views Asked by At

My question is quite related to this post but i am unable to assemble all the pieces together. I am trying to fetch SystemUser using ServiceContext object, XrmServiceContext via Linq in Plugin code as shown below:

var serviceFactory = serviceProvider.GetOrganizationServiceFactory();
var service = serviceFactory.CreateOrganizationService(context.UserId);
using (var xrmServiceContext = new XrmServiceContext(service))
{
    var user = xrmServiceContext.SystemUserSet
                   .Where(x => x.SystemUserId.Value == context.UserId)
                   .First();
}

But i am getting the following InvalidCastException:

Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type 'Xrm.SystemUser'.

Whereas the Early-bound classes generated through CrmSvcUtil placed in separate assembly (other than plugin assembly).

This is quite strange as if i place the generated Early-bound classes inside the plugin assembly it works just fine.

My little research led me to create separate OrganizationServiceProxy object but why should i create one when i am already creating IOrganizationService using serviceFactory.CreateOrganizationService(context.UserId)

So how to solve this issue by keeping generated code outside plugin assembly?

2

There are 2 answers

2
Guido Preite On

The behavior is not strange at all. If you put the Early-Bound classes in another assembly is quite normal that your plugin can't find it, specially if the assembly is not inside the server GAC (for example).

This because when you register a plugin, you register only the plugin dll, not all the referenced assemblies.

If you want to keep the generate code outside the plugin assembly you have two options:

  1. Register (and keep updated) the early bound assembly inside the GAC (if you are on-premise, online you can't do it)
  2. Use ILMerge to combine the two assemblies before you registered the plugin assembly

ILMerge link:

http://www.microsoft.com/en-us/download/details.aspx?id=17630

0
Jeff Xiong On

Add another suggestion: you can also put the early-bond assembly in C:\Program Files\Microsoft Dynamics CRM\CRMWeb\bin, if you chose opion register plugin in database when registering plugin.