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 :
Microsoft Dynamics CRM (Archived)

Adding products to quote with a plugin.

(0) ShareShare
ReportReport
Posted on by

I'm having trouble adding products to a quote programmatically   i read all the documentation and all the similar threads,  but after hundreds of tries, i continue not finding the right way to accomplish my purpose. This is my code:

using System;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace ultima
{
public class InsertProdPlugin : IPlugin
{

private ITracingService _tracingService;
public void Execute(IServiceProvider serviceProvider)
{
_tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

_tracingService.Trace("Tracing: EXECUTE");

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

 
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = factory.CreateOrganizationService(context.UserId);

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

{

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

try
{
if (entity.LogicalName == "quote" && service != null)
{

ColumnSet attributes = new ColumnSet(true);
_tracingService.Trace("Error1");
Entity CurrentQuoteEntity;
_tracingService.Trace("Error2");
var id = context.PrimaryEntityId;
_tracingService.Trace("Error3:" + context.PrimaryEntityId);
CurrentQuoteEntity = service.Retrieve("quote", id, new ColumnSet("quoteid"));
_tracingService.Trace("Error4");
Guid quoteid = CurrentQuoteEntity.Id;
_tracingService.Trace("Error5:" + CurrentQuoteEntity.Id);

Entity newQuoteproductsEntity = new Entity("quotedetail");
_tracingService.Trace("Error6" + newQuoteproductsEntity);
QueryByAttribute query = new QueryByAttribute("product");

query.AddAttributeValue("productid", "019f6101-8e02-e811-a2c1-cba121a17201");

var product = service.RetrieveMultiple(query).Entities.FirstOrDefault();
if (product != null)
{
_tracingService.Trace("Error7:" + product.Id);
newQuoteproductsEntity["productid"] = product.Id;
newQuoteproductsEntity["uomid"] = "Primary Unit";
_tracingService.Trace("Error10" + newQuoteproductsEntity["uomid"]);
newQuoteproductsEntity["quoteid"] = CurrentQuoteEntity.Id;
_tracingService.Trace("Error11:" + CurrentQuoteEntity.Id + "\n Error12:" + newQuoteproductsEntity.Id);
service.Create(newQuoteproductsEntity);
_tracingService.Trace("Error13");

}
else
{
_tracingService.Trace("Product is empty!");
}


}
else
{
_tracingService.Trace("Not working at all!");
}


}
catch (Exception ex)
{
_tracingService.Trace(ex.InnerException.ToString());
throw;
}

}

}

}
}

I registered the plugin Post-operation (i also tried pre-operation and pre-validation) Asynchronous (also tried Synchronous) The Message is Update with primary entity quote, Secondary entity none and filtering attributes effectivefrom (when i update the effectivefrom date, the plugin fires).

I receive a business Process Error and this is the log:

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected exception from plug-in (Execute): ultima.InsertProdPlugin: System.NullReferenceException: Object reference not set to an instance of an object.Detail:
<OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
<ActivityId>bd994089-8947-44bb-9990-b1cf5d53a8b3</ActivityId>
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): ultima.InsertProdPlugin: System.NullReferenceException: Object reference not set to an instance of an object.</Message>
<Timestamp>2018-02-12T11:02:52.2009169Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText>

[Ultima4: ultima.InsertProdPlugin]
[f8059231-e40f-e811-a2c2-e45f139a85c9: ultima.InsertProdPlugin: Update of quote]

Tracing: EXECUTE
Error1
Error2
Error3:13733bc2-d90f-e811-a2c2-e45f139a85c9
Error4
Error5:13733bc2-d90f-e811-a2c2-e45f139a85c9
Error6Microsoft.Xrm.Sdk.Entity
Error7:019f6101-8e02-e811-a2c1-cba121a17201
Error10Primary Unit
Error11:13733bc2-d90f-e811-a2c2-e45f139a85c9
Error12:00000000-0000-0000-0000-000000000000


</TraceText>
</OrganizationServiceFault>

