Sticky

This blog has moved to www.dreamingincrm.com. Please update your feed Url. Thank you.

27 January 2015

GetAttributeValue and null DateTime

Previously, I used to access the value of a property like entity["attributename"] and cast the result into the appropriate type. The preceding line to this, would always be a check to see if the property exists, as it can cause a KeyNotFoundException, without this check. GetAttributeValue is how I access attribute values these days. These are some influential posts that made me change my behaviour.

David Berry -> http://crmentropy.blogspot.com.au/2013/08/entitygetattributevalue-explained.html
Guido Preite -> http://www.crmanswers.net/2014/09/getattributevalue-activityparty.html

While this does prevent KeyNotFoundException, it is important to understand the behaviour of GetAttributeValue, w.r.t DateTime. When GetAttributeValue is invoked to retrieve a DateTime attribute, and the value of the attribute is null, it returns a DateTime.MinValue, which is 01/01/0001.

In a scenario where a retrieved value is used to update another record, you'll have to check if this is DateTime.MinValue before updating, or it will cause an exception like the one below.

The exception thrown is "DateTime is less than minumum[sic] value supported by CrmDateTime. Actual value: 01/01/0001 11:00:00, Minimum value supported: 01/01/1900 00:00:00". To prevent this exception, I check if the retrieved DateTime value == DateTime.MinValue, and if so, choose not to update the target property, or set it as null, depending on the requirement. It is also a realisation for me, that CrmDateTime still lives on, somewhere in the Sdk assemblies.

EDIT (29/01/15): Following David's tip from the comment below, the better approach is to use nullable types with GetAttributeValue, so I should be using DateTime? instead of DateTime.

21 January 2015

Quick Tip: Don't use underscore in Action argument name

There seems to be a bug in the process editor, when you use it to define an action that contains an argument with an underscore in the name. Once you save this action, which meets this criteria, you will not be able to open the action definition again through the process editor. You just get a generic error dialog when you try to open the action.


My action definition itself is minimal. It doesn't contain anything other than the argument (screenshot after following recovery steps).


The underlying error that is found in the url is:

Error code: 0x80040216
Error description: Invalid variable name format

In order to recover from the error follow these steps

1.) Create a new solution and add the action to this solution
2.) Export the solution as an unmanaged solution
3.) Unzip the solution to a location
4.) In the workflow folder, you will find a xaml file. Open this using any text editor
5.) Find and replace the parameter name which has the underscore, to be without underscore
6.) Rezip and import

The action can be opened again after following these steps. I tested this issue and can confirm that it  happens in CRM 2013 6.1.1 and CRM Online.

19 January 2015

Business Rules by Form Type

Xrm.Page.ui.getFormType() is used in form script to find out what type of form is currently loaded. Sometimes, we want to apply a certain logic, depending on whether it is a create form or update form. e.g I want to disable some fields, if it is an update form. If we are using Business Rules, it is not very obvious (at least to me) on how this can be achieved. The answer is quite simple: just check the value of any of these system fields (created, createdon, modifiedby, modifiedon). Here is a business rule that will trigger only for update form.

Here is the rule for create form.


Here is the result after the rule has run on an existing record


The important thing to remember is: The system field you are checking (in this case createdon), has to be on the form. Otherwise the rule will not fire.

Credits to @BernadoNH for this info.

15 January 2015

An alternative approach to loading form scripts in Dynamics CRM

With each browser update, full ES6 support has been getting closer and closer. But this is still sometime away, and transpilers like traceur or 6to5 can help bridge the gap in some areas. One ES6 functionality I am very much interested in, is module. As of today, no browser natively supports this, and I would have to transpile my code to get this functionality.

So, I once again would like to use my favorite module loader, requirejs for doing this. The last time I did this (http://nycrmdev.blogspot.com.au/2014/04/using-requirejs-in-crm2013.html) I had to use some unsupported tricks to get this working in CRM2013. This time, my approach is to do away with CRM script loading mechanism altogether and use requirejs to load the form scripts.

Here is how my resources are organised.

 Events.html is the HTML webresource that will be embedded in the entity form. Here is the code for events.html;

<!DOCTYPE html>
<html>
<head>
  <title>Form Events</title>
  <!-- data-main attribute tells require.js to load
  scripts/main.js after require.js loads. -->
  <script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
  <ul id="events">
  </ul>
</body>
</html>

main.js is the entry point into the form processing code.

(function () {
  var defaultConfig = {
    shim: {
      'lodash': {
        exports: '_'
      }
    },
    deps: ['lodash', 'common', 'ryr_eventform'],
    callback: function() {
      console.log('callback before requirejs has been loaded');
    },
    onError: function(err) {
      console.log(err.requireType);
      if (err.requireType === 'timeout') {
        console.log('modules: ' + err.requireModules);
      }
      throw err;
    }
  };
  defaultConfig.callback = function() {
    console.log('callback after requirejs has been loaded');
  };
  requirejs.config(defaultConfig);
})(); 

I want the scripts to load in the following order: lodash->common->ryr_eventform. If you use the form area to reference your script, you really don't have any control over the sequence, as they are loaded async and may not be loaded in the same order you added them in the form (http://www.develop1.net/public/post/Asynchronous-loading-of-JavaScript-Web-Resources-after-U12POLARIS.aspx). Until Microsoft changes this functionality, there are two ways to overcome this issue.

1.) Bundle all your scripts in the order of their dependencies
2.) Check if the dependency has loaded. (See the waitForScript technique in the develop1 link)

