Skip to main content

Notifications

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

How to fix Error code: 0x80040265

Posted on by 35

Hi, I am stuck with this error. Can anyone assist me fix this? I am trying to create a duplicate detection plugin using the dynamics 365 duplicate detection sample.

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

namespace DuplicateDetectionPlugin
{
 public class DuplicateDetectionForCreateAndUpdate : IPlugin
    {
        private Guid _accountId;
        private Guid _ruleId;
        private Guid _dupAccountId;
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.  
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Obtain the organization service reference which you will need for  
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                try
                {
                CreateRequiredRecords();
                    // Create and account record with the named Proseware, Inc. and already existing Account Number.
                    Account account = new Account
                    {
                        Name = "Proseware, Inc.",
                        AccountNumber = "ACC005"
                    };

                    // Create operation by suppressing duplicate detection
                    CreateRequest reqCreate = new CreateRequest();
                    reqCreate.Target = account;
                    reqCreate.Parameters.Add("SuppressDuplicateDetection", true); // Change to false to activate the duplicate detection.
                    CreateResponse createResponse = (CreateResponse)service.Execute(reqCreate);
                    _dupAccountId = createResponse.id;

                    // Retrieve the account containing with its few attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "accountnumber" });

                    Account retrievedAccount = (Account)service.Retrieve("account", _dupAccountId, cols);

                    // Update the existing account with new account number.
                    retrievedAccount.AccountNumber = "ACC006";

                    // Update operation – update record, if a duplicate is not found.
                    UpdateRequest reqUpdate = new UpdateRequest();
                    reqUpdate.Target = retrievedAccount;
                    reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.

                    // Update the account record.
                    UpdateResponse updateResponse = (UpdateResponse)service.Execute(reqUpdate);

                    DeleteRequiredRecords();
                }

                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
                /// 
                /// Creates any entity records that this sample requires.
                void CreateRequiredRecords()
                {
                    // Create an account record named Fourth Coffee.
                    Account account = new Account
                    {
                        Name = "Fourth Coffee",
                        AccountNumber = "ACC005"
                    };
                    _accountId =service.Create(account);

                    // Create a duplicate detection rule
                    DuplicateRule accountDuplicateRule = new DuplicateRule
                    {
                        Name = "DuplicateRule: Accounts with the same Account Number",
                        BaseEntityName = "account",
                        MatchingEntityName = "account"
                    };
                    _ruleId =service.Create(accountDuplicateRule);

                    DuplicateRuleCondition accountDupCondition = new DuplicateRuleCondition
                    {
                        BaseAttributeName = "accountnumber",
                        MatchingAttributeName = "accountnumber",
                        OperatorCode = new OptionSetValue(0), // Exact Match.
                        RegardingObjectId = new EntityReference(DuplicateRule.EntityLogicalName, _ruleId)
                    };
                    Guid conditionId = service.Create(accountDupCondition);

                    // Execute the publish request.
                    PublishDuplicateRuleResponse response =
                        (PublishDuplicateRuleResponse)service.Execute(new PublishDuplicateRuleRequest() { DuplicateRuleId = _ruleId });

                    // When the publishDuplicateRule request returns, the state of the rule will still be "Publishing" (StatusCode = 1).
                    // we need to wait for the publishing operation to complete, so we keep polling the state of the
                    // rule until it becomes "Published" (StatusCode = 2).
                    int i = 0;
                    DuplicateRule retrievedRule =
                        (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, _ruleId, new ColumnSet(new String[] { "statuscode" }));
                    while (retrievedRule.StatusCode.Value == 1 && i < 20)
                    {
                        i  ;
                        System.Threading.Thread.Sleep(1000);
                        retrievedRule =
                            (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, _ruleId, new ColumnSet(new String[] { "statuscode" }));
                    }

                }
                /// 
                /// Deletes any entity records that were created for this sample.
                /// delete the records created in this sample.
                /// 
                void DeleteRequiredRecords()
                {
                        service.Delete(Account.EntityLogicalName, _accountId);
                        UnpublishDuplicateRuleRequest unpublishRequest = new UnpublishDuplicateRuleRequest
                        {
                            DuplicateRuleId = _ruleId
                        };
                        service.Execute(unpublishRequest);
                        service.Delete(DuplicateRule.EntityLogicalName, _ruleId);
                        service.Delete(Account.EntityLogicalName, _dupAccountId);
                }
            }
        }
    }
8080.11Capture.PNG

Error Details: at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)
at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)
at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)
at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)
at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()
at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult(ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)
at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult(ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)
at lambda_method(Closure , Object , Object[ )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[ methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
Activity Id: 9a742c58-544c-4c93-886e-b60f3ed9f51c

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: How to fix Error code: 0x80040265

    You might be getting the error because of an update, like the MS Visual C++ package which might not be installed properly or completely. What you can do then is to uninstall the current package and install a fresh copy.

    Uninstall the package by going to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package.

    Click Uninstall on top of the list, and when it is done, reboot your computer.

    Download the latest redistributable package from Microsoft then install it.

  • Verified answer
    LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: How to fix Error code: 0x80040265

    Hi Partner,

    I tried you code and I got the same issue, then I enable the Plug-in Trace in D365 and I got the deeper issue, there is an infinite loop in your  code.

    pastedimage1597117126199v1.png

    According this error message, I did a lot of test in this code and I finally found the reason.

    I think you registered your plug-in at account pre-create event right? And this is the reason, the code already has function to create new account, and this action will be triggered when you creating new account, Multiple simultaneous account creation operations caused a conflict which caused this issue.

    So you should change your trigger event like update account or create other entities and try again.

    BTW, this code is used to show how the duplicate detection used in plug-in, in fact, you don't need to create new account in plug-in, you just need to create the duplicate detection rule and condition for account and then publish as the code worked.

    Best Regards,

    Leo

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

New! Quick response templatesâš¡

Save time with the new custom templates!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,228 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,056 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans