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

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Debugging plugin with Plugin Registration Tool

(0) ShareShare
ReportReport
Posted on by 1,328

I need assistance with debugging this plugin. Basic plugin logic: If the order product's product has field "ktl_ConsolidateintoServices.Value" == true, combine these order products into one specific product called "Professional Services". Also create an order service for each of these order products that were combined. When debugging in Plugin Registration Tool, here is what I have.

Error Message - Detail from Plugin Registration Tool

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Sequence contains no elements
Detail: <OrganizationServiceFault xmlns="schemas.microsoft.com/.../Contracts" xmlns:i="www.w3.org/.../XMLSchema-instance">
  <ErrorCode>-2147220970</ErrorCode>
  <ErrorDetails xmlns:a="schemas.datacontract.org/.../System.Collections.Generic">
    <KeyValuePairOfstringanyType>
      <a:key>CallStack</a:key>
      <a:value i:type="b:string" xmlns:b="www.w3.org/.../XMLSchema">   at Microsoft.Xrm.Sdk.Linq.QueryProvider.ThrowException(Exception exception)
   at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups, String&amp; pagingCookie, Boolean&amp; moreRecords)
   at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups)
   at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
   at Microsoft.Xrm.Sdk.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate)
   at EPSalesOrderSetStatePlugin2.SalesOrderSetStatePlugin.Execute(IServiceProvider serviceProvider)
   at PluginProfiler.Library.PluginAppDomainProxy.ExecuteCore(Stopwatch watch, ProfilerExecutionReport report, Object instance, Object executionParameter)
   at PluginProfiler.Library.AppDomainProxy.Execute(ProfilerExecutionConfiguration configuration, ProfilerExecutionReport report)</a:value>
    </KeyValuePairOfstringanyType>
  </ErrorDetails>
  <Message>Sequence contains no elements</Message>
  <Timestamp>2018-03-20T16:49:18.8750277Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText i:nil="true" />
</OrganizationServiceFault>


Copy of Code

        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService val = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext val2 = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            this.ValidateContext(val2, val);
            EntityReference salesOrderReference = (EntityReference)val2.InputParameters["EntityMoniker"];
            if (((OptionSetValue)(val2.InputParameters["State"])).Value == 1)
            {
                CrmServiceContext crmService = new CrmServiceContext(((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(val2.UserId)));
                IQueryable<SalesOrderDetail> salesOrderDetailSet = crmService.SalesOrderDetailSet;
                IQueryable<Product> productSet = crmService.ProductSet;
                var list = (from x in crmService.SalesOrderDetailSet.Join(
                    crmService.ProductSet,
                    (SalesOrderDetail x) => x.ProductId.Id,
                    (Product x) => x.Id,
                    (SalesOrderDetail x, Product y) => new
                    {
                        x,
                        y
                    })
                            where x.x.SalesOrderId.Id == salesOrderReference.Id && x.y.ktl_ConsolidateintoServices.Value == true
                            select x).ToList();
                SalesOrder salesOrder = crmService.SalesOrderSet.First((SalesOrder x) => x.Id == salesOrderReference.Id);
                if (list.Any())
                {
                    decimal num = default(decimal);
                    foreach (var item in list)
                    {
                        num += item.x.BaseAmount.Value;
                        if (!crmService.IsAttached(item.x))
                        {
                            crmService.Attach(item.x);
                        }
                       // crmService.DeleteObject(item.x);
                        ktl_OrderService ktl_OrderService = new ktl_OrderService
                        {
                            ktl_ServiceProductNumber = item.y.ProductNumber,
                            ktl_ProductId = item.x.ProductId,
                            ktl_UoMId = item.x.UoMId,
                            ktl_PricePerUnit = item.x.PricePerUnit,
                            ktl_Quantity = item.x.Quantity,

                        };
                        crmService.AddObject(ktl_OrderService);
                    }
                   
        

                    Product product = crmService.ProductSet.First((Product x) => x.Id == this._serviceProductId);
                    SalesOrderDetail salesOrderDetail = new SalesOrderDetail
                    {
                        IsPriceOverridden = true,
                        ProductId = product.ToEntityReference(),
                        Quantity = 1,
                        PricePerUnit = new Money(num),
                        SalesOrderId = salesOrder.ToEntityReference(),
                        UoMId = product.DefaultUoMId
                    };
                    crmService.AddObject(salesOrderDetail);
                    try
                    {
                        crmService.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        val.Trace(ex.Source, new object[0]);
                        val.Trace(ex.ToString(), new object[0]);
                        throw new InvalidPluginExecutionException(ex.Message);
                    }
                }
            }
        }


