You might have a situation where you would need to create or migrate records to dynamics using a console app or using any other platforms programmatically, and you don’t want to trigger plugins associated with the targeted entity. In this post, we would see as such a requirement can be met;
Here, I have created the below plugin and registered it to trigger on post Operation of entity Create, in this case, Account entity.
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
Random victorId = new Random();
entity.Attributes["new_formid"] = victorId.Next(010, 01000);
service.Update(entity);
}
}
The above code will populate a field with random numbers on create of an account record.
Below, I am creating account records in a console App using an in memory list data created;
class Program
{
private static readonly string crmConnection = @"AuthType=ClientSecret;Url=https://smart.crm11.dynamics.com;ClientId=732ea702-000d-455cxxxxxxxxxxxxxxx;ClientSecret=-xxxxxxxxxxxxxxxxxx.";
static CdsServiceClient service = new CdsServiceClient(crmConnection);
static void Main(string[] args)
{
List<string> accountNames = new List<string>
{
"victor","Lambo","Royce","Kool-g"
};
foreach (var item in accountNames)
{
Entity account = new Entity("account");
account.Attributes["name"] = item;
CreateRequest acctCreate = new CreateRequest();
acctCreate.Parameters["BypassCustomPluginExecution"] = true;
acctCreate.Target = account;
service.Execute(acctCreate);
Console.WriteLine($"Create {item}");
}
}
}
With this line acctCreate.Parameters[“BypassCustomPluginExecution”] = true, you are telling dynamics API to ignore any plugin registered against the entity. The below is the output of records created and the one created with the plugin running:
The highlighted are the records created using the console App.