Plugin on Pre-Validation Stage in Dynamics 365 CE

Recently we had a requirement to delete the Account record without deleting the associated Contact records.

If we try deleting the account record we’d get the following message box

The relationship definition can’t be updated as well to achieve this

So, we wrote a plugin on the pre-validation stage of pre-delete event of Account, which will retrieve and loop through all the child contact records and set its parent customer field as null.

In case of pre-operation the child records were not available.


public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService organizationService = serviceFactory.CreateOrganizationService(pluginContext.UserId);
EntityReference targetEntity = (EntityReference)pluginContext.InputParameters["Target"];
QueryExpression getContacts = new QueryExpression("contact");
getContacts.Criteria.AddCondition(new ConditionExpression("parentcustomerid", ConditionOperator.Equal, targetEntity.Id));EntityCollection allContacts = organizationService.RetrieveMultiple(getContacts);foreach (Entity contact in allContacts.Entities)
{
Entity contactToBeUpdated = new Entity("contact");
contactToBeUpdated.Id = contact.Id;
contactToBeUpdated.Attributes["parentcustomerid"] = null;
organizationService.Update(contactToBeUpdated);
}}

 

Another practical scenario

https://www.inogic.com/blog/2017/03/plugin-pre-validation-operation-to-show-an-error-message-as-well-as-log-the-error/

Hope it helps..

Using RetrieveRecordChangeHistoryRequest to get Audit Detail in Dynamics 365 CE

Just sharing a sample code to retrieve the Audit Detail using RetrieveRecordChangeHistoryRequest.


RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
changeRequest.Target = new EntityReference("entitySchemaName", "entityId"));
RetrieveRecordChangeHistoryResponse changeResponse =
(RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

AuditDetailCollection auditDetailCollection = changeResponse.AuditDetailCollection;

foreach (AttributeAuditDetail attrAuditDetail in auditDetailCollection.AuditDetails)
{
var auditRecord = attrAuditDetail.AuditRecord;

Console.WriteLine("Entity: " + ((EntityReference)auditRecord.Attributes["objectid"]).LogicalName);
Console.WriteLine("Operation: " + auditRecord.FormattedValues["operation"]);
Console.WriteLine("Action: " + auditRecord.FormattedValues["action"]);

var newValueEntity = attrAuditDetail.NewValue;

foreach(var attrNewValue in newValueEntity.Attributes)
{
Console.WriteLine("New Key: " + attrNewValue.Key + "New Value: " + attrNewValue.Value);
}

var oldValueEntity = attrAuditDetail.OldValue;

foreach (var attrOldValue in oldValueEntity.Attributes)
{
Console.WriteLine("Old Key: " + attrOldValue.Key + "Old Value: " + attrOldValue.Value);
}
}

The record whose Audit History we are retrieving :

Output :

AuditDetail.AuditRecord :

AuditDetail.OldValue n NewValue:

Hope it helps..

Alternate Key not getting created on solution import in Dynamics 365

Recently, we moved our Solution from Development to Test. Then on running one of the SSIS Packages we got the below error

The specified key attributes are not a defined key for the entity [4] CRM service call returned an error:

On opening the Entity for customization, and checking for the key, we saw that it was in the Status Pending.

On opening the system job, there was no detail for the error.

We normally get this error, if there are records already available that have duplicate values for that alternate key field. However, in this case, there we no record as this entity was being moved first time in the Test.

Well to just fix this we thought of manually reactivating the key

However, that threw a new error that “Reactivate entity key is only supported for failed job.”

To fix this go to Settings à System Jobs à search for the failed system job and delete them

Now we will see the status as Failed

This time it will allow running the reactivation.

Finally,

Hope it helps..

Upgrade to new Xrm client API object model (v9) smoothly using XrmToolBox plugins

We are currently in process of upgrading Dynamics from version 8.2 to 9.0. One of the major change is updating our current JavaScript to the new Xrm Client API Object Model.

https://docs.microsoft.com/en-us/dynamics365/get-started/whats-new/customer-engagement/important-changes-coming#some-client-apis-are-deprecated

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/understand-clientapi-object-model

Below are the most useful tools à

Install the plugin, connect to your organization and click on Retrieve Jscript Webresources, it will list all the JScript Web resources found.

Click on Scan

It will list down all the issues found.

One common change that we need to do across all our JScript is to pass the ExecutionContext from Form as well as Fields (and Ribbon) events. Script Finder makes it extremely easy to find them out.

Click on Find Scripts usage and it will generate a report with all the details as shown below

Now we can follow the generated report and directly make the change to the form, field, and ribbon instead of searching for it manually.

Happy Upgrading !!

Dealing with OptionSet inside PowerBI in Dynamics 365 CE

Updated 8-Sep-2018 –> Please check the Power Query Builder tool of XrmToolBox. Thanks Scott Sewell for informing about this wonderful tool.

Suppose, we have created a Power BI Report which makes use of OptionSet field.

It is on incident entity and we have selected priority code and state code option set fields. The problem is that we only get the value for them, so to get the label either we can manually specify it or use the plugin Power BI Option Set Assistant. We’d see both the methods.

Let us take state code field first and specify label for them manually.

In the Query Editor, select New Query and specify following value and save it.

= #table({“value”,”label”},{{0,”In Progress”},{1,”Resolved”}})

Select the main query and click on Merge Queries

Select statecode and value to map them, specify left outer join for Join Kind as shown below

Select the new column added to the query and check the label.

We now have the label specified added as a new column to our query.

Here, for small set of values we can specify the label manually, however if there are too many values this might not be feasible and also if there are changes in OptionSet inside Dynamics 365 CE, we’d have to do it manually here, which makes it difficult to maintain.

So, let us use the wonderful PowerBI OptionSet Assistant plugin from our favorite XRMToolBox

Install the plugin

Click on Load Entities and select Case Entity.

Select Priority field and click on “Create records for selected option sets

Basically, it will create a new entity named gap_powerbioptionsetrefs entity, which will hold the records corresponding to each of the values of the optionset field selected.

Back in Power BI create a new query and select the gap_powerbioptionsetfrefs entity and save the query.

Now follow the same steps, select the main incidents query and perform merge queries operation as shown below

Expand the column to select the label field

Our final query à

Hope it helps..

Upgrading from Dynamics CRM 2016 On-Premise to Dynamics 365

Make sure the Solution is compatible to Dynamics 365 (8.2), for this check the Version Compatibility

https://docs.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg328109%28v%3dcrm.8%29#version-compatibility

Upgrade the existing CRM 2016 On-Premise Server to CRM 2016 (8.1) for its solution to be compatible with Dynamics 365 Online using cumulative updates.

https://support.microsoft.com/en-gb/help/3142345/microsoft-dynamics-365-onpremise-cumulative-updates

If upgrading from previous version i.e. prior to CRM 2016, use “Migrate by using a new instance of Microsoft SQL Server” approach

https://technet.microsoft.com/en-us/library/hh699669.aspx

https://technet.microsoft.com/en-us/library/hh699747.aspx

Once updated to compatible CRM 2016 On Premise (8.1), go to settings à customizations and export the existing solutions or create a new solution, add all the required solution components to it as unmanaged which will be imported to the new Dynamics 365 online environment.

Create a new Dynamics 365 Online Environment and synchronize it with your existing Active Directory

https://blogs.msdn.microsoft.com/crm/2013/07/18/how-to-synchronize-crm-online-with-your-active-directory/

With solution ready and imported to new Dynamics 365 Online, next step is migration of data.

Consider using a data migration tool like KingswaySoft.

Check out their Migration Starter Pack.

https://www.kingswaysoft.com/blog/2016/09/16/Announcing-Migration-Starter-Pack-for-CRM-Online-and-CRM-On-Premise

or Scribe

https://www.scribesoft.com/solutions/dynamics-365/

Use following tools to update the JavaScript to Version 9.0 of XrmToolBox.

https://www.xrmtoolbox.com/plugins/XrmToolBox.Dynamics365V9JavascriptValidator/

  • Script Finder (to update the form and fields for passing the executionContext)

https://www.xrmtoolbox.com/plugins/MsCrmTools.ScriptsFinder/

https://community.dynamics.com/crm/b/develop1/archive/2017/11/11/executioncontext-hits-the-big-time

Update JavaScript to use Web API.

https://github.com/jlattimer/CRMRESTBuilder

SQL Based report, if possible, needs to be converted to use Fetch XML. Use the following tool to speed up the process.

http://www.sql2fetchxml.com/

If the reports are too complex, plan to use Power BI reports.

https://technet.microsoft.com/en-us/library/dn708055.aspx

Plugin and Custom workflow needs to be updated to run in an isolated environment i.e. sandbox along with references to the latest SDK assemblies.

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/plugin-isolation-trusts-statistics#web-access

https://www.nuget.org/packages/Microsoft.CrmSdk.CoreAssemblies/

If the existing On-Premise is integrated to other applications, make sure they can still talk with new Dynamics 365 Online.

Recurring jobs if needed, can be deployed to Azure as Azure WebJobs.

https://docs.microsoft.com/en-us/azure/app-service/websites-dotnet-deploy-webjobs

Use Hybrid Connection to talk with On-Prem resources.

https://docs.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections

These were some of the points I could quickly think of. Please share your thoughts and experiences in comments. I’d update this list.

Do check out :

Microsoft Dynamics CRM (on-premises) to Microsoft Dynamics
Online Migration Guide

https://download.microsoft.com/download/6/D/6/6D67BDEA-1D67-42B4-A52A-CF13CD547CB5/OPtoCRMOnlineMigration.pdf

Hope it helps..

LookupRecordNotAvailable error while using Configuration Migration Tool in Dynamics 365 Customer Engagement

While trying to migrate the record using the Configuration Migration Tool, we were getting error like below in the log

ImportEntity – Result: True – Entity: transactioncurrency – Adding transactioncurrency to the reprocess List as field createdonbehalfby with value 05d52058-eb35-41e8-8af7-dfb7120c4599 – LookupEntity systemuser and Record Id 2655712b-e13b-e711-80fb-5065f38b5691 (SYSTEM) – (action:Update) failed validation for reason code: LookupRecordNotAvailable

As we do not want to migrate the createdonbehalfby field, the easiest fix for this is to remove the field from the schema.

Ideally instead of adding the entire Entity, we should select only those fields whose value we want to migrate in the Schema file.

Hope it helps..

Power BI with Dynamics 365 CE – Dynamics 365 Content Pack

In previous posts we covered

Creating a Power BI Report using Dynamics 365 Online Service.

Publishing it and Showing it inside Dynamics 365 and scheduling its Refresh.

Apart from creating our own Power BI Report another way of quickly be up and running is to use the Content Packs provided by Third Party Service, for e.g. here we will be using Sales Analytics for Dynamics 365 content pack provided by Microsoft.

Login to the Power BI service, click on Get Data, select Services.

Select Apps and choose the Sales Analytics for Dynamics 365 from the AppSource.

If we search for Dynamics 365, we can see around 15 Apps provided by Microsoft.

Back into our Sales Analytics for Dynamics 365 App, when we click on Get in now we are presented with the option where we need to Specify the URL of our Dynamics CRM Online Service and Fiscal Year End Month Number for that organization.

In the next screen, we need to select OAuth2 as the authentication method and followed by signing in.

This installs the app which would be available in the Apps section.

Clicking on the installed Sales Analytics App opens the Dashboard

Clicking on Ask a question about your data inside Dashboard allows us to analyze the data by allowing us to choose the criteria

Here we have filtered the accounts by created on by month along with the owner

Also, we can see around 10 different reports created inside that app.

  • Sales Performance
  • Sales Leaderboard
  • Win/Loss Analysis
  • Top Won/Lost Details
  • Sales Pipeline
  • Sales Pipeline Dashboard
  • Sales Activity
  • Open Activities
  • Lead Analysis
  • Account Analysis

Similarly, we can create our own Content Packs to be shared with either specific group or with the entire organization.

Click on settings gear inside Power BI Service and select Create Content Pack

Here we are creating a content pack choosing the Dashboard, Reports and the Dataset that we created earlier in the previous posts.

Once published, the user 2 can click on Get Data and search for and can see the content pack.

Clicking on Connect adds the Dashboard, Report, and the corresponding Dataset to the My Workspace of the user. Only the user who had created the content pack can edit the artifacts that are part of Content Pack, however, the other user of the organization can save a copy of it and can work on it.

More on it

https://docs.microsoft.com/en-us/power-bi/service-organizational-content-pack-manage-update-delete

Hope it helps..

Power BI with Dynamics 365 CE – Refreshing the Dataset

In the previous post, we used Dynamics 365 Dashboard and Power BI Tile to show Power BI Dashboard and report inside Dynamics 365.

https://nishantrana.me/2018/08/20/power-bi-with-dynamics-365-ce-showing-power-bi-dashboard-tile-inside-dynamics-365-ce/

Now as a next step, we want to make sure that the users are looking at the latest data possible inside the Dashboard\Reports.

In case of Online Services like Dynamics 365 (Online), we have the option to manually Refresh the data.

To see it in action, let us create a lead record in Dynamics 365.

This is how our Dashboard looks like for now à

Now back in Power BI Service right, click on ellipsis for the Dataset and select Refresh Now.

We can see the newly created lead in our Power BI Report inside Power BI Service and Dynamics 365 CE.

The other option we have is to Schedule the refresh.

Navigate to the Dataset and select Schedule Refresh

We can select the Refresh Frequency as Daily or Weekly.

And we can set it to refresh up to 8 times per day as shown below.

With Power BI Pro License, we can complete the scheduled refresh 8 times a day whereas the Power BI Premium allows the refresh up to 48 times per day.

https://powerbi.microsoft.com/en-us/power-bi-premium/

Some helpful links

https://docs.microsoft.com/en-us/power-bi/refresh-scheduled-refresh

https://www.powerobjects.com/2018/01/11/power-bi-data-refresh-performance/

https://crmtipoftheday.com/category/power-bi/

Hope it helps..

Power BI with Dynamics 365 CE – Showing Power BI Dashboard / Tile inside Dynamics 365 CE

In the previous post, we created a simple report and published it to the web and used IFrame to display them in Dynamics 365 CE.

https://nishantrana.me/2018/08/20/power-bi-with-dynamics-365-ce-publishing-power-bi-report-to-the-web/

Now let us create a Power BI
Dashboard using that report, which we will then display inside Dynamics 365 CE as a proper native Dynamics 365 CE’s Power BI Dashboard.

Let us take the fastest route to create them, back in Power BI Service, hover over the chart in the report and select the option “Pin Visual

We will be presented with the option of creating a new dashboard or add to an existing one.

Here we have created a dashboard named “My Dynamics 365 Dashboard

Similarly, we can pin or add the other chart in our Report to this Dashboard.

Apart from pinning the chart from the report into the Dashboard we also have the option to configure the Phone View for the Dashboard by clicking on Create phone view.

Phone view lets us specify how the report should look within the mobile device by dragging the reports in the designer surface.

This is how our Dashboard looks now inside Power BI service.

Now suppose we want to share this Dashboard with other users and also want to display this Dashboard inside Dynamics 365 CE, for this, we need to Share them.

However, as soon as we click on Share button we would get the below message.

To share and collaborate we need to have Power BI Pro license.

With Power BI Pro license, we can share it the with other users in the organization having the Power BI Pro License and also use the Reports \ Dashboard within Dynamics 365 CE.

Click on Try Pro for free and Start Trial which assigns the user 60-day free trial

After successfully assigning the license click on Share and select the user to grant access to.

Here we have selected user2 here.

If you remember from the previous posts, the Dashboards and Reports reside inside My Workspace.

Alternatively, we create a workspace and add the members (user 2 in our case) to it with edit access.

Note: We can publish the report that we created earlier from Power BI Desktop to this new app workspace.

While creating the new workspace we can also define the Access to it for the other users.

Here we have already assigned Dynamics 365 CE Enterprise Edition Plan and Power BI free license to User 2.

User 2 can see the report in Shared with me section inside Power BI service.

As we had mentioned earlier, when the user2 tries to open the report he is prompted with the message that Power BI Pro license is required to see the reports shared,

Click on Try Pro for free to start the trial for the User 2.

After successful activation user will be able to see the report inside Power BI Service. Here we are done with Sharing and assigning license part, now let us display it within our Dynamics 365.

Before we can do so we need to enable Power BI Visualization Embedding inside Dynamics 365 CE.

Navigate to Settings à Administration à System Settings and enable Power BI integration.

Open CRM, and select New to create a new Personal Dashboard and select Power BI Dashboard

It will load the all the Workspaces and the corresponding Dashboard inside it to which the user has access to.

Enable for mobile will make the dashboard available on Dynamics 365 for Tablets and Phones.

Select the Dashboard and click Save.

The Dashboard inside Dynamics 365 à

Similarly, User 2 can create a personal Power BI Dashboard inside Dynamics 365 CE and select the dashboard that is shared.

Apart from adding the Dashboard, we can also add the Power BI Tile to the Dashboard.

Create a new Dynamics 365 Dashboard, click on add a Power BI tile option to add the tile as shown below.

The CRM Dashboard showing Power BI tile à

This completes the sharing and displaying the power bi dashboard and reports part inside Dynamics 365 CE, next we will cover how the data can be refreshed so that users are looking at the most up to date data possible.

Hope it helps..