Improve fetch xml performance by using latematerialize option.

If you have been working on dynamics projects, I bet fetch xml is your best friend as it’s really an easiest way to query and execute in order to get required results. Along with that, constructing it in advanced find is super easy too.

Don’t forget about amazing XRM toolboxes which helps you creating even complex fetch xml queries.

It all sounds fun and easy till your fetch XML becomes really heavy with so many joins or you have a requirement where you need to make many joins.

A Quick tip!

You can have a maximum of 10 joins in fetch xml for dynamics CE.

You will notice that retrieval from dynamics is getting slower and slower as fetch xml becomes complicated. I have faced something similar multiple times. What I did?

well, there are multiple options one of which I want to cover today as using this option, there are no extra efforts.

latematerialize to the rescue!

All you got to do is add latematerialize=”true” in fetch xml properties like below and test is to see the magic.

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" latematerialize="true">
  <entity name="account">
    <attribute name="emailaddress1" />
    <attribute name="statecode" />
    <attribute name="statuscode" />
    <attribute name="ownerid" />
    <attribute name="accountnumber" />
    <link-entity name="contact" from="contactid" to="primarycontactid">
      <attribute name="birthdate" />
      <attribute name="createdon" />
      <attribute name="contactid" />
      <attribute name="parentcustomerid" />
    </link-entity>
  </entity>
</fetch>

There are many internal technicalities as to how it works but to summarize, It breaks the data into multiple smaller segments which makes the retrieval of data faster unlike normal fetch xml which tries to query every at once.

if you are looking for official documentation on the same, please go here: Improve FetchXML request performance – Power Apps | Microsoft Docs

Advertisement

When To Use Which Microsoft Dynamics CRM Web Service

thiking kid

Meet Jerry, he is wondering about dynamics crm services, In this blog I am helping him to understand when he should use which dynamics CRM web service.

Let’s first understand how many services dynamics crm offers post which will discuss which service to be used when:

  1. Web API
  2. Organization Service
  3. Organization Data Service
  4. Discovery Service
  5. Deployment Service

Web API

WebAPI is fairly new for dynamics CRM and i see many developers havent touched upon it. You should be using WebAPI Service while doing Client side development(preferably) such as Javascript, HTML etc. At this point its not easy to use WebAPI on server side but i am sure it will be possible in coming updates. Web API uses ODATA (Open data protocol). It also doesnt need any dynamics CRM related libraries or assemblies. You perform CRUD operation using XmlHttpRequests.  

Organization service

Organization service is basically a SOAP endpoint of dynamics crm and have been available since dynamics crm version 2011.  This Service has to be used with .Net Framework and for Business logic that runs in plug-ins or workflow assemblies on the server expect to use the Organization service.( So nothing client side). To work with Organization you have to use microsoft dynamics crm SDK i,e provided libabries and assemblies to interact with dynamics crm.

Organization Data service

It is also known as Odata service for dynamics crm which is Infact nothing but a “REST” Endpoint. You can utilise Odata endpoint in C# code( a server side code as well) but it is widely used for for client side scripting using javascript. However this has been deprecated with the release of dynamics crm 365 which means it is no longer supported. and completely replace with WebAPI.

 

Discovery web services

As the name suggest, this service should be used when you have mutiple CRM instances of dynamics crm in single deployment. You would use this service in your plugins ( the server side code) to get the current instance obtain the context.

 

Deployment web service

This service is barely used by developer as UI options are available. Such as Deployment manager etc. Use this service if you have create , delete or edit a dynamics crm organization/instance. Again its all server side.

 

I hope this clears your doubt as to when you would use which service and with what programming language.

Cheers!

 

 

Create Text log file – Simplest way possible

We all need to log errors, information, warnings when writing your console application.

while there are several third party tools/methods available which you use in your solution such as Nlog, Log4net… etc. I would still prefer to create my custom code to generate the log file and capture all details as those tools might work on some machine and on some wont also depends badly on the permissions on the system.

below is simple code that i use :

using System;
using System.IO;

namespace YourNameSpace
{
 public static class ErrorLog
 {

public static void Logger(string ErrorCode, string ErrorMsg)
 {
 try
 {
 string path = Directory.GetCurrentDirectory();
 path = path + "\\Logs\\";

// check if directory exists
 if (!Directory.Exists(path))
 {
 Directory.CreateDirectory(path);
 }
 path = path + DateTime.Today.ToString("dd-MMM-yy") + ".log";
 // check if file exist
 if (!File.Exists(path))
 {
 File.Create(path).Dispose();
 }
 // log the error now
 using (StreamWriter writer = File.AppendText(path))
 {
 string error = "\n" + DateTime.Now.ToString() + ":" + ErrorCode + ":" + ErrorMsg;
 writer.WriteLine(error);
 writer.Flush();
 writer.Close();
 }

}
 catch (Exception ex)
 {
 throw new Exception(ex.Message);
 }
 }
 }
}

