1
votes

My PLUGIN is firing on Entity A and in my code I am invoking a web service that returns an XML file with some attributes (attr1,attr2,attr3 etc ...) for Entity B including GUID. I need to update Entity B using the attributes I received from the web service.

Can I use Service Context Class (SaveChanges) or what is the best way to accomplish my task please? I would appreciate it if you provide an example.

1
Have you tried anything yourself yet? What event are you firing on? Which entities is it acting on? Is it CRM Online or on premise?glosrob
It is CRM On Premise and it is firing on Update.Nick

1 Answers

2
votes

There is no reason you need to use a service context in this instance. Here is basic example of how I would solve this requirement. You'll obviously need to update this code to use the appropriate entities, implement your external web service call, and handle the field updates. In addition, this does not have any error checking or handling as should be included for production code.

I made an assumption you were using the early-bound entity classes, if not you'll need to update the code to use the generic Entity().

class UpdateAnotherEntity : IPlugin
{

    private const string TARGET = "Target";

    public void Execute(IServiceProvider serviceProvider)
    {

        //PluginSetup is an abstraction from: http://nicknow.net/dynamics-crm-2011-abstracting-plugin-setup/
        var p = new PluginSetup(serviceProvider);

        var target = ((Entity) p.Context.InputParameters[TARGET]).ToEntity<Account>();

        var updateEntityAndXml = GetRelatedRecordAndXml(target);

        var relatedContactEntity =
            p.Service.Retrieve(Contact.EntityLogicalName, updateEntityAndXml.Item1, new ColumnSet(true)).ToEntity<Contact>();

        UpdateContactEntityWithXml(relatedContactEntity, updateEntityAndXml.Item2);

        p.Service.Update(relatedContactEntity);

    }

    private static void UpdateContactEntityWithXml(Contact relatedEntity, XmlDocument xmlDocument)
    {
        throw new NotImplementedException("UpdateContactEntityWithXml");
    }

    private static Tuple<Guid, XmlDocument> GetRelatedRecordAndXml(Account target)
    {
        throw new NotImplementedException("GetRelatedRecordAndXml");
    }


}