Sunday, April 21, 2024

Duplicate Detection using Plugin in Dynamics 365 / Power Platform

Duplicate Detection in Power App using Plugin - Dynamics 365 / Power Platform

Introduction:

This blog will show you how to create Plugin in Dynamics 365 to stop users from saving records and display error messages. While you could use Out of the Box Duplicate detection rule but it won't prevent from saving the record. We can also use Duplicate Detection using Keys Click here to see Video.

Scenario: Create a plugin(Pre-Validation) for checking duplicate driving license on case form. Within the Case main form, there exists a text field named driving license. I've developed a plugin designed to restrict users from creating a new case if a duplicate driving license value already exists in any driving license record. Upon providing a driving license value during case creation, the plugin retrieves records from the driving license entity where the driving license attribute matches the entered value.

Refer to this video for a detailed implementation guide for creating Plugin-


What is Plugin?

A plugin is defined as a custom business logic that can be installed in Microsoft Dynamics CRM to make customizations or to enhance the standard behavior of the platform. Plugins help in handling various events and each plugin executes a specific event. In general, the Plug-ins are written in VB or C# can run an asynchronous or synchronous mode.

Before creating the plugin, ensure you have the following prerequisites in place-

  • Visual Studio with .Net Framework 4.6.2
  • Plugin Registration Tool
  • Understanding of Plugin Development:

Plugin code here





JavaScript Code for showing custom message in dialog box-

