I am writing a Plugin to validate a quote before it saves. We want to make enforce that there must be a quote product line
item on a quote before a quote can be activated, won or lost. I wrote the following code and when pressing the "Close Quote"
button on the ribbion and selecting "Won" as the reason, a business process error box pops up with the error message. However,
upon closing the error message and refreshing the page, the quote is set to closed. Why does it close even though the exception
was thrown?
FYI, the plugin stage is set to Pre-operation.
Here is my source code:
public class QuoteValidation : IPlugin { private ITracingService tracingService; public void Execute(IServiceProvider serviceProvider) { // retrieve the context, factory, and service IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); // ensure we are handling the correct event and we were passed an entity from the context if (context.MessageName != "SetStateDynamicEntity" || !context.InputParameters.Contains("EntityMoniker")) return; // get the reference to the quote entity EntityReference quoteEntityReference = (EntityReference)context.InputParameters["EntityMoniker"]; // get the quote entity from the entity reference Entity quoteEntity = ActualEntity.GetActualEntity(quoteEntityReference, service); // ensure that we have the correct entity if (quoteEntity.LogicalName != "quote") return; // write query to retrieve all the details for this quote QueryExpression retrieveQuoteDetailsQuery = new QueryExpression { EntityName = "quotedetail", ColumnSet = new ColumnSet(), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "quoteid", Operator = ConditionOperator.Equal, Values = { (Guid)quoteEntity.Id } } } } }; // execute the query to retrieve the details for this quote EntityCollection quoteDetails = service.RetrieveMultiple(retrieveQuoteDetailsQuery); // retrieve the current status of the quote // 0 - Draft // 1 - Active // 2 - Won // 3 - Closed int quoteStatus = ((OptionSetValue)(quoteEntity.Attributes["statecode"])).Value; // if not in draft mode if (quoteStatus != 0) { // iif the amount of details for the quote is less than 1 if (quoteDetails.Entities.Count < 1) { throw new InvalidPluginExecutionException("There must be a quote product line item on a quote before a quote can be activated, won, or lost while not in draft mode."); } } } }
*This post is locked for comments