Blocking Duplicate Quotes in Dynamics 365 Sales Professional / Enterprise (C#)

Blocking Duplicate Quotes in Dynamics 365 Sales Professional / Enterprise (C#)
Featured image of post Blocking Duplicate Quotes in Dynamics 365 Sales Professional / Enterprise (C#)

As you might be able to tell from other recent blog posts, I’ve been doing lots of work lately with Dynamics 365 Sales and, specifically, the Professional variant of the application. Sales Professional can be best thought of as a “lite” CRM system, with much of the same type of functionality as we’d expect from the full-blown Enterprise application. I’ve blogged previously on the subject of differences between the two versions. The only major thing you lose with the Professional application is access to things like Competitors and restrictions on the number of custom tables that you can include as part of your solution. It’s worth consulting the licensing guide to break down the differences in detail before making a decision. Still, if you are in the market for your very first CRM system, you can’t go far wrong with considering Dynamics 365 Sales Professional.

As was the case with last week’s jolly jaunt into Dynamics 365 Sales, I was dealing yet again with another unusual requirement. In this case, the organisation in question wanted to have it so that only a single Draft Quote could ever exist for an Opportunity in the system. As part of the solution, some additional automation and reporting requirements relied upon information present within the most current Quote issued to Customers and salespeople in the organisation were, very often, creating multiple Quotes without realising. So we needed an approach that would prevent the duplicates from ever getting made. Duplicate Detection Rules provide a mechanism to discourage users from creating duplicate rows, but users could still override this if they felt mischievous. Therefore, we decided that a server-side solution and, specifically, a C# plug-in would be required to prevent duplicates from being created altogether. As far as I know, this is the only way we can meet such a requirement; answers on a postcard, though, if you think there’s a better way. 😉 With all of this in mind then, below is the code that was implemented to achieve the requirement:

namespace JJG.MyPlugins
   using System;
   using Microsoft.Xrm.Sdk;
   using Microsoft.Xrm.Sdk.Query;

   /// <summary>
   /// Blocks the Create or Update action for a Quote, if it's detected that another Draft Quote exists linked to the same Opportunity.
   /// </summary>
   public class BlockDuplicateQuoteForOpportunity : IPlugin
      public void Execute(IServiceProvider serviceProvider)
         IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
         ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

         // Check for EntityType and Message supported by your Plug-In
         if (!(context.MessageName == "Create" || context.MessageName == "Update") || context.PrimaryEntityName != "quote")
            throw new InvalidPluginExecutionException($"Plug-In {this.GetType()} is not supported for message {context.MessageName} of {context.PrimaryEntityName}");

         tracer.Trace($"Starting execution of {nameof(BlockDuplicateQuoteForOpportunity)}");

         // Get the newly create Quote (Create) or the Post Image for the Quote (Update), and the Opportunity lookup value
         Entity quote = (Entity)context.InputParameters["Target"];
         EntityReference opportunity = quote.GetAttributeValue<EntityReference>("opportunityid");

         if (opportunity == null)
            tracer.Trace($"No Opportunity is present for Quote ID {quote.Id}. Cancelling plug-in execution");

         // Attempt to retrieve other Draft Quotes that are linked to the same Opportunity ID we have here
         tracer.Trace($"Attempting to retrieve other Quote rows linked to Opportunity ID {opportunity.Id}...");

         IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
         IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

         QueryExpression qe = new QueryExpression()
            EntityName = "quote",
            ColumnSet = new ColumnSet("quoteid"),
            Criteria =
               Conditions =
                  new ConditionExpression("opportunityid", ConditionOperator.Equal, opportunity.Id),
                  new ConditionExpression("statecode", ConditionOperator.Equal, 0),
                  new ConditionExpression("quoteid", ConditionOperator.NotEqual, quote.Id),

         EntityCollection quotes = service.RetrieveMultiple(qe);
         tracer.Trace($"Got {quotes.Entities.Count} Quotes!");

         // If one or more exist, then we throw an error to block the Create / Association
         if (quotes.Entities.Count >= 1)
            tracer.Trace($"Multiple Draft Quotes exist for Opportunity ID {opportunity.Id}. Throwing error to cancel operation...");
            throw new InvalidPluginExecutionException("Draft Quote(s) already exist for the selected Opportunity. Only a single Draft Quote is allowed. Please edit or delete the other Draft Quote(s) before proceeding.");
            tracer.Trace($"No other Draft Quotes are linked to Opportunity ID {opportunity.Id}. No action required. Cancelling plug-in execution");

When registering this plug-in into the application, ensure that it’s aligned to the Post-Operation step on the following messages indicated below:

For the Update step, we also specifically filter on just the opportunityid row, to ensure the plug-in doesn’t fire unnecessarily:

When the user then attempts to create or associate more than one Quote to a single Opportunity, this will be the error message they will receive:

Because the plug-in throws the InvalidPluginExecutionException error message, the platform will roll back the entire transaction. We can then inject our own custom message into the dialog that appears.

As alluded to earlier, having a low/no-code solution to achieve this requirement would be preferred. But, unless I’m missing something obvious, doing something similar via a real-time workflow would be impossible due to the RetrieveMultiple request we have to perform to get other pre-existing Quotes. As much as I make a living out of implementing these types of solutions, we should always be cautious of adopting a code-first mindset if other routes are available to us within Dynamics 365 Sales and the Power Platform. Take care to understand the “baggage” involved with a solution like this so that you don’t get caught out in future as part of an upgrade or when you later incorporate additional functionality into the equation.

Published on:

Learn more
The CRM Chap
The CRM Chap

Anything and everything to do with the #PowerPlatform, #MSDYN365, #Azure and more!

Share post:

Related posts

Interview Questions and Answers Dynamics 365 CE and Power Platform – Ultimate Guide

In today's business landscape, Dynamics 365 Customer Engagement (CE) and the Power Platform have emerged as game-changing tools that have tran...

12 days ago

Back to Basics # 72: Limit Special Characters Using a Webresource in Dynamics CRM

Recently we got a requirement to restrict user to enter special characters. Step 1 : Use the below method for restricting special characters S...

20 days ago

{How to} Get real time tips and suggested answers during Teams meetings on Dynamics 365 Sales

Hello Everyone,Today I am going to share my thoughts on the real time tips and suggested answers during Teams meetings on Dynamics 365 Sales.L...

27 days ago

Leveraging Copilot in Dynamics 365 Sales to prepare for sales meeting

In today’s rapidly evolving sales environment, staying ahead of the curve is more crucial than ever. The post Leveraging Copilot in Dynamics ...

28 days ago

{How to} Allow sellers to track performance with out of box forecasting in Dynamics 365 Sales

If you're looking to improve your sales performance using Dynamics 365 Sales, this tutorial is the right resource for you. By using the out-of...

29 days ago

Elevating email efficiency using Copilot in Dynamics 365 Sales and the rich text editor 

In today's digital age, effective communication is key to build and maintain strong business relationships and accelerate sales success. As su...

1 month ago

Transform seller effectiveness with Dynamics 365 Sales Copilot

If you want to boost your sales team's productivity, Dynamics 365 Sales Copilot might just be the solution you're looking for. With natural-la...

1 month ago

20 Most commonly used JavaScript Scenarios with Sample code Snippet in Form Script Dataverse/ Dynamics 365 CE

JavaScript is a powerful tool for developers working with Dataverse (formerly known as Common Data Service) and Dynamics 365 Customer Engageme...

1 month ago

New and Retired Microsoft Dynamics 365 Certifications

Microsoft has recently shared updates regarding new and retired certifications for Microsoft Dynamics 365. This post provides an overview of t...

1 month ago
Stay up to date with latest Microsoft Dynamics 365 and Power Platform news!
* Yes, I agree to the privacy policy