Hello,
I have registered a Plugin onUpdate of account. My requirement is - when I update the description filed in my Account entity, I want to auto-update then same value in all Contact of that related Accounts.
Now, I am getting An unexpected error occurred from ISV code. Error on Save Form
Here Is the code I used:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace CFT158SalesPlugins
{
public class AccountUpdate : IPlugin
{
IOrganizationService service; Entity currentEntity;
IPluginExecutionContext context;
ITracingService trace;
///
/// Initializes common parameters to set the IPluginExecutionContext and IOrganizationServiceFactory.
///
/// Object of IServiceProvider
private void GetOrganizationService(IServiceProvider serviceProvider)
{
try
{
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(context.UserId);
trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
}
catch(Exception ex)
{
}
}
private void GetRecordContext()
{
try
{
currentEntity = (Entity)context.InputParameters["Terget"];
if (currentEntity.Attributes.Contains("new_description"))
{
string description = currentEntity.GetAttributeValue("new_description");
GetAllChildRecords(description);
}
}
catch (Exception)
{
throw;
}
}
private void GetAllChildRecords(String description)
{
try
{
String fetchXML = @"
< entity name = 'contact' >
< attribute name = 'fullname' />
< attribute name = 'telephone1' />
< attribute name = 'contactid' />
< order attribute = 'fullname' descending = 'false' />
< filter type = 'and' >
< condition attribute = 'parentcustomerid' operator= 'eq' value = '{" currentEntity.Id.ToString() @"}' />
";
EntityCollection retrievedContacts = service.RetrieveMultiple(new FetchExpression(fetchXML));
if (retrievedContacts.Entities.Count > 0)
{
foreach (Entity e in retrievedContacts.Entities)
{
Entity contactUpdate = new Entity("contact");
contactUpdate["description"] = description;
contactUpdate.Id = e.Id;
service.Update(contactUpdate);
}
}
}
catch (Exception)
{
throw;
}
}
public void Execute(IServiceProvider serviceProvider)
{
try
{
GetOrganizationService(serviceProvider);
GetRecordContext();
}
catch(Exception)
{
throw;
}
}
}
}