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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Code to populate products

(0) ShareShare
ReportReport
Posted on by 10

Hi,

I am trying to copy products from opportunity products to quote quote products

I tried this code using plugin

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;


namespace Products
{
public class MyProducts : IPlugin
{

public void Execute(IServiceProvider serviceProvider)
{

// Obtain the organization service reference.

IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));

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


// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];

if (entity.LogicalName == "quote")
{
if (entity.Attributes.Contains("opportunityid"))
{

var optyRef = ((EntityReference)(entity.Attributes["opportunityid"]));
var fetchData = new
{
OPTYGUID = optyRef.Id.ToString()
};

var fetchXml = $@"

<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='product'>
<attribute name='name' />
<attribute name='productid' />
<attribute name='productnumber' />
<attribute name='description' />
<attribute name='statecode' />
<attribute name='productstructure' />
<attribute name='defaultuomid' alias='defaultUOMID' />
<attribute name='transactioncurrencyid' alias='defaultCurrency' />
<order attribute='productnumber' descending='false' />
<link-entity name='opportunityproduct' from='productid' to='productid' link-type='inner' alias='ai'>
<attribute name='priceperunit' />
<attribute name='quantity' />
<attribute name='extendedamount' />
<attribute name='opportunityproductid' />
<filter type='and'>
<condition attribute='opportunityid' operator='eq' value='{fetchData.OPTYGUID}' />
</filter>
</link-entity>
</entity>
</fetch>";

EntityCollection optyProdCollection = service.RetrieveMultiple(new FetchExpression(fetchXml.ToString()));
if (null == optyProdCollection || null == optyProdCollection.Entities || optyProdCollection.Entities.Count == 0)
{

return;
}
else
{
foreach (Entity optyProds in optyProdCollection.Entities)
{

Guid uomtoUse = ((EntityReference)optyProds.GetAttributeValue<AliasedValue>("defaultUOMID").Value).Id;
Entity quoteProdCreate = new Entity("quotedetail");
quoteProdCreate["quoteid"] = entity.Id;

//quoteProdCreate["quoteproductname"] = optyProds.GetAttributeValue<string>("name");
quoteProdCreate["productid"] = optyProds.GetAttributeValue<Guid>("productid");
quoteProdCreate["uomid"] = new EntityReference("uom", uomtoUse);
quoteProdCreate["quantity"] = optyProds.GetAttributeValue<double>("quantity");

quoteProdCreate["extendedamount"] = optyProds.GetAttributeValue<double>("extendedamount");
quoteProdCreate["ispriceoverridden"] = true;
service.Create(quoteProdCreate);
}
}
}



}
else
{
throw new InvalidPluginExecutionException("Exception occured");
}
}


}
}

But getting this error