I am loading the scripts using requirejs, but the triggering page is an external web resource. This way I can keep this a supported method.

This is common.js, which is required by ryr_eventform.js.

define(['lodash'], function (_) {
    var common = {
      log: function(message) {
        var e = document.createElement("li");
        e.innerHTML = new Date().toString().split(' ')
        .filter(function(d,i){ return i>0 && i<=4})
        .join(' ') +': '+ message;
        document.getElementById('events').appendChild(e);
      }
    };
    common.log('Loading common_script.js');
    //can use lodash, as it is specified as a dependency and should have been loaded
    common.log('Lodash Version: '+_.VERSION);
    return common;
});

This is ryr_eventform.js.

define(['common', 'lodash'], function (common,_) {
 common.log('Loading ryr_eventform.js');
 //can use lodash, as it is specified as a dependency and should have been loaded
 common.log('Lodash Version: '+_.VERSION);
 var Xrm = parent.Xrm;

 var form = {
  onSave: function(context) {
   common.log('Form Save Event');
  },
  onLoad: function() {
   common.log('Form Load Event');
   if(Xrm){
    Xrm.Page.data.entity.addOnSave(this.onSave);
    Xrm.Page.getAttribute('ryr_name').addOnChange(function(context) {
     common.log('Name Change Event: ' + context.getEventSource().getValue());
    });
    }
   else{
    common.log('Web Resource has not been embedded inside a CRM form');
   }
  }
 };

 form.onLoad();
 return form;
});

Here is how the form looks in the design mode.

I have not added any scripts to the form.



Since requirejs will start loading the scripts, you don't need to worry about this.

Lets start looking at some form events now and how the script behaves.

Form Load

Name field changed
 As you, can see a script can do exactly the same things, even though it has not been been loaded through the CRM form script loading mechanism. These are are two key things that help to achieve this.

1.) The webresource folder structure
2.) Referencing Xrm object from webresource using parent.Xrm

The impetus for this post is this: I have got "The form has changed. Would you like to save your changes" dialog more than a few times and I have no idea what is the reason for this dialog. If the change has made by a script, I have no way of knowing what the change was, and which script triggered this, unless I have added some console.log message the scripts. This is not possible if I can't change the script. You could live edit the script using the DevTools, but I don't want to do that.

The disadvantages of this techique, that I can see are
  1. html webresource has to be added to the form
  2. Tablet support
If CRM Client API exposes some sort of event listening capability, this would help the devs to listen to certain events like form save, form load, field onchange from the devtools console and figure out what is happening with the form, without using the debugger step through. 

CRM itself, uses custom events and listeners internally, to figure out what scripts to execute for a particular event. But this functionality is not exposed externally for everyone to use. Until this is made available down the line, into some sort of Client API - Dev Mode, I can use this to control the form script loading process and audit of form events.

18 December 2014

Using Advanced Find FetchXml capability in custom forms


I prefer FetchXml compared to QueryExpression or LINQ when writing custom code. Back during the CRM3/4 days there was Stunnware. CRM2011 introduced capability to export the FetchXml directly from the Advanced Find. In CRM 2013/2015 you have four tools, to write and export the FetchXml.
  1. FetchXml Tester (comes with XRMToolBox)
  2. FetchXml Builder
  3. Fetch Tester 3000
  4. CRM DevTools (Chrome only)
The fetchxml I build, is used mostly in a plugin or workflow assembly, but there are times when I want to store the fetchxml in custom entity, and use it a part of scheduled workflow logic. This also needs to be flexible, as I may need to change the fetchxml, without needing to rebuild any assemblies. The obvious and most straight forward way to do this would be to have a textarea field in the form, and copy-paste the fetchxml that was generated from one of this tools, or from the advanced find.

What if there is an better, albeit unsupported way? You can embed the advanced find on the entity form that needs to store the fetchxml, and get the fetchxml from the advanced find, when the user saves the record.

Step 1:
You need two controls: a text area to store the fetchxml and an IFrame that will display the advanced find. The target of the IFrame is "about: blank". We will set the correct URL using Javascript. I have added the IFrame to a seperate tab, and the default state of this tab is collapsed.



