Search code examples
pluginsdynamics-crm-2011fetchxml

How to use OrganizationServiceProxy on my Plugin - CRM 2011?


I need to use fetch xml in a CRM plugin, and I found here an example on how to do that:

string groupby1 = @" 
    <fetch distinct='false' mapping='logical' aggregate='true'> 
     <entity name='opportunity'>
      <attribute name='name' alias='opportunity_count' aggregate='countcolumn' />  
      <attribute name='ownerid' alias='ownerid' groupby='true' />
      <attribute name='createdon' alias='createdon' /> 
      <attribute name='customerid' alias='customerid' /> 
     </entity> 
    </fetch>";

    EntityCollection groupby1_result = orgProxy.RetrieveMultiple(new FetchExpression(groupby1));

but there's something else I don't know how to use, or where is it to use.. it's the part which says:

orgProxy.RetrieveMultiple(new FetchExpression(groupby1));

I Know it's an object of the OrganizationServiceProxy, but where is it in the plugin class? I couldn't find out.


Solution

  • In the politest way possible, you probably need to take a few steps backwards to go forwards.

    So to write a plugin, you need to implement IPlugin, which has just the one method

    public void Execute(IServiceProvider serviceProvider)
    

    The IServiceProvider is your window into CRM and the context of the event that you are hooking into.

    Typically, you would do something like:

    var context = (IPluginExecutionContext) serviceProvider.GetService(typeof (IPluginExecutionContext));
    var factory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
    var service = factory.CreateOrganizationService(context.UserId);
    

    In the example above, service is of type IOrganizationService. This gives you all the methods you would expect

    service.Execute(foo);
    service.RetrieveMultiple(bar);
    service.Update(... /* etc
    

    Might be worth reviewing some of the guides around this - as I've given in a previous answer here