I created a Plugin which is triggered while updating a Movie and shows an error when the fields "Title" and "Year" are left empty.
I also need to use PreImage to check whether the value is present in the pre-image but not in the target, i.e. if it was erased by the user.
I wrote the following code, but it doesn't work, can you please tell me if I'm using preImage and PostImage correctly?
public void Execute(IServiceProvider serviceProvider) { var context = new PluginContext(serviceProvider); var service = context.CrmServiceSystem; var trace = context.TracingService; var target = context.GetTarget(); var preImage = context.GetPreImage(); if (target == null) return; var postImage = preImage.Merge(target); // case 1: the field is left empty and it was empty before too: if((!preImage.Attributes.Contains("title") && !postImage.Attributes.Contains("title")) || // case 2: the field was not empty, but the user deleted the content: (preImage.Attributes.Contains("title") && !postImage.Attributes.Contains("title"))) { throw new InvalidPluginExecutionException(OperationStatus.Failed, "Title can't be null"); } if ((!preImage.Attributes.Contains("year") && !postImage.Attributes.Contains("year")) || (preImage.Attributes.Contains("year") && !postImage.Attributes.Contains("year"))) { throw new InvalidPluginExecutionException(OperationStatus.Failed, "Year is null!"); } }
For instance, I have this issue: when the Year is already correct and I don't modify it, I get the error "Year can't be null". As I merged the PreImage with the target, why the value is not recognized?