Step 2:
Add the script below as a Javascript webresource and hookup the onSave and onLoad functions to the form save and form load respectively. The id of my IFrame is IFrame_Advanced and the fetchxml is stored in textarea ryr_fetchxml.

var RYR = window.RYR || {};

RYR.onLoad = function(){
  Xrm.Page.getControl('IFRAME_AdvancedFind').setSrc(Xrm.Page.context.getClientUrl()+'/advancedfind/advfind.aspx?pagemode=iframe&navbar=off&cmdbar=false');
};

RYR.onSave = function(){
 var advancedFindFrame = document.getElementById('IFRAME_AdvancedFind').contentWindow;
 advancedFindFrame.ExecuteQuery();
 advancedFindFrame.ShowQuery(); 
 Xrm.Page.getAttribute('ryr_fetchxml').setValue(advancedFindFrame.document.getElementById('FetchXml').value);
};

window.RYR = RYR;

Here is how it looks.


The trick is to call ShowQuery straight after ExecuteQuery, so that div with id FetchXml contains the correct value. If we don't call the ExecuteQuery, the value of FetchXml won't be updated when the advanced find is modified by the user.

Once again, this technique is unsupported, so use it at your own risk. I have tested this in Firefox 34 and CRM 2013 6.1.0.581.

UPDATE (24/12/14): There was an issue with the initial script, as it was only working if the organisation was a default one. The initial script split the screen horizontally, if the IFrame url was correctly set using getClientUrl. The updated script fixes this issue. Based on my testing, this is working in Firefox 34, Chrome 39.0.2171.95 and IE 11(in IE9 mode only). One more thing to note -> If the tab with the Advanced Find IFrame doesn't started out collapsed, the Ribbon Interface of the Advanced Find shows up on the form.

8 December 2014

Quicktip: Install .net 4.5.2 before developing for CRM2015

Before you start developing console application, workflow or plugin for CRM2015 the first step is to install .net 4.5.2 as this is required by CRM2015. I was working on a simple console application using CRM2015 assemblies and I encountered a weird error. I ran "Install-Package Microsoft.CrmSdk.XrmTooling.CoreAssembly" from the PM console without any issue. But when you try to build the application I got these compilation errors.


The root cause of these errors is because the project is not targetting .net 4.5.2. Download .net 4.5.2 from http://www.microsoft.com/en-us/download/details.aspx?id=42637 and update the project target framework to .net 4.5.2. This time the build process succeeds. I was quite surprised that nuget did not prevent me from using the package in the project, even though I didn't have a the prerequisite framework version.

7 December 2014

Calculated Fields in CRM 2015

Calculated fields are new to CRM 2015. Business Rules now also have a new Entity Level scope option. When it comes to simple decimal operations you can use either Business Rules at Entity Level scope or calculated fields. Obviously calculated fields, are much more powerful than business rules. There is one issue I experienced with business rules at entity level. The division operator currently does not seem to work properly.

This the business rule to perform the division.


When you save the record an error is displayed.


This is the actual error

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Expression operator not supported for specified type.Detail: 
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
  <ErrorCode>-2147220891</ErrorCode>
  <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
    <KeyValuePairOfstringanyType>
      <d2p1:key>OperationStatus</d2p1:key>
      <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">0</d2p1:value>
    </KeyValuePairOfstringanyType>
    <KeyValuePairOfstringanyType>
      <d2p1:key>SubErrorCode</d2p1:key>
      <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">-2146233088</d2p1:value>
    </KeyValuePairOfstringanyType>
  </ErrorDetails>
  <Message>Expression operator not supported for specified type.</Message>
  <Timestamp>2014-12-06T22:54:07.9005933Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>

[Microsoft.Crm.ObjectModel: Microsoft.Crm.ObjectModel.SyncWorkflowExecutionPlugin]
[c3877360-9a7d-e411-80cf-e83935c2f340: ]
Starting sync workflow 'Decimal Formula', Id: bc877360-9a7d-e411-80cf-e83935c2f340
Entering ConditionStep1_step: 
Sync workflow 'Decimal Formula' terminated with error 'Expression operator not supported for specified type.'

</TraceText>
</OrganizationServiceFault>

The calculated field that performs the division works without any issue.

Interesting behaviours that I encountered below.

Scenario 1: Calculated field to divide two integers and the result of the operation is float e.g. : 5 / 2

Result: The result is rounded up to the closest int.


  
Scenario 2: Calculated field - Divide by zero

Result: No divide by zero exception. The result is blank.



Scenario 3: Calculated field of type text, with calculation using decimal fields.

Result: No error. Result of the operation is can be assigned to the string field.



Conclusion: If it can be done using calculated fields, do it that way, instead of Entity scope business rules, as calculated fields offer much more flexibility and functionality.