Loading...

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");
            return;
         }

         // 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.");
         }
         else
         {
            tracer.Trace($"No other Draft Quotes are linked to Opportunity ID {opportunity.Id}. No action required. Cancelling plug-in execution");
            return;
         }
      }
   }
}

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

Security Model of Dynamics CRM

Business Unit โ€“ It is a way to group business activities.When an organization is created, a Root Business Unit is created by default. Thi...

4 days ago

Dynamics 365 Sales – Connect AI agents to sales workflows using Model Context Protocol server

We are announcing the ability to connect Dynamics 365 Sales to your agents and assistants with the new Model Context Protocol server. This fea...

15 days ago

Dynamics 365 Sales – Improve sales efficiency with Sales Qualification Agent’s email validation

We are announcing the ability to use the Sales Qualification Agent to validate email addresses in Dynamics 365 Sales. This feature will reach ...

15 days ago

How to Use Copilot Custom Prompts and AI Builder in Dynamics 365 Sales

This blog builds on our previous article, How to Configure and Use the Prompt Column in Dataverse, which you can read here. While that post fo...

15 days ago

We need to talk about... Dynamics 365 Sales... Sales Qualification Agents

Next in my blog, I wanted to talk about a new feature which is part of the recent release wave for 2025. The Sales Qualification Agent...

17 days ago

Dynamics 365 Sales – Get embedded experience for Copilot summaries

We are announcing an embedded experience for Copilot summaries in Dynamics 365 Sales. This feature will reach general availability on Septembe...

22 days ago

Dynamics 365 Sales – Sales Qualification Agent is now fully autonomous

We are announcing that the Sales Qualification Agent for Dynamics 365 Sales is now fully autonomous. This updated feature is currently being r...

1 month ago

I recreated Dynamics CRM with the Power Platform Plan designer

In January 2003 after many months of engineering and development, Microsoft released one of the first business solutions built-in house; Micro...

1 month ago

Introducing the new summary experience in Dynamics 365 Sales

Weโ€™re excited to announce a major upgrade to how sellers interact with Copilot summaries in Dynamics 365 Sales. Beginning with the 2025 Releas...

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