*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Hi,

    Since you are running CRM on Premise (2015), you can install Visual Studio Remote Debugger on your CRM Server, and then from within Visual Studio attach you process to the w3wp service on the remote machine.

    This will allow you to debug in your own VS environment.

    See this link for further help:

    crmbusiness.wordpress.com/.../crm-2011-how-to-set-up-remote-debugging-for-plugins

    Hope this helps.

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello,

    You have two occurrences of the Linq extension 'First' - one of them is throwing the exception because it's not returning any records.

    The 'First' extension method demands that at least one record is returned by your query and throws this exception if nothing is returned. (unlike the 'FirstOrDefault' method, which quietly returns null instead)

      

    1.

    SalesOrder salesOrder = crmService.SalesOrderSet.First((SalesOrder x) => x.Id == salesOrderReference.Id);

    The first one is unlikely because you are retrieving the ID from an EntityReference earlier in the code.

    Unless you are running this code on a Create of the SalesOrder, in which case it could be that the SalesOrder hasn't been committed to the database yet.

      

    2.

    Product product = crmService.ProductSet.First((Product x) => x.Id == this._serviceProductId);

    For the second one, it's unclear to me where this._serviceProductId comes from. I worry that you are running into the issue of multiple concurrency, because I see a reference to 'this'. Can you verify that this ID is correct?

    If the same plug-in is called multiple times in quick succession, it's important to note that it doesn't create a specific instance of the class for every run, it reuses the same one multiple times and just calls 'Execute' on the same instance multiple times. It might be the case that you are getting a GUID from a different plug-in execution, which might reference a product that doesn't exist.

    It's a best practice to avoid scoping any fields or properties in your class and avoid calling 'this'. 

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

    Hi


    Replace the method First() with FirstOrDefault(). The method FirstOrDefault() returns a null value, if there are no records that matches to the filtering criteria.

    Product product = crmService.ProductSet.First((Product x) => x.Id == this._serviceProductId);
    
    SalesOrder salesOrder = crmService.SalesOrderSet.First((SalesOrder x) => x.Id == salesOrderReference.Id);

    Try with
    FirstOrDefault()

      Product product = crmService.ProductSet.Where(Product => (Product.Id == this._serviceProductId)).FirstOrDefault();
    
      SalesOrder salesOrder = crmService.SalesOrderSet.Where(SalesOrder => (Product.Id == salesOrderReference.Id)). FirstOrDefault();

    Hope this helps
  • epark06 Profile Picture
    1,328 on at

    Thank you, here is more information on the error message in VS.

    Object '/5bb71736_d413_4958_b4d3_539e1371ceb1/tbww9xkq5juambx9p4_kwzhi_15.rem' has been disconnected or does not exist at the server.

    4503.Capture4.PNG

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

    Hi,

    Seems you have missed my suggestion - Please use FirstOrDefault()

    Product product = crmService.ProductSet.Where(Product => (Product.Id == this._serviceProductId)).FirstOrDefault();

  • epark06 Profile Picture
    1,328 on at

    [quote user="Goutam Das"]

    Hi,

    Seems you have missed my suggestion - Please use FirstOrDefault()

    Product product = crmService.ProductSet.Where(Product => (x.Id == this._serviceProductId)).FirstOrDefault();

    [/quote]

    I tried that, and after Rebuild I get the following error: "The name 'x' does not exist in the current context."

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    It should be

    Product product = crmService.ProductSet.Where((Product x) => x.Id == this._serviceProductId).FirstOrDefault();

    It looks like the ID you are passing from 'this.__serviceProductId' refers to a record that doesn't exist.

    Please check that it's using the right ID.

    You still have to find out why this ID isn't returning any products, changing to FirstOrDefault will only fix the exception you have now but, if the product still can't be found you will get a NullReferenceException a few lines later!

     

    Also please take in mind my comment about the usage of 'this'. 

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

    It was typo, modified now . You just need to replace Product .

    Product product = crmService.ProductSet.Where(Product => (Product.Id == this._serviceProductId)).FirstOrDefault();

  • epark06 Profile Picture
    1,328 on at

    Thank you, this plugin was decompiled from an existing plugin whose source code I don't have. I am not sure how the ID now does not exist, but I do have the GUID of product: cc20175b-7369-e511-80ca-0050569110f8

    Can you please show me how to replace the product with this ID?

  • epark06 Profile Picture
    1,328 on at

    And just making sure I understand correctly, the ID that is not being found is the ID of the specific product "Professional Services" that the individual order products are being rolled into?

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

News and Announcements

Season of Giving Solutions is Here!

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 2

#1
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

#1
Shidin Haridas Profile Picture

Shidin Haridas 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans