I am looking to build a fairly simple plug in that calculates the amount of "units" used & remaining. I have two custom entites (Parent) bc\_learninglicences & ( Child) bc\_llbalance, the plug - in fires on create of bc\_llbalance and another for update. 

 bc\_llbalance: Contains

 bc\_learninglicense (Look up field on parent entite bc\_learninglicences / bc\_name)

 bc\_units (units that are used by this record)

bc\_learninglicences: Contains 

 bc\_name

 bc\_unitsquantity (This is set to the total qty of units)

 bc\_unitsused (this needs to inherit the sum of "bc\_units" on "bc\_llbalance")

 bc\_unitsremaining ( simply bc\_unitsquantity - bc\_unitsused )

Ok so I have included the code I have just been trying to figure out how to get bc\_unitsused to inherit the sum... 

p.s I am new to developing for CRM 2011 with only a few weeks/ few projects experience. 

```
// 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);
    }
}

```

So i Think the issue lays with the connection to the parent   
entity "bc\_learninglicences", "bc\_learninglicense" is the look up field on the Child   
entity "bc\_llbalance".

Hope this makes sense: Basically its not working 

i get this error from 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>

```

Any advise or help with this solution would be greatfully appreciated.

Thanks for any time taken to aid me with this!

I also had some jscritp on load of parent form which calculates the sum from subgrid of children entities: This is just to clarify what i need to achieve... this is not sufficient as the parent form only updates on load where with plugin bc\_learninglicences will be updated on create of 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") }

     }

```