简体   繁体   中英

The given key was not present in the dictionary Microsoft CRM Plugin

Another Microsoft CRM plugin related question. My plugin is firing when an invoice record is updated. I want to copy the contents of some of the invoice fields to the corresponding fields on the commission record. The if which contains the due date seems to work ok but the if containing the invoiceamount gives a key not present error. I have checked that all the field names are correct and exist in the correct entities.

Any ideas what's happening? Do I need to use images and if so, could somebody help me with some code, please?

Thanks

// <copyright file="PreInvoiceUpdate.cs" company="">
// Copyright (c) 2013 All Rights Reserved
// </copyright>
// <author></author>
// <date>8/8/2013 10:40:22 AM</date>
// <summary>Implements the PreInvoiceUpdate Plugin.</summary>
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
// </auto-generated>
namespace UpdateCommission
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;


    /// <summary>
    /// PreInvoiceUpdate Plugin.
    /// Fires when the following attributes are updated:
    /// All Attributes
    /// </summary>    
    public class PreInvoiceUpdate : Plugin
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PreInvoiceUpdate"/> class.
        /// </summary>
        public PreInvoiceUpdate()
            : base(typeof(PreInvoiceUpdate))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "invoice", new Action<LocalPluginContext>(ExecutePreInvoiceUpdate)));

            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }

        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePreInvoiceUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            IServiceProvider serviceProvider = localContext.ServiceProvider;
            ITracingService tracingService = localContext.TracingService;


            // Obtain the target entity from the input parmameters.
            //Entity contextEntity = (Entity)context.InputParameters["Target"];

            if (context.Depth == 1)
            {

                #region Set up variables

                Entity targetInvoice = null;
                targetInvoice = (Entity)context.InputParameters["Target"];
                Guid invoiceID = targetInvoice.Id;


                ColumnSet invoiceCols = new ColumnSet("new_totalcomm", "new_grossprofit", "new_invoiceamount", "duedate");


                //Entity contact = service.Retrieve("contact", cid, cols);
                //contact.Attributes["jobtitle"] = "Sometitle";
                // contact.Attributes["address1_line1"] = "Some address";
                //service.Update(contact);


                string fetchCommissionQuery = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='tbw_commission'>
    <attribute name='tbw_commissionid' />
    <attribute name='tbw_name' />
    <attribute name='createdon' />
    <order attribute='tbw_name' descending='false' />
    <filter type='and'>
      <condition attribute='new_relatedinvoice' operator='eq' uitype='invoice' value='";

                fetchCommissionQuery += invoiceID;
                fetchCommissionQuery += @"' />
    </filter>
  </entity>
</fetch> ";


                EntityCollection commissionCollection = service.RetrieveMultiple(new FetchExpression(fetchCommissionQuery));

                //targetInvoice = service.Retrieve("invoice", invoiceID, invoiceCols);

                #endregion

                foreach (var commission in commissionCollection.Entities)
                {
                    if (targetInvoice.Attributes["duedate"] != null)
                    {

                        commission.Attributes["tbw_duedate"] = targetInvoice.Attributes["duedate"];
                    }

                    if (targetInvoice.Attributes["new_invoiceamount"] != null)// && commission.Attributes["tbw_paymentrate"] != null)
                    {
                        //dynamic commRate = commission.Attributes["tbw_paymentrate"];

                        //dynamic invoiceTotal = ((Money)targetInvoice.Attributes["new_invoiceamount"]).Value;

                        //dynamic commTotal = commRate * invoiceTotal;

                        //commission.Attributes["tbw_total"] = new Money(commTotal);
                        //commission.Attributes["tbw_total"] = 1.02;
                    }

                    //commission.Attributes["tbw_name"] = "TestCommName";
                    service.Update(commission);

                }


                // dynamic currentInvoiceTotal = ((Money)targetInvoice.Attributes["new_invoiceamount"]).Value;

                // currentInvoiceTotal = currentInvoiceTotal - 10;

                // Entity invoice = service.Retrieve("invoice", invoiceID, invoiceCols);
                // invoice.Attributes["new_grossprofit"] = new Money(currentInvoiceTotal);
                //service.Update(invoice);

                //}

            }
        }
    }
}

In Update, you will only have the value of fields those are updated. Other fields won't be there in Target Entity. You need to register plugin with PreImage. Add the fields to PreImage you want to access in plugin.

preImage = (Entity)context.PreEntityImages["PreImage"];

How to Register Plugin with Image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM