奇怪的行为CRM 2011插件

时间:2013-03-11 15:17:41

标签: c# plugins dynamics-crm-2011

我已经为我们的报价产品注册了一个插件。该插件在我们的测试环境中运行良好。我已经测试了很多次。然后在主服务器中注册该插件。但是,出现以下情况: 当我首先创建或更新报价产品时,报价产品表格会变灰:

enter image description here

点击报价表单后会出现错误。没有可用的日志文件(如您所见)。我调试了插件,但也没有错误。单击“确定”后,错误消失,所需业务发生在报价产品上(对于税收字段)。意味着插件代码没有错误并且工作得很好。代码如下:

using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Xrm;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk.Deployment;

public class Plugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)
        serviceProvider.GetService(typeof(IPluginExecutionContext));
        Entity entity;
        if (context.InputParameters.Contains("Target") &&
        context.InputParameters["Target"] is Entity)
        {
            entity = (Entity)context.InputParameters["Target"];
            if (entity.LogicalName != "quotedetail") { return; }
        }
        else
        {
            return;
        }
        try
        {
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(
            typeof(IOrganizationServiceFactory));
            IOrganizationService service =
            serviceFactory.CreateOrganizationService(context.UserId);
            if (context.MessageName == "Create")
            {
                Entity QuoteProduct = (Entity)context.InputParameters["Target"];
                Guid QPID = QuoteProduct.Id;
                TaxCreator(service, QPID);
            }
            if (context.MessageName == "Update" && context.Depth < 3)
            {
                Entity QuoteProduct = (Entity)context.PostEntityImages["Target"];
                Guid QPID = QuoteProduct.Id;
                TaxUpdater(service, QPID);
            }
        }
        catch (FaultException<OrganizationServiceFault> ex)
        {
            throw new InvalidPluginExecutionException(
            "An error occurred in the plug-in.", ex);
        }
    }
    private static void TaxCreator(IOrganizationService service, Guid QPID)
    {
        using (var crm = new XrmServiceContext(service))
        {
            var QuoteProduct = crm.QuoteDetailSet.Where(c => c.QuoteDetailId == QPID).First();
            var SaleSetting = crm.new_salessettingSet.Where(c => c.statecode == 0).First();
            double TaxPercent = (Convert.ToDouble(SaleSetting.new_TaxPercent) / 100);
            if (QuoteProduct.IsPriceOverridden == false)
            {
                decimal Tax = (decimal)Convert.ToDecimal(Convert.ToDouble(QuoteProduct.BaseAmount - QuoteProduct.ManualDiscountAmount.GetValueOrDefault()) * TaxPercent);
                decimal PricePerUnit = (decimal)(QuoteProduct.PricePerUnit.GetValueOrDefault() - QuoteProduct.VolumeDiscountAmount.GetValueOrDefault());
                crm.UpdateObject(QuoteProduct);
                crm.SaveChanges();
                QuoteProduct.Attributes["tax"] = new Money(Tax);
                QuoteProduct.Attributes["new_result"] = new Money(PricePerUnit);
                crm.UpdateObject(QuoteProduct);
                crm.SaveChanges();
            }
        }
    }
    private static void TaxUpdater(IOrganizationService service, Guid QPID)
    {
        using (var crm = new XrmServiceContext(service))
        {
            var QuoteProduct = crm.QuoteDetailSet.Where(c => c.QuoteDetailId == QPID).First();
            var SaleSetting = crm.new_salessettingSet.Where(c => c.statecode == 0).First();
            double TaxPercent = (Convert.ToDouble(SaleSetting.new_TaxPercent) / 100);
            if (QuoteProduct.IsPriceOverridden == false)
            {
                decimal Tax = (decimal)Convert.ToDecimal(Convert.ToDouble(QuoteProduct.BaseAmount - QuoteProduct.ManualDiscountAmount.GetValueOrDefault()) * TaxPercent);
                decimal PricePerUnit = (decimal)(QuoteProduct.PricePerUnit.GetValueOrDefault() - QuoteProduct.VolumeDiscountAmount.GetValueOrDefault());
                crm.UpdateObject(QuoteProduct);
                crm.SaveChanges();
                QuoteProduct.Attributes["tax"] = new Money(Tax);
                QuoteProduct.Attributes["new_result"] = new Money(PricePerUnit);
                crm.UpdateObject(QuoteProduct);
                crm.SaveChanges();
            }
        }
    }
}

我还检查了服务器上的事件查看器是否有错误,没有结果! 我已经在创建和更新报价产品时注册了我的插件。 非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        Entity entity;
        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            entity = (Entity)context.InputParameters["Target"];
            if (entity.LogicalName != "quotedetail") { return; }
        }
        else
        {
            return;
        }

        try
        {
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            QuoteDetail QuoteProduct = ((Entity)context.InputParameters["Target"]).ToEntity<QuoteDetail>();
            if (context.MessageName == "Create" || context.MessageName == "Update")
                // && context.Depth < 3) //try to avoid depth unless you have to have it
            {
                TaxSetter(service, QuoteProduct);
            }
        }
        catch (FaultException<OrganizationServiceFault> ex)
        {
            throw new InvalidPluginExecutionException( "An error occurred in the plug-in.", ex);
        }
    }

    private static void TaxSetter(IOrganizationService service, QuoteDetail product)
    {
        using (var crm = new TrainingContext(service))
        {
            var QuoteProduct = product.ToEntity<QuoteDetail>();
            if (QuoteProduct.IsPriceOverridden == false)
            {
                double TaxPercent = Convert.ToDouble(50 / 100);
                decimal Tax = (decimal)Convert.ToDecimal(Convert.ToDouble(QuoteProduct.BaseAmount - QuoteProduct.ManualDiscountAmount.GetValueOrDefault()) * TaxPercent);
                decimal PricePerUnit = (decimal)(QuoteProduct.PricePerUnit.GetValueOrDefault() - QuoteProduct.VolumeDiscountAmount.GetValueOrDefault());

                QuoteProduct.Tax = Tax; //depending on how you the parameters passed into CrmSvcUtil
                QuoteProduct.Attributes["new_result"] = new Money(PricePerUnit); //same deal here

                //crm.UpdateObject(QuoteProduct);
                //crm.SaveChanges();
                //code not needed, the Plugin context will take care of this for you
            }
        }
    }

这个想法是,您希望您的插件上下文适合您;而你想要尽可能少地公开做。我改变了税收计算,因为我没有你的属性;你会想要改变它们。如果我仍然误解了您的问题,我很乐意删除我的帖子(或尝试)。

答案 1 :(得分:2)

我会对它进行鸟枪调试。实现以下跟踪。通常,我将跟踪器的声明作为类成员放置(因此它对类中的所有帮助方法都可见)并在每次操作(或多或少)之后写入(当绝望和沮丧时)。然后,当程序自身崩溃时(或者当我故意使其崩溃以查看跟踪日志时),我通常可以指出问题区域。

public class MyPlugin _ IPlugin
{
  private ITracingService _trace;

  public void Execute(IServiceProvider service)
  {
    _trace = (ITracingService)service.GetService(typeof(ITracingService));
    _trace.Trace("Commencing.");
    ...
    _trace.Trace("Right before an operation. " + someValue);
    PerformAnOperation();
    _trace.Trace("Right before an other operation. " + someOtherValue);
    PerformAnOtherOperation();
    ...
    throw new Exception("Intentional!");
  }
}

您可以通过以下方式查看问题的确切位置。根据我的经验,一旦有人知道哪里它很疼,就可以轻松地建议如何解决这个问题。

编辑:

由于OP要求更多详细信息,我正在接受他的代码并为其添加跟踪算法。有点多余,但显然,CRM可能非常混乱。我自己去了。

public class Plugin : IPlugin
{
  // Here we declare our tracer.
  private ITracingService _trace;

  public void Execute(IServiceProvider serviceProvider)
  {
    // Here we create it.
    _trace = (ITracingService)serviceProvider
      .GetService(typeof(ITracingService));
    _trace.Trace("Commencing.");

    // Here we crash our plugin just to make sure that we can see the logs 
    // with trace information. This statement should be gradually moved down
    // the code to discover where exactly the plugin brakes.
    throw new Exception("Intentional!");

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

    try { ... }
    catch (FaultException<OrganizationServiceFault> ex)
    {
      throw new InvalidPluginExecutionException(
        "An error occurred in the plug-in.", ex);
    }

    // Here we catch all other kinds of bad things that can happen.
    catch(Exception exception) { throw exception; }
  }

  private static void TaxCreator(IOrganizationService service, Guid QPID)
  {
    // Here we add a line to the trace hoping that the execution gets here.
    _trace.Trace("Entered TaxCreator.");

    using (var crm = new XrmServiceContext(service))
    {
      var QuoteProduct = crm.QuoteDetailSet.Where(...).First();
      var SaleSetting = crm.new_salessettingSet.Where(...).First();
      double TaxPercent = (Convert.ToDouble(...) / 100);

      // Here we add a line to the trace to see if we get past this point.
      _trace.Trace("Approaching if statement.");

      if (QuoteProduct.IsPriceOverridden == false) { ... }
    }
  }

  private static void TaxUpdater(IOrganizationService service, Guid QPID)
  {
    // Here we add a line to the trace hoping that the execution gets here.
    _trace.Trace("Entered TaxUpdater.");

    ...
  }
}