Hello,
I created a plugin which is triggered when a user tries to deactivate an entity Movie; it should block the process if the movie is associated to an active entity of type Collection.
When I tried to deactivate some Movies the operation was always successful, no matter if they were related to an active Collection.
I'm debugging it and noticed that the current target is recognized, the following variable is not null:
var target = context.GetTarget();
Nonetheless, the following instruction throws the System.NullReferenceException:
Entity currentMovie = (Entity)context.InputParameters["Target"];
Can you please help me to understand why I get that exception and if the code is correct? I used if (collectionStateCode.Value == 0) to check if the state is active, is it correct?
Here is my code:
public void Execute(IServiceProvider serviceProvider)
{
var context = new PluginContext(serviceProvider);
var service = context.CrmServiceSystem;
var trace = context.TracingService;
var target = context.GetTarget();
if (target == null)
return;
Entity currentMovie = (Entity)context.InputParameters["Target";
// 2) Assuming that collection is a required field on the movie, get the collectionid
Guid collectionid= currentMovie .GetAttributeValue<EntityReference>("collection").Id;
// 3) Query the encyclopedia for the details I need:
var collectionEntity = service.Retrieve("collection", collectionid, new ColumnSet("statecode"));
// 4) get the values from the collection entity
OptionSetValue collectionStateCode = (OptionSetValue)collectionEntity .Attributes["statecode";
if (collectionStateCode.Value == 0)
{
throw new InvalidPluginExecutionException(OperationStatus.Failed,, "The movie cannot be disable because it is associated to an active collection.");
}
}