{Exception details: ErrorCode: 0x80040216 Message: An unexpected error occurred. TimeStamp: 2021-01-03T12:32:35.4921720Z -- Exception details: ErrorCode: 0x80040216 Message: System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'Microsoft.Xrm.Sdk.EntityReference'. at Microsoft.Crm.ObjectModel.DefaultCurrency.TryGetCurrencyFromParent(EntityDataInformation entityDataInformation, EntityReference& transactionCurrencyEntityReference) +0x0 at Microsoft.Crm.ObjectModel.DefaultCurrency.SetDefaultCurrency(EntityDataInformation entityDataInformation) +0x14 at Microsoft.Crm.ObjectModel.DoubleAttributeValidator.GetRecordCurrency(MoneyAttributeMetadata moneyMetadata, Entity entity, ExecutionContext platformContext) +0x78 at Microsoft.Crm.ObjectModel.DoubleAttributeValidator.UpdatePrecision(Nullable`1 decimalValue, Nullable`1 floatValue, Money moneyValue, DoubleAttributeMetadata doubleMetadata, Entity entity, String propertyName, ExecutionContext platformContext) +0xd3 at Microsoft.Crm.ObjectModel.DoubleAttributeValidator.Validate(Entity entity, KeyValuePair`2 property, AttributeMetadata attributeMetadata, ExecutionContext platformContext) +0x13d at Microsoft.Crm.ObjectModel.AttributeValidationPlugin.PerformValidation(Entity entity, EntityMetadata entityMetadata, ExecutionContext platformContext, Entity parentEntity) +0x3d at Microsoft.Crm.ObjectModel.AttributeValidationPlugin.Execute(IServiceProvider serviceProvider) +0x68 at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context) +0x399 at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context) +0x7: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #46906C30 TimeStamp: 2021-01-03T12:32:35.4921720Z -- }

Can any one please help me regarding this

I have the same question (0)
  • Verified answer
    Community Member Profile Picture
    on at

    Without debugging it or having trace I think it could be in a few places.

    change the below (I dont think its this one, but it could be)

    Guid uomtoUse = ((EntityReference)optyProds.GetAttributeValue<AliasedValue>("defaultUOMID").Value).Id;

    EntityReference uOM optyProds.GetAttributeValue<EntityReference>("defaultUOMID");

    then change quoteProdCreate["uomid"] = new EntityReference("uom", uomtoUse); to

    quoteProdCreate["uomid"] = new EntityReference("uom", uOM ,Id);

    I think its one of these:

    quoteProdCreate["quoteid"] = entity.Id;

    quoteProdCreate["productid"] = optyProds.GetAttributeValue<Guid>("productid");

    I believe they are both lookups on your entity, but you are setting them with Guids.

    new EntityReference("uom", uOM ,Id);

    quoteProdCreate["quoteid"] = new EntityReference("quote", enitity,Id);

    quoteProdCreate["productid"] = new EntityReference("product", optyProds.GetAttributeValue<Guid>("productid")); optyProds.GetAttributeValue<Guid>("productid")

  • Ashok__ Profile Picture
    10 on at

    Thanks a lot, that helped me.

    I have made all the changes.

    But still I'm getting this error when I debug. I have configured step on Create of quote and on post operation, synchronous. This is triggered onclick of save on quote form .

    The quoteid is a required field and guid id for quote gets created only after saving that form. But I am getting error as soon as I click on save and form is not saving. Please help me if you have any idea in resolving this issue.

    + Detail {Exception details:

    ErrorCode: 0x80040217

    Message: quote With Id = 24815c77-c74d-eb11-a812-000d3aca0dfa Does Not Exist

    TimeStamp: 2021-01-03T13:29:16.0616942Z

    --

    Exception details:

    ErrorCode: 0x80040217

    Message: quote With Id = 24815c77-c74d-eb11-a812-000d3aca0dfa Does Not Exist

    TimeStamp: 2021-01-03T13:29:16.0616942Z

    --

    } Microsoft.Xrm.Sdk.OrganizationServiceFault

  • Suggested answer
    Community Member Profile Picture
    on at

    Try adding something like this in, the target variable should have the guid (I tend to use CWAs and not workflows)

    Entity target = null;        

    if (context.InputParameters.Contains("Target"))

    {

       if (context.InputParameters["Target"] is Entity)

       {

           target = (Entity)context.InputParameters["Target"];

       }

    }

  • Ashok__ Profile Picture
    10 on at

    Thank you.

    Tried but getting the same error.

    Can you please tell me if you have an idea of when to trigger the plugin(step registration).

  • Verified answer
    Community Member Profile Picture
    on at

    You could add a post image, then include the Quote primary key - if you keep it a plugin.

    I like custom workflow activities, if you decided to turn it into one of those you could control the trigger (and filters) from a workflow, that way you can pass the guid in dynamically as an entity reference.

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…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 74 Super User 2025 Season 2

#2
Daniyal Khaleel Profile Picture

Daniyal Khaleel 32 Most Valuable Professional

#3
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 31 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans