CRM 2011 Online - 插件中的无限循环错误 - 无法找到它

时间:2013-01-13 13:12:52

标签: c# plugins dynamics-crm-2011

我正在使用以下插件,该插件在更新商机时执行:

public class PreOpportunityWin : Plugin
{
    public PreOpportunityWin() : base(typeof(PreOpportunityWin))
    {
        base.RegisteredEvents.Add(
        new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "opportunity", new Action<LocalPluginContext>(ExecuteAutonumber)));
    }

    protected void ExecuteAutonumber(LocalPluginContext localContext)
    {
        Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)localContext.PluginExecutionContext;
        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            //Organization Service
            IOrganizationService service = localContext.OrganizationService;
            //Tracing Service
            ITracingService trace = (ITracingService)localContext.TracingService;

            Entity Target = (Entity)context.InputParameters["Target"];
            var entity = service.Retrieve(
            Target.LogicalName, Target.Id, new ColumnSet(true));
            var entityStatusCode = (OptionSetValue)entity.Attributes["statuscode"];
            if (entityStatusCode.Value == 3)
            {
                //Code to execute if opportunity won
                trace.Trace("In the execute block...");

                //Depending on the retrieved name, generate the appropriate fetch xml
                string fetchXml = null;
                fetchXml = @"<fetch mapping='logical'> 
                <entity name='my_autonumber'><all-attributes/>
                <filter type=""and"">
                <condition attribute=""my_autonumberentity"" operator=""eq"" value=""opportunity"" />
                <condition attribute=""my_name"" operator=""eq"" value=""The Autonumber Record"" />
                </filter></entity></fetch>";

                try
                {
                    //Fetch the approiate autonumber record
                    EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));
                    string nextIncrementNumber = string.Empty;
                    if (result.Entities.Count == 1)
                    {
                        Entity autoNumber = result.Entities[0];

                        //Lock the autonumber enity
                        lock (autoNumber)
                        {
                            if (!autoNumber.Attributes.Contains("my_counter"))
                                throw new InvalidPluginExecutionException("my_counter must contain a value");
                            if (!autoNumber.Attributes.Contains("my_incrementunit"))
                                throw new InvalidPluginExecutionException("my_IncrementUnit must contain a value");
                            int counter = Int32.Parse(autoNumber.Attributes["my_counter"].ToString());
                            int incrementUnit = Int32.Parse(autoNumber.Attributes["my_incrementunit"].ToString());
                            string prefix = autoNumber.Attributes.Contains("my_prefix") ? autoNumber.Attributes["my_prefix"].ToString() : string.Empty;
                            string prefixSeparator = autoNumber.Attributes.Contains("my_prefixseparator") ? autoNumber.Attributes["my_prefixseparator"].ToString() : string.Empty;
                            string suffix = autoNumber.Attributes.Contains("my_suffix") ? autoNumber.Attributes["my_suffix"].ToString() : string.Empty;
                            string suffixseparator = autoNumber.Attributes.Contains("my_suffixseparator") ? autoNumber.Attributes["my_suffixseparator"].ToString() : string.Empty;
                            string numberFormatter = autoNumber.Attributes.Contains("my_numberformatter") ? autoNumber.Attributes["my_numberformatter"].ToString() : string.Empty;

                            string fieldToUpdate;
                            if (autoNumber.Attributes.Contains("my_entityautonumberfield"))
                                fieldToUpdate = autoNumber.Attributes["my_entityautonumberfield"].ToString();
                            else
                                throw new InvalidPluginExecutionException("my_entityautonumberfield should not be empty");
                            nextIncrementNumber = BuildAutoNumber(entity, prefix, prefixSeparator, suffix, suffixseparator, counter, incrementUnit, numberFormatter, service);

                            //Set project number
                            entity.Attributes["new_projectnumber"] = nextIncrementNumber;
                            autoNumber.Attributes["my_counter"] = counter + incrementUnit;
                            service.Update(autoNumber);
                      }
                  }
              }
              catch (Exception ex)
              {
                  throw new InvalidPluginExecutionException(string.Format("An error occured in Autonumber plugin: {0}", ex.ToString()));
              }
          }
      }
  }

  //This function builds the autonumber itself
  private string BuildAutoNumber(Entity entity, string prefix, string prefixSeparator, string suffix, string suffixSeparator, int counter, int incrementUnit, string numberFormatter, IOrganizationService service)
  {
      bool hasPrefix = false, hasSuffix = false;
  string returnNumber = string.Empty;

      prefix = "P";
      if (!string.IsNullOrEmpty(prefix))
      {
          hasPrefix = true;
      }
      counter = counter + incrementUnit;
      returnNumber = (hasPrefix ? prefix + prefixSeparator : "") + counter.ToString(numberFormatter) + (hasSuffix ? suffix + suffixSeparator : "");
      return returnNumber;
 }    

}

此插件在更新机会时执行,但会引发以下错误:

  

此工作流作业已取消,因为启动它的工作流程已取消   包括无限循环。更正工作流逻辑,然后重试。

我无法在任何地方找到无限循环,而且,我在创建机会时使用几乎相同的代码在另一个字段中追加另一个自动编号。两个插件之间的唯一区别是这个代码检查win状态:

Entity Target = (Entity)context.InputParameters["Target"];
var entity = service.Retrieve(Target.LogicalName, Target.Id, new ColumnSet(true));
var entityStatusCode = (OptionSetValue)entity.Attributes["statuscode"];
if (entityStatusCode.Value == 3)
  //Code to execute if opportunity won

有人可以为我详细说明这个错误吗?

2 个答案:

答案 0 :(得分:6)

在某个地方你有一个插件可以生成一个你没有发现的重复循环,请参阅我关于my_autonumber实体的问题。

要检查的值是IPluginExecutionContext.Depth,它会告诉您循环的次数。

后:

Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)localContext.PluginExecutionContext;

插入此行:

if (context.Depth > 1) return;

如果插件执行多次,这将终止处理。

答案 1 :(得分:1)

使用context.Depth进行使用。

使用context.Depth会使插件失败,你有另一个插件可以在你的插件中触发这个动作。

现在Depth将是2,但这是因为有另一个插件调用此插件。

我也面临这个问题,除了使用Context.Depth之外的任何其他解决方案?