add this file to your code and later you can use it in your solution anywhere like below :

 ErrorLog.Logger("Info","yourtexthere");

kindly note that this will generate the logs file on your directory where the code is running in that case in the “BIN” folder. You can tweak the code to put it somewhere else if you need.

logs

Hope this helps!

Cheers!

How to get value from a lookup or parent entity using Calculated field in Microsoft Dynamics CRM

Did you ever need to get values from other entity or from a lookup on current entity? What comes to your mind, bet it is javascript , plugin etc?

Well, lets pause the coding life for minute and do it using Calculated Fields which used simple UI like business rules.

In Scenario below , i am retrieving the Budget Allocated amount from source campaign on a lead record.

  1. Create a currency Calculated field on lead record :1Give the appropriator name , select data type as Currency or as per your need > Select Field type as Calculated and click on Edit. As soon as you click on edit, system will actually create this field for you.
  2. After clicking on Edit button , you will be presented with the UI where you have put in  your logic:2

    As a first step i am checking if Budget Allocated field on campaign actually has data.To do this you have select Source campaign in the Entity and the corresponding field.

  3. Once this condition is set click on the Action :3

    In the editor start the typing the name of source campaign lookup or you can scroll though all fields/lookups available on the lead entity. Here i have select campaignid

  4. Once selected the campaignid , enter a dot(.) – post which you will start getting fields from the campaign:4

    Here i am selecting the budgetcost(Allocated Budget)

  5. Finally it will look like below :5Save and close the editor and also the field property window.
  6. Put this calculated field on the form and publish customization.
  7. Open a lead which has campaign associated to it:

    6campaign :

    7It is a very basic example i showed , i tried not to make it complex as it might become very confusing for a beginner.  You can do a lot manipulation with the data by using out of the box functions that are available for a calculated field or apply your custom logic.hope this helps!

    cheers!

RIP SDK – Dynamics CRM 365 v9

As per the recent communication from Microsoft, Microsoft Dynamics CRM SDK will not be available on Microsoft downloads. If you are working on Dynamics 365 v9, well you have to download every component which was available in the SDK individually.

Every tool will be available via NuGet Manager.

The name will be : Developer Guide not Dynamics CRM SDK.

For more information, visit the below blog :  https://blogs.msdn.microsoft.com/crm/2017/11/01/whats-new-for-customer-engagement-developer-documentation-in-version-9-0

Here is the step by step information on how to download these tools using powershell :  https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/download-tools-nuget

 

i hope this helps.

Cheers!

 

How to set PartyList in Microsoft Dynamics CRM using Javascript

Let make it a smallest blog possible.

below code i have been using without any issue when it comes to setting a partylist or multi lookup in CRM. In the below code i am retrieving the contact id or the id of entity which is there in the regarding field & setting it on the “From” field.

function setCallFrom() 
{
 var lookup = new Array();
 lookup = Xrm.Page.getAttribute("regardingobjectid").getValue();
 if (lookup != null) {
 var name = lookup[0].name;
 var id = lookup[0].id;
 var entityType = lookup[0].entityType;
 if (entityType == "contact") {

var value = new Array();
 value[0] = new Object();
 value[0].id = id;
 value[0].name = name;
 value[0].entityType = "contact";

Xrm.Page.getAttribute("from").setValue(value);
 }

}
}

With slight modifications you can use the code on any other activity if you need to set partylist.

Call this function on Onload of the record or on onchange of the regarding field.

hope this helps!

Cheers!

Show entity form based on a field value in Microsoft Dynamics CRM

Having multiple forms for an entity is definitely amazing since you can control visibility of fields without having to write business rule or Javascript to hide hundreds of fields based on some value.

Now out of the box you can control CRM forms visibility/preference using security roles. However it is not you would always want to to do; sometimes you might have to control form preferences based on field value.

here is the sample code that i am using – on load of create/update/all forms i am retrieving a value from owner of that record – since on creation only owner gets filled up.  I have create a field “new_form” as a whole number on system user :

1

i have currently have it a value as “2”. lets see how i am going to retrieve this value in my code and set the correct form :

