0
votes

I am trying to update the telephone number on all associated contacts of an account entity. the following is the code that i have used,

public class Plugin:IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)
        serviceProvider.GetService(typeof(IPluginExecutionContext));

        Entity entity;


        if (context.InputParameters.Contains("Target") &&
        context.InputParameters["Target"] is Entity)
        {

            entity = (Entity)context.InputParameters["Target"];

            if (entity.LogicalName != "account") { return; }
        }
        else
        {
            return;
        }

        try
        {
            string telephoneNum = string.Empty;
            IOrganizationServiceFactory serviceFactory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service =serviceFactory.CreateOrganizationService(context.UserId);

            var id = (Guid)context.OutputParameters["id"];
            telephoneNum = entity.GetAttributeValue<string>("telephone1");
            UpdateContact(service, id,telephoneNum);
        }
        catch (FaultException<OrganizationServiceFault> ex)
        {
            throw new InvalidPluginExecutionException(
            "An error occurred in the plug-in.", ex);
        }
    }

    private static void UpdateContact(IOrganizationService service, Guid id,string telephoneNUm)
    {
        using (var crm = new XrmServiceContext(service))
        {

            var res = from c in crm.CreateQuery("contact")
                      where c["parentcustomerid"].Equals(id)
                      select c;

            foreach (var c in res)
            {
                Entity e = (Entity)c;
                e["telephone1"] = telephoneNUm;
                crm.UpdateObject(e);
            }


            crm.SaveChanges();
        }
    }
}

I register the plugin on update, and primary entity "account" but whenever i try to save the account form after change of number in the telephone field i see an error pop up. Am i missing something? Thank you all!

1
Can you specify which error is pop up. If it's a generic error please active trace or use this tool to get a full error information.Pedro Azevedo

1 Answers

0
votes

Just a hunch..but I think you are getting the Id in the wrong way..try getting it by:

Guid Id = context.PrimaryEntityId

But as Pedro suggested..you need to see what is the exact error or try to debug the plugin using attach to process..