Retrieve data from View based on View Name in plugin

We had requirement to update field on multiple records of an entity based on another entity flag. We need to keep it in mind that In future, If we change View of an entity then it will not affect our plugin logic.

Here we need to retrieve records from one of the active views of an entity instead of writing query directly on entity or relationship.

We have option to query on views using CRM base entity :

1. savedquery (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/web-api/savedquery?view=dynamics-ce-odata-9)

2. userquery (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/web-api/userquery?view=dynamics-ce-odata-9)

Note : System Views are stored in the SavedQuery entity, while User Views are stored in the UserQuery Entity.

We have system view so in our case we used “savedquery” entity instead of “userquery” entity.

Basic code to get the fetchxml of view are as below :

private string getFetchXml(IOrganizationService service)
{
var query = new QueryExpression
{
EntityName = "savedquery",
ColumnSet = new ColumnSet("savedqueryid", "name", "fetchxml"),
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = { "View Name" }//View Name - "Active Accounts"
},
new ConditionExpression
{
AttributeName = "returnedtypecode",
Operator = ConditionOperator.Equal,
Values = { "Entity Name" } //Account
}
}
}
};
var result = service.RetrieveMultiple(query);
var view = result.Entities.FirstOrDefault();
var fetchXml = view.GetAttributeValue("fetchxml");
return fetchXml;
}

How to debug a custom workflow activity in Dynamics CRM

Sandeep Sharma's CRM Blog

The following are the steps we have to follow in order to debug a custom workflow activity in Dynamics CRM:

Step 1. Run the Plugin Registration Tool as an administrator.

Step 2. Connect to your CRM organization using the Plugin Registration Tool (Fig. 1).

CWA 1

(Fig. 1)

Step 3. Register your Custom Workflow Activity.

Step 4. Create a workflow in CRM which trigger your Custom Workflow Activity.

Step 5. Select the newly registered custom workflow activity and click on the ‘Plug-in Profiler’ button (Fig. 2)

CWA 2(Fig. 2)

Step 6. If you do not see the Plug-in Profiler button then you need to install the Profiler by clicking on the ‘Install Profiler’ button. Once the installation is done successfully, the Plugin Registration Tool shows the “Uninstall Profiler” button and a new item ‘Plug-in Profiler’ is added to the registered components (Fig. 3).

CWA 3

(Fig. 3)

Step 7. Select the “Plug-in Profiler” and then…

View original post 222 more words

Recalculate Rollup Field using Plugin in Dynamics 365

I came across a situation where we need to update Rollup Field value when it’s related entity field value changed(New record added or update existing value). Rollup field calculating values based on related entity field. i.e., We have subgrid of related entity on the primary entity.

Rollup Field Value = Sum of related entity record field values

We need to register our plugin on Create and Update message of related entity field to test the below code.

Plugin Code :

// Main class..

public class RecalculateRollupFieldOnRelatedEntityPostOp : IPlugin
{
private Money rollupField;
Entity _relatedEntity;
EntityReference __relatedEntityRef;
decimal oldRollupFieldValue, newollupFieldValue;

// Execute method..
public void Execute(IServiceProvider serviceProvider)
{
var _context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var _serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var _service = _serviceFactory.CreateOrganizationService(_context.UserId);
var _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

if (_context.InputParameters.Contains("Target") && _context.InputParameters["Target"] is Entity)
{
var _primaryEntityContext = (Entity)_context.InputParameters["Target"];

if (_primaryEntityContext.LogicalName != "EntityLogicalName")
return;

if (_primaryEntityContext.Contains("RelatedEntityLookupSchemaName") ||
_primaryEntityContext.GetAttributeValue("RelatedEntityLookupSchemaName") != null)
{
UpdateRollupField(_service, _tracingService, _primaryEntityContext);
}

}

}

// Function to calcualte Rollup field..

private void UpdateRollupField(IOrganizationService _service, ITracingService _tracingService, Entity _primaryEntityContext)
{
__relatedEntityRef = _primaryEntityContext.GetAttributeValue("CRMLookupfieldName");

if (__relatedEntityRef != null)
{
_relatedEntity = _service.Retrieve(__relatedEntityRef.LogicalName, __relatedEntityRef.Id, new ColumnSet("relatedEntityRollupField"));
rollupField = _relatedEntity.GetAttributeValue("relatedEntityRollupField");
}
if (rollupField != null)
{
oldRollupFieldValue = _relatedEntity.GetAttributeValue("relatedEntityRollupField").Value;
// print the old value of the roll-up field
_tracingService.Trace("Old Rollupfield Value) = " + _relatedEntity.GetAttributeValue("relatedEntityRollupField"));

CalculateRollupFieldRequest crfrRequested = new CalculateRollupFieldRequest
{
Target = new EntityReference(__relatedEntityRef.LogicalName, __relatedEntityRef.Id),
FieldName = "relatedEntityRollupField"
};

CalculateRollupFieldResponse responseRequested = (CalculateRollupFieldResponse)_service.Execute(crfrRequested);

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

// print the new value of the roll-up field
_tracingService.Trace("New Rollupfield Value) = " + _relatedEntity.GetAttributeValue("relatedEntityRollupField"));

newollupFieldValue = _relatedEntity.GetAttributeValue("relatedEntityRollupField").Value;
}
}
}

 

 

 

Calculate RollupField using Javascript WebApi

As we know that rollup field recalculate values every hour but in some cases if we need to recalculate value to represent the value on another entity, then we can do it using JavaScript Web API.

Suppose, Rollup field is mapped with another entity and we need latest value of rollup on create of related entity record then below code is useful to achieve your requirements :

