I have used project as the sample entity.
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
// Check whether the input parameters property bag contains a target
// of the create operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
{
// Obtain the target business entity from the input parmameters.
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
// Verify that the entity represents an account.
if (entity.Name != "new_project") { return; }
}
else
{
return;
}
//Query for the max ref number
ICrmService service = context.CreateCrmService(true);
QueryExpression qe = new QueryExpression();
qe.EntityName = "new_project";
ColumnSet cols = new ColumnSet();
cols.Attributes.AddRange(new string[] { "new_projrefnumber" });
qe.PageInfo = new PagingInfo();
qe.PageInfo.Count = 1;
qe.PageInfo.PageNumber = 1;
OrderExpression order = new OrderExpression();
order.AttributeName = "new_projrefnumber";
order.OrderType = OrderType.Descending;
qe.Orders.AddRange(new OrderExpression[] { order });
RetrieveMultipleRequest req = new RetrieveMultipleRequest();
req.ReturnDynamicEntities = true;
req.Query = qe;
//BusinessEntityCollection entityCol = service.RetrieveMultiple(qe);
RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);
// find the existing max Ref number from the project entity, increment it and update it to the properties.
foreach (BusinessEntity be in resp.BusinessEntityCollection.BusinessEntities)
{
DynamicEntity proj = (DynamicEntity)be;
if (proj.Properties.Contains("new_projrefnumber"))
{
if (proj["new_projrefnumber"] != null)
{
string currentRefNumber = proj["new_projrefnumber"].ToString();
int refNumber = Convert.ToInt32(currentRefNumber) + 1;
if (entity.Properties.Contains("new_projrefnumber"))
{
entity.Properties["new_projrefnumber"] = refNumber.ToString();
}
else
{
entity.Properties.Add(new StringProperty("new_projrefnumber", refNumber.ToString()));
}
}
}
}
}
}
No comments:
Post a Comment