Create a Visual Studio project for the plug-in

  1. Open Visual Studio and open a new Class Library (.NET Framework) project using .NET Framework 4.6.2

    Open a new class library (.NET Framework) project using .NET Framework 4.6.2.

    The name used for the project is also the name of the assembly. This tutorial uses the name DuplicateDrivingLicencePlugin.

  2. In Solution Explorer, right-click the project and select Manage NuGet Packages… from the context menu.

    Manage NuGet packages.

  3. Select Browse and search for Microsoft.CrmSdk.CoreAssemblies and install the latest version.

    Install Microsoft.CrmSdk.CoreAssemblies NuGet Package.

  4. You must select I Accept in the License Acceptance dialog.
    Note - Adding the Microsoft.CrmSdk.CoreAssemblies NuGet package will include these assemblies in the build folder for your assembly, but you will not upload these assemblies with the assembly that includes your logic. These assemblies are already present in the sandbox runtime.

  5. In Solution Explorer, right-click the Class1.cs file and choose Rename in the context menu.

    Rename class.

  6. Rename the Class1.cs file to DuplicateDrivingLicence.cs.

  7. When prompted, allow Visual Studio to rename the class to match the file name.

    Confirm rename dialog.

    Paste below plugin code - 

    using System;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    
    namespace DuplicateDrivingLicence
    {
        public class DuplicateDrivingLicencePlugin : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                try
                {
                    // Check if the plugin is running in the pre-operation stage and for the intended entity
                    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                    {
                        Entity targetEntity = (Entity)context.InputParameters["Target"];
    
                        // Check if the target entity is the "incident" entity and contains the "new_drivinglicence" field
                        if (targetEntity.LogicalName == "incident" && targetEntity.Contains("new_drivinglicence"))
                        {
                            // Retrieve the driving licence value from the case record
                            string drivinglicenceValue = targetEntity.GetAttributeValue<string>("new_drivinglicence");
    
                            // Check for duplicate driving licence records
                            if (IsDuplicateDL(service, drivinglicenceValue))
                            {
                                throw new InvalidPluginExecutionException("Duplicate driving licence value found. Cannot create the case.");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracingService.Trace($"Exception: {ex.Message}");
                    throw;
                }
            }
    
            private bool IsDuplicateDL(IOrganizationService service, string drivinglicenceValue)
            {
                // Query to retrieve driving licence records with the provided value
                QueryExpression query = new QueryExpression("new_drivinglicence")
                {
                    ColumnSet = new ColumnSet("new_drivinglicence"),
                    Criteria = new FilterExpression()
                    {
                        Conditions =
                        {
                            new ConditionExpression("new_drivinglicence", ConditionOperator.Equal, drivinglicenceValue)
                        }
                    }
                };
    
                EntityCollection results = service.RetrieveMultiple(query);
    
                // If there are any matching records, it's a duplicate
                return results.Entities.Count > 0;
            }
        }
    }

About the code

The above plugin, 'DuplicateDrivingLicencePlugin', aims to prevent duplicate driving license entries when creating case records in Dynamics 365. 
  • 1. Main Logic: It checks if the plugin is triggered in the pre-operation stage for case records containing the "new_drivinglicence" attribute.
  • 2. If so, it retrieves the driving license value from the case record.
  • 3. It then queries the "new_drivinglicence" entity to check for duplicates using the `IsDuplicateDL` method.
  • 4. The `IsDuplicateDL` method constructs a query to find records with matching driving license values.
  • 5. If duplicates are found, the plugin throws an exception, preventing the creation of the case.
  • 6. Exception handling ensures graceful error management with tracing for debugging purposes.
  • 7. This approach ensures data integrity by validating driving license entries before case creation.

Build plug-in

In Visual Studio, press F6 to build the assembly. Verify that it compiles without error

Sign the plug-in

  1. In Solution Explorer, right-click the DuplicateDrivingLicencePlugin project and in the context menu select Properties.

    Open project properties.

  2. In the project properties, select the Signing tab and select the Sign the assembly checkbox.

    Sign the assembly.

  3. In the Choose a strong name key file: dropdown, select <New…>.

  4. In the Create Strong Name Key dialog, enter a key file name, and deselect the Protect my key file with a password checkbox.

  5. Select OK to close the Create Strong Name Key dialog.

  6. In the project properties Build tab, verify that the Configuration is set to Debug.

  7. Press F6 to build the plug-in again.

  8. Using windows explorer, find the built plug-in at: \bin\Debug\DuplicateDrivingLicencePlugin.dll.

Register plug-in
To register a plug-in, you'll need the Plug-in Registration tool.

Connect using the Plug-in Registration tool

  1. After you have downloaded the Plug-in registration tool, click the PluginRegistration.exe to open it.

  2. Click Create new Connection to connect to your instance.

  3. Make sure Office 365 is selected.

  4. If you are connecting using a Microsoft account other than one you are currently using, click Show Advanced and enter your credentials. Otherwise, leave Sign-in as current user selected.

  5. If your Microsoft Account provides access to multiple environments, select Display list of available organizations.

    Logging in with the Plug-in registration tool.

  6. Click Login.

  7. If you selected Display list of available organizations, select the organization you would like to connect to and click Login.

  8. After you are connected, you will see any existing registered plug-ins, custom workflow activities and data providers.

    View existing plug-ins an custom workflow activities.

Register your assembly

  1. In the Register drop-down, select New Assembly.

    Register new assembly.

  2. In the Register New Assembly dialog, select the ellipses () button and browse to the assembly you built in the previous step.

  3. For Microsoft 365 users, verify that the isolation mode is set to sandbox and the location to store the assembly is Database.

  4. Click Register Selected Plug-ins.

  5. You'll see a Registered Plug-ins confirmation dialog.


  6. Select OK to close the dialog and close the Register New Assembly dialog.

  7. You should now see the (Assembly) DuplicateDrivingLicencePlugin assembly, which you can expand to view the (Plugin) DuplicateDrivingLicencePlugin plugin.



Register a new step

  1. Right-click the (Plugin) DuplicateDrivingLicencePlugin and select Register New Step.



  2. In the Register New Step dialog, set the following fields

    SettingValue
    MessageCreate
    Primary Entityaccount
    Event Pipeline Stage of ExecutionPostOperation
    Execution ModeAsynchronous
    • Select Register New Step to complete the registration and close the Register New Step dialog.

    • You can now see the registered step.



    Test plug-in

    1. Open a your app and create a new case record with existing driving licence

    2. You should get below error while saving record


    No comments:

    Post a Comment

    Followers

    Power Dynamix YouTube Videos