//do a webapi action to retrieve the form value from systemuser.

var formnewvalue = ' ';
function retrieveFromValue() {
 debugger;
 var userid = Xrm.Page.getAttribute("ownerid").getValue();
 var newid = userid[0].id.slice(1, -1);
 var req = new XMLHttpRequest();
 req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/systemusers(" + newid + ")?$select=new_form", true);
 req.setRequestHeader("OData-MaxVersion", "4.0");
 req.setRequestHeader("OData-Version", "4.0");
 req.setRequestHeader("Accept", "application/json");
 req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
 req.onreadystatechange = function () {
 if (this.readyState === 4) {
 req.onreadystatechange = null;
 if (this.status === 200) {
 var result = JSON.parse(this.response);
 var new_form = result["new_form"];
 var new_form_formatted = result["new_form@OData.Community.Display.V1.FormattedValue"];
formnewvalue = new_form_formatted;

 showForm();

 } else {
 Xrm.Utility.alertDialog(this.statusText);
}
 }
 };
 req.send();
}
function showForm() {
 debugger;
var lblForm;
var relType = formnewvalue

switch (relType) {
case "1":
lblForm = "Portal Contact";
break;

case "2":
lblForm = "Profile Web Form";
break;

default:
lblForm = "Contact";

}
 //check if the current form is form need to be displayed based on the value
 if (Xrm.Page.ui.formSelector.getCurrentItem().getLabel() != lblForm) {
 var items = Xrm.Page.ui.formSelector.items.get();
 for (var i in items) {
 var item = items[i];
 var itemId = item.getId();
 var itemLabel = item.getLabel()
 if (itemLabel == lblForm) {
 //navigate to the form
 item.navigate();
 } 
 } 
 }
}

if you notice my switch statement you will see i m assigning the name of the forms to the values that i will be setting on the user profile.

Once it gets the form name – it than runs through all the forms for this entity untill it fins the correct form and then navigates to it.

i would say this script is majorly needed for first time or for a new system – since Internet Explorer or Chrome keep the form preference , so once our code the job and opened the required form -next time even if we remove the script -it will opening that form.

Another good is – this script prevents user to switch to other form as whenever  a user try to switch the form – on load event triggers and again check the value from owner id and change it back to the required one.

so since i have assigned value “2” to my user i should see “Profile Web Form” , lets see if this works :

2.jpg

woo , it did work.

point to note is you will have to attach this script to all the forms in the entity and call the function on onload for all forms.

hope this helps!

cheers!

Calculation Using Business Rules in Microsoft Dynamics CRM

Hi Guys,

We all love business rules & i am a big fan of them since they save alot of your time developing javascript for small actions that you need perform for e.g from making a field mandatory to setting fields value or showing error message.

Well , fortunately business rules can help if you need to perform some simple calculation on a form based on field values too. Lets get into action.

I have thought of a silly scenario where if i have estimated closed date on opportunity – i would like to set a date of 10 days before the estimated closed on a custom date field that i have created. Based on that i can then perform some other action using this new value either with JavaScript or business itself. This is dynamics crm 365 trial that i am using but its pretty much similar in 2016 or 2015.

So lets create a business role.

  1. Add a new condition to check if Est. Closed date contains data AND the new field(date difference) doesn’t not contains data.
    please note that if we don’t check the second condition the business rule will run every time and set the value to date difference on every on load even if date difference has been set last time :1
  2. Now once we are done with condition , lets add the action to it “set field value”. and from right side select the field = “date difference” , Type = “Formula”, other field = “Est Closed Date” , Operator = “-“, Type = “Value” , Days = “10”. Take a look at reference below:
    2
    3
  3.  now lets apply , save , Activate the business rule.
  4. Lets open a record a with estimated closed date and see it in action 🙂
    4
  5. the date difference field has been set to 10 days before the est close date which is 24-02-2017.
    5.PNG

There you go , it was simple example but i am sure you can perform some more complex calculation and not on just date fields but on currency and other fields.

Hope this helps!

Cheers!

Learn Microsoft Dynamics CRM – Basics, Customization & Configuration

aads-education-offers-microsoft-dynamics-crm-training-2-638

In office, while i am blogging or in dynamics community ; i always get this question that how a fresher can start learning CRM. Well let me tell you learning CRM is very easy since it is a Microsoft technology in which we have been living & using from our outlook to windows.

Well on internet ; information is pretty much distributed and in bits & pieces but i have collected the below information in sequence on how you  can you start from zero and go till 100 🙂

  1. First things first you should know what is CRM , well according to microsoft definition is :
             crm definition.PNG

    “CRM solutions streamline processes and increase profitability in your sales, marketing, and service divisions. A strong CRM solution is a multifaceted platform where everything crucial to developing, improving, and retaining your customer relationships is stored. Without the support of an integrated CRM solution, you may miss growth opportunities and lose revenue because you’re not maximizing your business relationships.”

  2. Next i would suggest you to see above everything in action :  https://www.chalkstreet.com/microsoft-dynamics-crm-tutorial    ,  https://mva.microsoft.com/en-us/training-courses/introduction-to-microsoft-dynamics-365-17593?l=J6OdOYtqD_906312570
  3. Once you have done this – i think you will be pretty much comfortable having your own CRM environment to get your hands dirty in, therefore go ahead and get your trial :https://trials.dynamics.com/
  4. Time to know how CRM can be available to you(to be technical “deployment options available in CRM”) :  https://www.powerobjects.com/2015/10/21/upgrading-crm-crm-online-vs-on-premises-finding-the-best-fit-for-your-organization/
  5. Once you understood all above, my suggestion for you is to now understand the core concepts which makes the whole CRM :

https://www.tutorialspoint.com/microsoft_crm/microsoft_crm_overview.htm

In this tutorial you will learn about what are the core components of  CRM like Entities , Fields, Forms, Business process flows etc. This blog also pretty much explains how you can customize the crm.

6. Now go though this blog and do same in your trial version :

https://crmbook.powerobjects.com/system-administration/customization/

i will talk about customizing, fields, forms , entities , charts, dashboards,solutions etc.

7. Security model – Now this is a major topic which you must understand very well without which it will be very difficult for you to master dynamics crm else you will be missing out on very small/minor things during your career

https://www.youtube.com/watch?v=_vfp3C11a3Mhttps://www.youtube.com/watch?v=An-VgsHEp9A

8. Now , one of the main features of crm is “Processes” , processes are the main component in CRM which helps you to perform actions based on your needs :

a. business rules :  http://www.inogic.com/blog/2016/12/business-rules-dynamics-365/

b. Workflows :  https://crmbook.powerobjects.com/system-administration/processes/workflows/

c.Plugins :  https://crmbook.powerobjects.com/extending-crm/plug-in-development-and-workflow-extensions/plug-ins/developing-a-plug-in/

9.Apart from it most of the stuff you would do through JavaScript which you coudnt  using business rule, mainly javascript is used to perform complex logics else i always recommend you to use business rules  :  https://www.youtube.com/watch?v=wxMB-cIQPUw

 

if you go through all of the above carefully , you will be in a position to work on dynamics crm confidently.

Please leave your comment if i have missed out anything major or you have any question, need guidance on any of the topics above.

happy crm learning, cheers!

Lock all fields on a form using Javascript- Microsoft Dynamics CRM

Hi Guys,

We all get requirements to lock the whole form to stop people from editing the record.

There are some out of the box options available to achieve this :

  1. Create a business rule : you can easily create a business and use lock field feature however you will have to select all the field on the form one by one – for .e.g if you have 50 fields on the form, you will have to add action for all of them. Moreover another limitation is if a field is removed from the form – you business rule will stop working.
  2. We all know if record is status is set to inactive – form become uneditable but in this scenarios we want to keep the record but uneditable.

Therefore, we come down to our final easy solution to tackle all problems above, the Javascript. Have a look on the below code :

 function disableFormFields()

{

       Xrm.Page.ui.controls.forEach(function (control, index) {

           var controlType = control.getControlType();

           if (controlType != “iframe” && controlType != “webresource” && controlType != “subgrid”)

           {

               control.setDisabled(true);

           }

       });

}

above code takes the control of the form directly rather then of each field & locks all of them. Just call the function on Onload , I have used this on my form and it looks like below:

lockfield

 

Now you can definitely add your own logic into this code for .e.g you put a if condition to check some value based on which you want to lock all fields and another things if you need to leave some fields unlocked you can again you a if condition , check the value and use below

just add the below code to above code :

if (crmfield = abc)

{

Xrm.Page.ui.controls.get(“CrmFieldShcemaname1”).setDisabled(false);

Xrm.Page.ui.controls.get(“CrmFieldShcemaNam2”).setDisabled(false);

Xrm.Page.ui.controls.get(“CrmFieldShcemaNam2”).setDisabled(false);

}

 

hope this helps you!

cheers