The CalculateRollupField function inside the web request requires few parameter to know which rollup field you want to to calculate:

  • The EntitySetName of the target record.
  • The GUID of the target record.
  • The schema name of the target field.

function calculateRollupField(TargetEntitySetName, TargetRecordId, TargetRollupFieldName)
{
   TargetRecordId= TargetRecordId.replace("{", "").replace("}", "");
    var req = new XMLHttpRequest();
    req.open(this.method, this.url, true); // Need this to initiate the request
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" +
        "CalculateRollupField(Target=@p1,FieldName=@p2)?" +
        "@p1={'@odata.id':'" + TargetEntitySetName+ "(" + TargetRecordId+ ")'}&" +
        "@p2='" + TargetRollupFieldName+ "'", true);
    req.onreadystatechange = function ()
    {
        if (this.readyState === 4)
        {            
            req.onreadystatechange = null;
            if (this.status === 200)
            {
                var results = JSON.parse(this.response);
                //Use XRM commands to perform operation..
            }
            else
            {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };    
    req.send(JSON.stringify({}));
}

We can retrieve the updated value via JavaScript API call and use XRM commands to replace the updated value in the form.

Top Dynamics CRM/365 Blogs and Websites

Microsoft Dynamics 365 Documentationhttps://docs.microsoft.com/en-us/dynamics365/

Microsoft Dynamics Community Pagehttps://community.dynamics.com/

MS Dynamics Newshttps://msdynamicsworld.com/news

Nishant Rana’s Webloghttps://nishantrana.me/

Deepesh Somani’s Bloghttps://dynamicsofdynamicscrm.com/

Arpit’s Dynamics CRM Blog http://arpitmscrmhunt.blogspot.com/

Arun Potti’s MS CRM Bloghttps://arunpotti.wordpress.com/

Arun Vinoth’s Dynamics Blog https://arundynamix.blogspot.com/

Hosk’s Dynamics CRM Bloghttps://crmbusiness.wordpress.com/

Neil Parkhurst’s Bloghttps://neilparkhurst.com/

Dynamics CRM Tip of the Dayhttps://crmtipoftheday.com/

Vishal grad’s Dynamics CRM bloghttps://dynamics365blocks.wordpress.com/

Power Objects Bloghttps://www.powerobjects.com/blog/

Inogic’s Bloghttps://www.inogic.com/blog/

Magnetism’s Blog https://www.magnetismsolutions.com/blog

Megan Walker’s Bloghttps://meganvwalker.com/blog/

PowerXRM’s Bloghttp://www.powerxrm.com/blog/

CRMUGhttps://www.crmug.com/home

 

Continue…

Tools for Dynamics CRM/365

Dynamics CRM Power PaneBrowser extension for Dynamics CRM

https://chrome.google.com/webstore/detail/dynamics-crm-power-pane/eadknamngiibbmjdfokmppfooolhdidc

 

Browser extensions for Dynamics CRMBrowser extension for Dynamics CRM

https://community.dynamics.com/crm/b/crmtechie/archive/2018/02/01/browser-extensions-for-dynamics-crm

 

XrmToolBox – Provides tools to ease customization, configuration and operation tasks for anything built on CDS, including Dynamics 365 CE (formerly CRM) and model-driven PowerApps

https://www.xrmtoolbox.com/

 

Ribbon Workbench – The Ribbon Workbench has been the standard for editing the Dynamics CRM Ribbon

https://www.develop1.net/public/rwb/ribbonworkbench.aspx

 

KingswaySoft – SSIS Integration Toolkit for Microsoft Dynamics 365
https://www.kingswaysoft.com/products/ssis-integration-toolkit-for-microsoft-dynamics-365

 

DocumentsCorePack – Professional document generation and processing in Microsoft Dynamics 365!

https://www.mscrm-addons.com/Products/DocumentsCorePack

 

CRM Rest Builder – A tool for CRM 2015/2016 & D365 CE (7.0+) Online & On Premise to generate JavaScript code using the 2011 & Web API REST endpoints.

https://github.com/jlattimer/CRMRESTBuilder

 

FetchXML Formatter Online – Online tool for quick formatting of FetchXML in Dynamics CRM before using into C#/,JS code.

https://www.ashishvishwakarma.com/FetchXmlFormatter/

 

Continue…

What’s new changes in Dynamics 365 version 9 – Useful Links

General Changes : https://docs.microsoft.com/en-us/dynamics365/get-started/whats-new/customer-engagement/new-in-version-9

For Developers : https://docs.microsoft.com/en-us/dynamics365/get-started/whats-new/customer-engagement/new-in-version-9-for-developers

Importan changes (Deprecations) coming : https://docs.microsoft.com/en-us/dynamics365/get-started/whats-new/customer-engagement/important-changes-coming

 

Some useful links which will help you during Upgrade project (Version 8.2 to 9): 

https://community.dynamics.com/crm/b/briteglobalsolutions/archive/2018/01/01/migrating-your-client-api-to-dynamics-365-ce-v9-part-i

All JavaScript Changes – Dynamics 365 9.0

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-navigation/openform

Dynamics 365 9.0 Client-side navigation

 

For XRM.Utility.OpenEntityForm changes:

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-navigation/openform

ttps://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/set-field-values-using-parameters-passed-form

Dynamics 365 9.0 Client-side navigation

 

For RibbonWorkBench changes:

https://stackoverflow.com/questions/48202316/how-to-get-formcontext-in-ribbon-command-of-dynamics-365-9-0

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/customize-dev/pass-dynamics-365-data-page-parameter-ribbon-actions