LINQ: GroupBy, Sum and EntityCollection

Just resharing a sample code that could be used for group by and sum operation on EntityCollection.

Suppose below is the output that we want

Continue reading “LINQ: GroupBy, Sum and EntityCollection”

Linq and Parallel.ForEach loop

If requests are internal then Linq query will perform better over Parallel.ForEach and for external request Parallel.ForEach will perform better than Linq request.

Parller Foreach is faster than traditional For or ForEach loop

private List GetOrganizationRequests(List incidents)
             var orgRequests = new List();
         Parallel.ForEach(incidents.Where(x => x.Contains("statuscode") && x.Contains("qi.queueitemid") && x.Contains("tm.queueid")), incident =>
             orgRequests.Add(new AddToQueueRequest
                 SourceQueueId = ((EntityReference)((AliasedValue)incident["qi.queueid"]).Value).Id,
                 Target = new EntityReference("incident", incident.Id),
                 DestinationQueueId = ((EntityReference)((AliasedValue)incident["tm.queueid"]).Value).Id
         return orgRequests;

Linq query for same request

private List GetOrganizationRequests(List incidents) =>
             incidents.Where(x => x.Contains("statuscode") && x.Contains("qi.queueitemid") && x.Contains("tm.queueid"))
             .Select(z => new AddToQueueRequest()
                 SourceQueueId = ((EntityReference)((AliasedValue)z["qi.queueid"]).Value).Id,
                 Target = new EntityReference("incident", z.Id),
                 DestinationQueueId = ((EntityReference)((AliasedValue)z["tm.queueid"]).Value).Id

hope its helps !!

workflow execution from Plugin

Here is quick sample code for workflow execution from Plugin …

Execute workflow …

Continue reading “workflow execution from Plugin”

bulk Create/Update/Delete for Dynamics 365


Create / Update / Delete can be done with bulk operation, to avoid more DB hits and it will improve performance of the plugins and or code.

Here is reference MSDN URL

Default max batch size is 1000, its applicable for all three create/update/delete.

  1. bulk Create can be done with following code snippet
CreateRequest createRequest = new CreateRequest { Target = 'your Entity Object' };

2. bulk Update can be done with following code snippet

UpdateRequest updateRequest = new UpdateRequest { Target = 'your Entity Object' };

3. bulk Delete can be done with following code snippet

DeleteRequest deleteRequest = new DeleteRequest { Target = 'your Entity Reference Object' };

Here are sample code blocks for bulk Update


Create multiple execute request

/// <summary>
 /// Create an ExecuteMultipleRequest object
 /// </summary>
 /// <returns></returns>
 private static ExecuteMultipleRequest CreateBulkExcuteRequest()
 var multipleRequest = new ExecuteMultipleRequest()
 // Assign settings that define execution behavior: continue on error, return responses.
 Settings = new ExecuteMultipleSettings()
 ContinueOnError = false,
 ReturnResponses = true
 // Create an empty organization request collection.
 Requests = new OrganizationRequestCollection()
 return multipleRequest;

Continue reading “bulk Create/Update/Delete for Dynamics 365”

Refresh roll up field from plugin

data retrival

Roll up fields are very useful, it reduce lots of manual and coding efforts. This rolls up field will auto refresh by each hour by default, off course it can be changed any time.

But what if developer wants to refresh it on fly from plugin itself to make following logic to work perfectly, which is dependent on this roll up field? Is there any way for this? or roll up fields are not useful in such a condition.

Yes, there is way we need to execute “CalculateRollupFieldRequest and CalculateRollupFieldResponce” functions to refresh roll up attributes.

Call to refresh the roll up field, here is sample code….

Entity incident = new Entity(“incident”)
{ Id = incidentId };

int refreshedExAssetRequested = RefreshRollup(context, incident, “soft_exassetrequested”);
context.Trace(“new soft_exassetrequested: ” + refreshedExAssetRequested);

Function to execute

/// <summary>
/// refresh attribute
/// </summary>
/// <param name=”context”></param>
/// <param name=”entityToRefresh”></param>
/// <param name=”fieldToRefresh”></param>
/// <returns></returns>
internal static int RefreshRollup(SelectContext context, Entity entityToRefresh, string fieldToRefresh)

// print the old value of the roll-up field
context.Trace(“Total Accepted Qty (updated)= ” + entityToRefresh.GetAttributeValue<int>(fieldToRefresh));
// create a request by passing an entity reference and the targeted rollup field name
CalculateRollupFieldRequest crfrRequested = new CalculateRollupFieldRequest
Target = new EntityReference(entityToRefresh.LogicalName, entityToRefresh.Id),
FieldName = fieldToRefresh

CalculateRollupFieldResponse responseRequested = (CalculateRollupFieldResponse)context.OrgService.Execute(crfrRequested);

// read the entity and value of the rollup field
entityToRefresh = responseRequested.Entity;

// print the new value of the roll-up field
context.Trace(“Total Accepted Qty (updated)= ” + entityToRefresh.GetAttributeValue<int>(fieldToRefresh));

return entityToRefresh.GetAttributeValue<int>(fieldToRefresh);

Also, same rollup can be refreshed from JavaScript, here is sample code for it. Only thing you need to keep in the memory is that this refresh is async call and may take 10 second to refresh.

function RefreshSHRollup(entityToRefresh, entityId, rollupField) {

    //var requestUrl = Xrm.Page.context.getClientUrl() + "/api/data/v9.0/CalculateRollupField(Target=@tid,FieldName=@fn)?@tid={'':'" + entityToRefresh + "(" + entityId + ")'}&@fn='" + rollupField + "'";
    var requestUrl = Xrm.Page.context.getClientUrl() + "/api/data/v9.0/CalculateRollupField(Target=@p1,FieldName=@p2)?@p1={'':'" + entityToRefresh + "s(" + entityId + ")'}&@p2='" + rollupField + "'"

    try {

        var req = new XMLHttpRequest();"GET", requestUrl, false);

    } catch (e) {


That’s it!


Get complete trace through multiple level plugins



While extending MSD CRM with complicated business requirements, we write many plugins; one plugin triggers from another plugin’s create or update. In such a scenarios if one of child plugin breaks then it will provide only current plugins trace, it’s very hard to analyse that particular scenario or replicate that same scenario in Dev environment without the proper trace.  if we develop with normal plugin sample it won’t generates that all trace from various different plugins, it will provide only one plugin’s trace where it actually got a break.  Continue reading “Get complete trace through multiple level plugins”

Plugin debugging


Have you ever stuck in a situation where the plugin working perfectly in a test environment but not the SIT/UAT/Production environment?

Remote debugging might be a tricky setup in most of the production server because of the firewall constraint or even many times developer does not have access to the following environment. In such situation how we can survive, Debugging skills will save us in this situation.

Debugging is must skill for every developer while updating or fixing any code; we need debugging skills.  Continue reading “Plugin debugging”

Linq Entity with filter

data retrival

Many times we need to joins with filters in one entity or both of them. Here is the simple sample …

Continue reading “Linq Entity with filter”

Date Issue


In MS CRM, we have multiple date time zone setting, each user can set his own time zone as per his requirement.

Thus, Microsoft Dynamics CRM stores all DateTime fields in UTC time, so by using the ‘DateTime.UtcNow’ approach our dates will be converted into UTC time before hitting the database. Continue reading “Date Issue”

Consume Web-request from Plugin


Generally, CRM not works alone, it includes many other application, such time we needs to move data from one application to another. In this situation we needs integration; We do integration with either “HttpWebRequest” or “BasicHttpBinding”.  Continue reading “Consume Web-request from Plugin”