My customer had a requirement of bulk update of account records with email “string” , based on the primary contact email value.
Scenario : Account Records don’t have a email value from primary contact’s record.
So I have chosen to write a plugin to bulk update.
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 MallaSolutions
{
public class UpdateAccounts : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Get a reference to the Organization service.
IOrganizationServiceFactory factory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
Entity entity;
if (context.InputParameters != null)
{
entity = (Entity)context.InputParameters[“Target”];
string fetchXML = @”<fetch distinct=’false’ mapping=’logical’ output-format=’xml-platform’ version=’1.0′>
<entity name=’account’>
<attribute name=’accountid’ />
<attribute name=’emailaddress1′ />
<order descending=’false’ attribute=’emailaddress1′ />
<filter type=’and’>
<condition attribute=’primarycontactid’ operator=’not-null’ />
</filter>
<link-entity name=’contact’ to=’primarycontactid’ from=’contactid’ alias=’PrimaryContact’ link-type=’outer’ visible=’false’>
<attribute name=’emailaddress1′ alias=’contactEmailAddress’ />
</link-entity>
</entity>
</fetch>”;
EntityCollection entityCollection = service.RetrieveMultiple(new FetchExpression(fetchXML));
for (int i = 0; i < entityCollection.Entities.Count; i++)
{
AliasedValue contactemailaddress = entityCollection.Entities[i].GetAttributeValue<AliasedValue>(“contactEmailAddress”);
if (contactemailaddress != null)
{
Entity account = new Entity(“account”);
account.Attributes[“accountid”] = entityCollection.Entities[i].Attributes[“accountid”];
account.Attributes[“emailaddress1”] = entityCollection.Entities[i].GetAttributeValue<AliasedValue>(“contactEmailAddress”).Value.ToString();
service.Update(account);
}
}
}
else
{
return;
}
}
}
}
====================================================================
Plugin Registration tool steps:
Message: Update
Primary Entity : Account
Filtering attributes : address1_city
event: post-opeartion
execution mode: Asynchronus
deployment: Server
I have registered asynchronous mode as the system will have performance impact if it is selected as Synchronous mode and it will time out after 2 min, as in my case , I am using dynamics 365 online.
We can increase time limit of plugin if it is dynamics 365 onpremise.
I hope this helps:-)
Cheers guys….