Thanks in advance.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Radu Chiribelea Profile Picture
    6,667 on at

    Hi Girao,

    You can use the plug-in profiler & plug-in registration tool to debug the plug-in execution.

    Please see following articles for guidance:

    msdn.microsoft.com/.../hh372952.aspx

    community.dynamics.com/.../how-to-debug-plugins-using-profiler

    In the debugger in Visual Studio you should be able to see what is causing the exception.

    Hope this helps

    Radu

  • Community Member Profile Picture
    on at

    Hi Radu,

    I already tried to install the Profiler in the plugin registration tool  but i always receive the following error:

    Unhandled Exception: System.Exception: Solution Import Failed: 31 Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Access is denied.Detail:
    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
    <ActivityId>b4dad6f2-ec06-4935-ad72-58336be2a89c</ActivityId>
    <ErrorCode>-2147187707</ErrorCode>
    <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
    <Message>Access is denied.</Message>
    <Timestamp>2018-02-12T11:57:48.3464531Z</Timestamp>
    <ExceptionRetriable>false</ExceptionRetriable>
    <ExceptionSource i:nil="true" />
    <InnerFault>
    <ActivityId>b4dad6f2-ec06-4935-ad72-58336be2a89c</ActivityId>
    <ErrorCode>-2147187707</ErrorCode>
    <ErrorDetails xmlns:d3p1="schemas.datacontract.org/.../System.Collections.Generic" />
    <Message>Access is denied.</Message>
    <Timestamp>2018-02-12T11:57:48.3464531Z</Timestamp>
    <ExceptionRetriable>false</ExceptionRetriable>
    <ExceptionSource i:nil="true" />
    <InnerFault>
    <ActivityId>b4dad6f2-ec06-4935-ad72-58336be2a89c</ActivityId>
    <ErrorCode>-2147220970</ErrorCode>
    <ErrorDetails xmlns:d4p1="schemas.datacontract.org/.../System.Collections.Generic" />
    <Message>System.UnauthorizedAccessException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #0BF8781D</Message>
    <Timestamp>2018-02-12T11:57:48.3464531Z</Timestamp>
    <ExceptionRetriable>false</ExceptionRetriable>
    <ExceptionSource i:nil="true" />
    <InnerFault i:nil="true" />
    <OriginalException i:nil="true" />
    <TraceText i:nil="true" />
    </InnerFault>
    <OriginalException i:nil="true" />
    <TraceText i:nil="true" />
    </InnerFault>
    <OriginalException i:nil="true" />
    <TraceText i:nil="true" />
    </OrganizationServiceFault>
    at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext)
    at Microsoft.Crm.Extensibility.InprocessServiceProxy.ExecuteCore(OrganizationRequest request)
    at Microsoft.Crm.Asynchronous.ExecuteSdkMessageOperation.InternalExecute(AsyncEvent asyncEvent)

    at PluginProfiler.Library.ProfilerManagementUtility.ImportSolutionAsyncAndWait(CrmServiceClient service, String prtpath, Boolean publishWorkflows, Boolean overwriteUnmanagedCustomizations, Int32 sleepInterval, Int32 asyncWaitTimeout)
    at PluginProfiler.Library.ProfilerManagementUtility.RetrieveOrCreateProfilerPluginType(CrmServiceClient service, String prtpath)
    at Microsoft.Crm.Tools.Libraries.OrganizationHelper.InstallProfiler(CrmOrganization org, String prtPath)
    at Microsoft.Crm.Tools.PluginRegistration.OrganizationControlViewModel.<>c__DisplayClass27.<InstallProfiler_Clicked>b__1f(Object o, DoWorkEventArgs e)

    So i'm working with the trace service and the Plugin Trace Log.

    Thanks

  • Suggested answer
    Radu Chiribelea Profile Picture
    6,667 on at

    Hi Girao,

    Is this CRM Online or OnPrem ?

    When do you get the Access Denied error? What operation are you trying to perform? Is it with you enable the profiling?

    If this is CRM OnPrem, are you trying to perform this operation with a Deployment Admin?

    For CRM Online can you try using a Global Admin / D365 Service Admin?

    Regards,

    Radu

  • Community Member Profile Picture
    on at

    Thanks for your answer.

    It is an Onpremisses.

    I receive the error just trying to install the profiler i just click the "Install Profiler" and a few moments latter i receive the error.

    I already checked and i'm a deployment admin at the Deployment manager, i also have the role of administrator and customizer at the user roles.

  • Suggested answer
    Radu Chiribelea Profile Picture
    6,667 on at

    If it is CRM OnPremise you can also attach Visual Studio directly to the process (Sandbox is plug-in is in Isolation mode or W3WP.exe if there is no isolation on your plugin - given that the plug-in is running synchronous)

    Also, you need to specify the path of the Symbols of your Plug-in in Visual Studio - (Debug - Options- Debugging - Symbols).

    Once the symbol path is specified you can attach VS to the process and add a breakpoint to your code. Trigger the plug-in and debug it.  

  • Suggested answer
    Guido Preite Profile Picture
    54,086 Moderator on at

    productid, quoteid and uomid are EntityReference

    so for productid you need to do

    newQuoteproductsEntity["productid"] = new EntityReference(“product”,product.Id);

    and for uomid you need to have the id of the unit, not the name

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Seems you are facing multiple issue while debugging plugin. Could you please tell us

    Which version of CRM are you using?

    Which version of SDK you have downloaded?

    Seems you have some version mismatch of the sdk.

    Can you please verify?

    Secondly you can debug your piece of code in console app as well.

    If it's difficult then you can enable CRM diagnostic tool by which you can get the trace log.

    Hope this will help.

    Thanks

    Goutam

  • Suggested answer
    Michel Gueli Profile Picture
    982 on at

    Here a rewrite of your code. Hope it helps:

    using System;

    using System.Linq;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    namespace ultima

    {

    public class InsertProdPlugin : IPlugin

    {

    private ITracingService _tracingService;

    public void Execute(IServiceProvider serviceProvider)

    {

    _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    _tracingService.Trace("Tracing: EXECUTE");

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

    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    IOrganizationService service = factory.CreateOrganizationService(context.UserId);

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

    {

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

    try

    {

    if (entity.LogicalName == "quote")

    {

    var quoteId = entity.Id;

    var product = RetrieveProduct(service, new Guid("019f6101-8e02-e811-a2c1-cba121a17201");

    if (product != null)

    {

    var newQuoteproductsEntity = new Entity("quotedetail");

    newQuoteproductsEntity.Attributes.Add("quoteid", new EntityReference("quote", quoteId));

    newQuoteproductsEntity.Attributes.Add("productid", new EntityReference("product", product.Id));

    //You need to have the guid of the Primary Unit.

    //newQuoteproductsEntity["uomid"] = "Primary Unit";

    service.Create(newQuoteproductsEntity);

    }

    else

    {

    _tracingService.Trace("Product is empty!");

    }

    }

    else

    {

    _tracingService.Trace("Not working at all!");

    }

    }

    catch (Exception ex)

    {

    _tracingService.Trace(ex.InnerException.ToString());

    throw;

    }

    }

    }

    private Entity RetrieveProduct(IOrganizationService service, Guid productId)

    {

    var query = new QueryExpression("product");

    query.Criteria.AddCondition("productid", ConditionOperator.Equal, productId);

    var result = service.RetrieveMultiple(query);

    if (result != null && result.Entities.Any())

    return result.Entities.First();

    return null;

    }

    }

    }

  • Suggested answer
    Emre GULCAN Profile Picture
    2,379 on at

    Hi

    You can add products just 2 simple lines with using XrmLibrary helpers.

    QuoteProductHelper quoteProductHelper = new QuoteProductHelper(_organizationService);
    quoteProductHelper.Add(Guid.Parse("YOUR_QUOTE_ID"), Guid.Parse("YOUR_PRODUCT_ID"), Guid.Parse("YOUR_UOM_ID"), 1); 

    also you can use "quoteProductHelper.Add" override alternatives that matched your requirement.

  • Community Member Profile Picture
    on at

    Hi Guido.

    I updated the code based on your advice but i still get a business error, "Object reference not set to an instance of an object." Just before the service.Create the newQuoteproductsEntity.Id haves a value of 00000000-0000-0000-0000-000000000000 is it supposed to be like that, since the quotedetail is not yet created?  I pasted the new updated code bellow:

    using System;

    using System.Linq;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    namespace ultima

    {

       public class InsertProdPlugin : IPlugin

       {

           private ITracingService _tracingService;

           public void Execute(IServiceProvider serviceProvider)

           {

               _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

               _tracingService.Trace("Tracing: EXECUTE");

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

               IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

               IOrganizationService service = factory.CreateOrganizationService(context.UserId);

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

               {

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

                   try

                   {

                       if (entity.LogicalName == "quote" && service != null)

                       {

                           ColumnSet attributes = new ColumnSet(true);

                           _tracingService.Trace("Error1");

                           Entity CurrentQuoteEntity;

                           _tracingService.Trace("Error2");

                           var id = context.PrimaryEntityId;

                           _tracingService.Trace("Error3:" + context.PrimaryEntityId);

                           CurrentQuoteEntity = service.Retrieve("quote", id, new ColumnSet("quoteid"));

                           _tracingService.Trace("Error4");

                           Guid quoteid = CurrentQuoteEntity.Id;

                           _tracingService.Trace("Error5:" + CurrentQuoteEntity.Id);

                           Entity newQuoteproductsEntity = new Entity("quotedetail");

                           _tracingService.Trace("Error6" + newQuoteproductsEntity);

                           QueryByAttribute query = new QueryByAttribute("product");

                           query.AddAttributeValue("productid", "019f6101-8e02-e811-a2c1-cba121a17201");

                           var product = service.RetrieveMultiple(query).Entities.FirstOrDefault();

                           if (product != null)

                           {

                               _tracingService.Trace("Error7:" + product.Id);

                               newQuoteproductsEntity["productid"] = new EntityReference("product", product.Id);

                               newQuoteproductsEntity["uomid"] = "2a18388e-a026-49c5-8a12-25b8c13acab9";

                               _tracingService.Trace("Error10" + newQuoteproductsEntity["uomid"]);                

                               newQuoteproductsEntity["quoteid"] = CurrentQuoteEntity.Id;

                               _tracingService.Trace("Error11:" + CurrentQuoteEntity.Id + "\n Error12:" + newQuoteproductsEntity.Id);

                               service.Create(newQuoteproductsEntity);

                               _tracingService.Trace("Error13");

                           }

                           else

                           {

                               _tracingService.Trace("Product is empty!");

                           }

                       }

                       else

                       {

                           _tracingService.Trace("Not working at all!");

                       }

                   }

                   catch (Exception ex)

                   {

                       _tracingService.Trace(ex.InnerException.ToString());

                       throw;

                   }

               }

           }

       }

    }

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 > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans