删除不触发Dynamics CRM的消息插件

时间:2017-10-30 13:50:51

标签: c# plugins dynamics-crm

我有一个父实体和子实体。我正在创建一个插件来计算每个父实体的子实体数,并在父实体的noOfProduct字段中显示该数字。所以每当我创建一个新的子实体时,noOfProduct中的数字值将增加到1.但是当我删除子实体时,我的插件没有触发,因此值保持不变。

我注册了我的插件

step: create
primary entity: child_entity
event_pipeline: post-operation
synchronous 
Plugin Images: post-image

这是我的完整代码。

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.Web.Services;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NoOfProductsPlugin
{
  public class NoOfProducts : IPlugin
  {
    public void Execute(IServiceProvider serviceProvider)
    {
        ITracingService tracingService = 

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

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

        //for create and update event
        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            // Obtain the target entity from the input parmameters.
            Entity targetEntity = (Entity)context.InputParameters["Target"];

            // Verify that the entity represents a connection.
            if (targetEntity.LogicalName != "child_entity")
            {
                return;
            }
            else
            {
                try
                {
                    //triggered upon create or update message
                    if (context.MessageName == "Create" || context.MessageName == "Update")
                    {
                        Entity postMessageImage;
                        Guid oppId = new Guid();

                        if (context.PostEntityImages.Contains("postMessageImage") && context.PostEntityImages["postMessageImage"] is Entity)
                        {
                            postMessageImage = (Entity)context.PostEntityImages["postMessageImage"];
                            oppId = ((EntityReference)postMessageImage.Attributes["lookup_fieldtoParent"]).Id;
                        }

                        //throw new InvalidPluginExecutionException

                        queryOppProd(service, oppId);
                    }

                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred :-" + ex.Message, ex);
                }
                //</snippetFollowupPlugin3>

                catch (Exception ex)
                {
                    tracingService.Trace("An error occurred  : {0}" + ex.Message, ex.ToString());
                    throw;
                }
            }
        }
        //for delete event use entityreference
        else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
        {
            // Obtain the target entity from the input parmameters.
            EntityReference targetEntity = (EntityReference)context.InputParameters["Target"];

            // Verify that the entity represents a connection.
            if (targetEntity.LogicalName != "child_entity")
            {
                return;
            }
            else
            {

                try
                {
                    //triggered upon delete message
                    if (context.MessageName == "Delete")
                    {
                        Guid oppProdId = targetEntity.Id;

                        // retrieve oppid guid
                        Entity oppProd = new Entity("child_entity");
                        ColumnSet columns_ = new ColumnSet(new string[] { "lookup_fieldtoParent" });
                         oppProd = service.Retrieve(oppProd.LogicalName, oppProdId, columns_);

                        Guid oppId = new Guid();
                        oppId = ((EntityReference)oppProd["lookup_fieldtoParent"]).Id;

                        //throw new InvalidPluginExecutionException(
                    }

                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred :-" + ex.Message, ex);
                }
                //</snippetFollowupPlugin3>

                catch (Exception ex)
                {
                    tracingService.Trace("An error occurred: {0}" + ex.Message, ex.ToString());
                    throw;
                }
            }
        }
    }
    public void queryOppProd(IOrganizationService service, Guid oppId)
    {
        int noOfProduct = 0;

        QueryExpression oppProdQuery = new QueryExpression { EntityName = "child_entity", ColumnSet = new ColumnSet("child_entityid", "lookup_fieldtoParent") };
        oppProdQuery.Criteria.AddCondition("lookup_fieldtoParent", ConditionOperator.Equal, oppId); // to search for child_entity that linked to the selected parent_entity
        EntityCollection oppProdQueryRetrieve = service.RetrieveMultiple(oppProdQuery);

        if (oppProdQueryRetrieve != null && oppProdQueryRetrieve.Entities.Count > 0)
        {
            for (var i = 0; i < oppProdQueryRetrieve.Entities.Count; i++)
            {

                noOfProduct++;
            }
        }

        //declare table used to retrieve the field and update
        Entity opportunity = new Entity("parent_entity");
        ColumnSet columns = new ColumnSet(new string[] { "new_noofproducts" });
        opportunity = service.Retrieve(opportunity.LogicalName, oppId, columns);

        opportunity["new_noofproducts"] = noOfProduct;
        service.Update(opportunity);
    }

    public void queryOppProdOnDel(IOrganizationService service, Guid oppId, Guid oppProdId)
    {
        int noOfProduct = 0;


        //query opportunityProduct by using opportunity guid
        QueryExpression oppProdQuery = new QueryExpression { EntityName = "child_entity", ColumnSet = new ColumnSet("child_entityid", "lookup_fieldtoParent") };

        FilterExpression oppProdQueryFilter = oppProdQuery.Criteria.AddFilter(LogicalOperator.And);
        oppProdQueryFilter.AddCondition("child_entityid", ConditionOperator.NotEqual, oppProdId);
        oppProdQueryFilter.AddCondition("lookup_fieldtoParent", ConditionOperator.Equal, oppId); // to search for child_entity that linked to the selected parent_entity
        EntityCollection oppProdQueryRetrieve = service.RetrieveMultiple(oppProdQuery);

        if (oppProdQueryRetrieve != null && oppProdQueryRetrieve.Entities.Count > 0)
        {
            for (var i = 0; i < oppProdQueryRetrieve.Entities.Count; i++)
            {

                noOfProduct++;
            }
        }
        //throw new InvalidPluginExecutionException

        //declare table used to retrieve the field and update
        Entity opportunity = new Entity("parent_entity");
        ColumnSet columns = new ColumnSet(new string[] { "new_noofproducts" });

        opportunity = service.Retrieve(opportunity.LogicalName, oppId, columns);
        service.Update(opportunity);
    }
}
}

2 个答案:

答案 0 :(得分:0)

几点:

  1. step: create您应该在delete上注册。
  2. 非常确定删除后的图片is not supported。你需要使用pre's。 &#34;创建操作不支持前映像,删除操作不支持后映像。&#34;

  3. 您的基本设计存在缺陷。如果同时发生大量更改,它们都可以在单独的线程上同时执行,这意味着在某些情况下计数可能不正确。

答案 1 :(得分:0)

您忘记调用方法queryOppProdOnDel

当您注册插件程序集&amp;单击“删除邮件”,替换代码中的以下代码段。

                   //triggered upon delete message
                    if (context.MessageName == "Delete")
                    {
                        Guid oppProdId = targetEntity.Id;

                        // retrieve oppid guid
                        Entity oppProd = new Entity("child_entity");
                        ColumnSet columns_ = new ColumnSet(new string[] { "lookup_fieldtoParent" });
                         oppProd = service.Retrieve(oppProd.LogicalName, oppProdId, columns_);

                        Guid oppId = new Guid();
                        oppId = ((EntityReference)oppProd["lookup_fieldtoParent"]).Id;

                        //throw new InvalidPluginExecutionException(

                        queryOppProdOnDel(service, oppId, oppProdId);
                    }

<强>更新

queryOppProdOnDel中缺少此行:

opportunity["new_noofproducts"] = noOfProduct;