【问题标题】:CRM 2011: Plug-in - fetch statement, to inherit total sum from child entitesCRM 2011:插件 - 获取语句,从子实体继承总和
【发布时间】:2013-01-08 02:49:33
【问题描述】:

我正在寻找构建一个相当简单的插件来计算使用和剩余的“单位”数量。我有两个自定义实体(父)bc_learninglicences 和(子)bc_llbalance,插件在创建 bc_llbalance 时触发,另一个用于更新。
bc_llbalance:包含
bc_learninglicense(在父实体 bc_learninglicences / bc_name 上查找字段)
bc_units(此记录使用的单位)

bc_learninglicences:包含
bc_name
bc_unitsquantity (设置为单位的总数量)
bc_unitsused(这需要继承“bc_llbalance”上的“bc_units”之和)
bc_unitsremaining (简单的 bc_unitsquantity - bc_unitsused )
好的,所以我已经包含了我刚刚试图弄清楚如何让 bc_units 用于继承总和的代码......

p.s 我是 CRM 2011 开发新手,只有几周/几个项目经验。

// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =(ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

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

    EntityReference a = (EntityReference)entity.Attributes["bc_learninglicense"];// ((EntityReference)targetEntity.Attributes["bc_learninglicense"]).Id;

    if (entity.LogicalName == "bc_llbalance")
    {  
        //fetchxml to get the sum total of estimatedvalue
        string value_sum = string.Format(@"<fetch distinct='false' mapping='logical'
          aggregate='true'><entity name='bc_llbalance'><attribute name='bc_units'
          alias='units_sum' aggregate='sum' /><filter type='and'><condition
          attribute='bc_learninglicense' operator='eq' value='{0}' uiname=''</filter></entity>
          </fetch>", a.Id);

        FetchExpression fetch = new FetchExpression(value_sum);
        EntityCollection value_sum_result = service.RetrieveMultiple(fetch);
        decimal TotalValue = 0;
        // decimal TotalValue = 0;

        foreach (var c in value_sum_result.Entities)
        {
            TotalValue = ((Decimal)((AliasedValue)c["value_sum"]).Value);
        }
        Entity llc = new Entity("bc_learninglicences");
        llc.Id = a.Id;
        llc.Attributes["bc_unitsused"] = TotalValue;
        service.Update(llc);
    }
}


所以我认为问题在于与父
实体“bc_learninglicences”的连接,“bc_learninglicense”是子
实体“bc_llbalance”的查找字段。

希望这是有道理的:基本上它不起作用

我从 crm 收到此错误

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected exception from plug-in (Execute): LearningLicenses.LearningLicenses: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.Detail: 
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
  <ErrorCode>-2147220956</ErrorCode>
  <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
  <Message>Unexpected exception from plug-in (Execute): LearningLicenses.LearningLicenses: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.</Message>
  <Timestamp>2013-01-24T13:11:51.2373399Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>

[LearningLicenses: LearningLicenses.LearningLicenses]
[c1b35170-c563-e211-8c6d-b499bafd5e5b: LearningLicenses.LearningLicenses: Create of bc_llbalance]


</TraceText>
</OrganizationServiceFault>



任何有关此解决方案的建议或帮助将不胜感激。

感谢您花时间帮助我!
我在加载父表单时也有一些jscritp,它计算子实体的子网格的总和:这只是为了澄清我需要实现的目标......这还不够,因为父表单仅在加载时更新插件 bc_learninglicences 将在创建 bc_llbalance 时更新。

      function timeout(){
     setTimeout(calcUnitTotal, 3000);
    }

  function calcUnitTotal(){

   var grid = document.getElementById('Lines').control; 
   var ids = gridControl.get_allRecordIds();

   var sum = 0;
   var cellValue;

  for(i = 0; i < ids.length; i++) {

     var cellValue = grid.get_selectedRecords('bc_units')[i].value;
     var number = Number(cellValue.replace(/[^0-9\.]+/g,""));
     sum = sum + number;
                                                    }


   Xrm.Page.data.entity.attributes.get('bc_unitsused').setValue(sum);

    var val1 = Xrm.Page.getAttribute('bc_unitsquantity').getValue(); 

    if(val1 != null && sum != null )
       {

    var result = val1 -  sum;

    Xrm.Page.data.entity.attributes.get('bc_unitsremaining').setValue(result); 

     }
      else { alert(val1 + sum + "error: Values not passed for Remaining") }

     }

【问题讨论】:

  • 你能重构你的 catch 块吗 - 你隐藏了实际的错误。此外,如果您没有对错误信息做任何事情,为什么还要有一个 catch 块?编辑:等等,你有两个 catch 块没有做任何事情。基本上,在我们提供帮助之前,我们需要来自 ex.Message 的信息(或删除 catch 块并让错误被抛出)
  • 谢谢。我已经删除了 try&catch 并将“TotalValue”更改为十进制而不是字符串。这给出了一个新错误,我在这篇文章中用旧错误消息替换了它......
  • 好吧,我把最后一段代码改成了

    llc.Attributes["bc_name"] = a.Id;
    llc.Attributes["bc_unitsused"] = TotalValue;

    service.Update(llc);
    我现在有一个新错误 ---
    未处理的异常:-2147220991 xmlns:d2p1="schemas.datacontract.org/2004/07/System.Collections.Generic" /> 无效的 XML。 有什么想法吗?也可以假设这可能是失败的地方?

标签: c# plugins dynamics-crm-2011 dynamics-crm crm


【解决方案1】:

在这里工作是代码希望它可以帮助某人:

public void Execute(IServiceProvider serviceProvider)
    {
        {


            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            if (context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is Entity)
            {
            Entity entity = (Entity)context.InputParameters["Target"];
                Guid a = ((EntityReference)entity["bc_learninglicense"]).Id;
                Entity llc = new Entity("bc_learninglicences");
                llc.Id = a;

                        //fetchxml to get the sum total of estimatedvalue
            string value_sum = string.Format(@"         
                <fetch distinct='false' mapping='logical' aggregate='true'> 
                    <entity name='bc_llbalance'>
                        <attribute name='bc_units' alias='units_sum' aggregate='sum' />
                           <filter type='and'>
                            <condition attribute='bc_learninglicense' operator='eq' value='{0}' uiname='' uitype='' />
                           </filter>
                    </entity>
                </fetch>", a);

                       EntityCollection value_sum_result = service.RetrieveMultiple(new FetchExpression(value_sum));
                       decimal TotalValue = 0;
                       foreach (var c in value_sum_result.Entities)
                       {
                            TotalValue += ((Decimal)((AliasedValue)c["units_sum"]).Value);
                       }       
                        llc.Attributes["bc_unitsused"] = TotalValue;
                        service.Update(llc);
            }
        }
     }  

【讨论】:

  • TotalValue = ((Decimal)((AliasedValue)c["units_sum"]).Value);一定要使用 '+=' 否则每次都会覆盖该值?
  • 是的,在这种情况下,我得到了总和/总数字,因此使用 foreach(value_sum_result.Entities 中的 var c)循环遍历每个结果并返回总和。
【解决方案2】:

错误

The given key was not present in the dictionary

表示您正在尝试检索属性包中不存在的属性。

我猜这行是导致异常的原因:

TotalValue = ((Decimal)((AliasedValue)c["value_sum"]).Value);

在这里您假设值 value_sum 存在,但它可能不存在。

一种简单的测试方法是编写如下代码:

if (c.Attributes.ContainsKey("value_sum"))
{
    throw new InvalidPluginException("Test - yep no key in the dictionary here!");
}

一旦你能证明这是导致错误的原因,你就需要看看为什么会这样。

【讨论】:

  • 谢谢,是的,我注意到应该是... TotalValue = ((Decimal)((AliasedValue)c["units_sum"]).Value);我想,我现在收到一个错误 Invalid XML. Invalid XML “传递给平台的 XML 不是格式正确的 XML ...
  • 我也改了 llc.Id = a.Id;是 llc.Attributes["bc_name"] = a.Id;
  • 字段“bc_name”是文本字段吗?如果是这样,请尝试 = a.Id.ToString()(字段类型和分配的值应该匹配)
  • 是的,基本上 bc_unitsused & bc_name 存在于 bc_learninglicences(父实体)上,并且 bc_learninglicense 是 bc_llbalance(子实体)上的一个查找字段,用于查找 (bc_learninglicences -bc_name)...与“许可证”混淆" & "license" 我没有命名字段/实体:p。因此,对于那段代码,我试图将 bc_unitsused 设置为具有给定 bc_learninglicences(Parent) 的所有 (bc_llbalance-bc_units) 的总数。你会建议我如何构建它?非常感谢您的患者。
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2014-03-12
相关资源
最近更新 更多