1

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?

Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93

2 Answers2

2

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.

Jeff Xiong
  • 213
  • 1
  • 9
1

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

Guido Preite
  • 14,905
  • 4
  • 36
  • 65
  • By using `OrganizationServiceProxy` i can do the same operation by assigning the result to Early-Bound classes. But why i can't use it? The plugin can be invoked by any user and in order to create the `OrganizationServiceProxy` instance i need to have the plugin user credentials. Currently i am using administrator credentials in order to initiate and do the same operation successfully. – Furqan Safdar Jul 28 '13 at 06:39
  • If you put your early bound classes in a separate assembly and your plugin can't find that assembly you get the exception. This have nothing to do with OrganizationServiceProxy or with the credentials. – Guido Preite Jul 28 '13 at 07:58