web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Cannot insert duplicate key while cloning Product programmatically using custom Action

(0) ShareShare
ReportReport
Posted on by 59

I have a custom action which clones the product entity using the code snippet below

List<string> ignoreAttributes = new List<string>() { "productid", "productnumber", "statecode"};
Entity clonedProduct = Clone(sourceProduct, new Entity("product"), ignoreAttributes);

        private Entity Clone(Entity source, Entity cloned, List<string> ignoreAttributes)
        {
            foreach (var attribute in source.Attributes)
            {
                string attributeName = attribute.Key;
                object attributeValue = attribute.Value;

                if (ignoreAttributes.Contains(attributeName)) continue;
                cloned[attributeName] = attributeValue;

            }

            return cloned;
        }


Now this code works fine for almost every product except few in the production. I have tried to log the key attributes being cloned but there is not any. Can someone please help me in identifying what is this key which is throwing this error for some particular products only? Any idea how I can check what is this key name which is causing issues?
Below is the exception being logged

Unhandled exception: 
Exception type: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]
Message: Cannot insert duplicate key.Detail: 
<OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
<ActivityId>e111d6d8-d8b3-4db6-87e0-df7d1c1eddba</ActivityId>
<ErrorCode>-2147220891</ErrorCode>
<ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>OperationStatus</d2p1:key>
<d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema" i:type="d4p1:int">0</d2p1:value>
</KeyValuePairOfstringanyType>
<KeyValuePairOfstringanyType>
<d2p1:key>SubErrorCode</d2p1:key>
<d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema" i:type="d4p1:int">-2146233088</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>Cannot insert duplicate key.</Message>
<Timestamp>2019-01-04T06:50:54.3872309Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource>PluginExecution</ExceptionSource>
<InnerFault i:nil="true" />
<OriginalException>Microsoft.Xrm.Sdk.InvalidPluginExecutionException
at System.Activities.WorkflowApplication.Invoke(Activity activity, IDictionary`2 inputs, WorkflowInstanceExtensionManager extensions, TimeSpan timeout)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow, IDictionary`2 inputs, TimeSpan timeout, WorkflowInstanceExtensionManager extensions)
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, String customActivityTypeName, IExecutionContext requestContext, Dictionary`2 sandboxServices, Boolean useDrawbridgeEnabled, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, String customActivityTypeName, IExecutionContext requestContext, Dictionary`2 sandboxServices, Boolean useDrawbridgeEnabled, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxWorker.ExecuteCustomWorkflowActivity(SandboxCallInfo callInfo, SandboxCustomActivityExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, SandboxRequestCounter&amp; workerCounter, Boolean returnTraceInfo)</OriginalException>


 

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Pawar Pravin  Profile Picture
    5,237 on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    Hey,

    As I believe you are creating clone record using custom action.

    While creating record make sure that you have removed GUID parameter as shown below:

    switch (attributeName.ToLower())

                       {

                           case "contactid":

                               break;

                           case "lastname":

                               Clone_Contact[attributeName] = attributeValue + " - Cloned";

                               break;

                           default:

                               Clone_Contact[attributeName] = attributeValue;

                               break;

                       }

  • Suggested answer
    Community Member Profile Picture
    on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    This is assuming that you are creating a custom CodeActivity?

    If so, to narrow down the attribute causing the error without attaching the debugger, you can leverage the Plugin Trace Log and the Tracing Service.  The Plugin Trace Log allows viewing your trace messages in addition to the exception stack trace.

    If so, you can grab a reference to the Tracing Service like this: 

    protected override void Execute(CodeActivityContext executionContext)
    
    ITracingService tracer = executionContext.GetExtension<ITracingService>();
    

    Once you have the tracer object, you write the to the trace log using 

    tracer.trace("message");

    In your loop, write out the attributes and values... Last one would likely be the one with the issue.

    To enable the plugin tracing, go to Settings -> System -> Administration -> System Settings, and open the Customizations Tab and enable tracing: 

    1817.Untitled.png

    Run the workflow on the records that cause the exception.. then under settings, go to Plugin Trace log and you should see some new records with the exceptions.  You may need to refresh the grid a few times until the log populates. 

    Another trace viewer option is a Tool in the XrmToolBox called Plugin Trace Viewer by Jonas Rapp.  This will allow to you to view the trace logs outside of CRM with additional filtering and sorting, including an automatic refresh.

  • RaviKashyap Profile Picture
    55,410 Moderator on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    never mind, ignore that. I just tried to see if the product returns any attribute of type entity collection but it didn't. I would suggest to try the same code in console app and debug to find the issue.

    Your modified code for console app-

    =====================

    public void GetProducts()

           {

               using (service = new OrganizationServiceProxy(new Uri(_organizationURI), null, _credential, null))

               {

                   string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >

                                          <entity name = 'product' >

                                              <all-attributes/>

                                          </entity>

                                      </fetch>";

                   var allProducts = service.RetrieveMultiple(new FetchExpression(fetchXml));

                   foreach (var prod in allProducts.Entities)

                   {

                       List<string> ignoreAttributes = new List<string>() { "productid", "productnumber", "statecode", "statuscode" };

                       Entity clonedProduct = Clone(prod, new Entity("product"), ignoreAttributes);

                       service.Create(clonedProduct);

                   }

               }

           }

           private Entity Clone(Entity source, Entity cloned, List<string> ignoreAttributes)

           {

               foreach (var attribute in source.Attributes)

               {

                   string attributeName = attribute.Key;

                   object attributeValue = attribute.Value;

                   if (ignoreAttributes.Contains(attributeName)) continue;

                   cloned[attributeName] = attributeValue;

               }

               return cloned;

           }

    ==============

  • Bilal Hussain Profile Picture
    59 on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    @Ravi how can I check the type of attributes? I am using a custom action so unable to debug it using plugin profiler.

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    Hi Bilal,

    Did you identify the product which causes the problem ? You can do some manual check using advanced find and compare the attributes value.

  • Bilal Hussain Profile Picture
    59 on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    Yes but they are already in the ignored list , so they are not being copied. Also this works for most of the products except few ones and I am not able to find which other attribute is causing the issues there.

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    Hi,

    Recently encountered the similar error when I was cloing the activity. In my case, it turned out that one of the attribute type was entity collection i.e. it was returning the entity records (activity party) so when you set that attribute to your cloned instance, it tries to create the same entity record with the same Guid and failed.

    You need to check if in your collection, you have any attribute of entity collection type. If yes then you need to handle it in a different way.

    Hope this helps.

  • Suggested answer
    Alex Fun Wei Jie Profile Picture
    33,626 on at
    RE: Cannot insert duplicate key while cloning Product programmatically using custom Action

    Hi,

    from what i know, productnumber and productid  will throw error, if it has duplicate value.

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
HR-09070029-0 Profile Picture

HR-09070029-0 2

#2
ED-30091530-0 Profile Picture

ED-30091530-0 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans