Advertisements

“Cannot read property ‘<entity name>’ of null”–Error while executing a bound action from from a WebResource in Dynamics V9.0 using Xrm.WebApi.execute

This one drove me crazy and believe these kind of things pop-up the most when you don’t expect them at all. A simple training going on and I was demoing them the wonderful Xrm.WebApi methods. Then came the turn of using Xrm.WebApi.execute to execute a bound action or entity action.

Since I worked a lot recently on Xrm.WebApi methods, was pretty confident of doing and just took this one example out of a participant wish. So here goes the requirement.

  • There is a custom entity (let’s call it Test Entity) which has N:1 relation with account. So account is a lookup on the Test Entity form.
  • There is a ribbon button on the Test Entity form which when clicked would open up a webresource which would show all the contacts related to the account in the form of HTML table.

So simple isn’t it. In the days when we moved to PowerApps and Flows, this just seems a walk in the park.

So here I started from scratch and wrote the below code onload of the HTML webresource.

var actionRequest = {};
     var crmContext = Xrm.Utility.getGlobalContext();
     var qString = crmContext.getQueryStringParameters();


    var accountId = qString.Data.replace(“}”, “”).replace(“{” ,””);


    actionRequest.StringParam = “Web Api Test”;
     actionRequest.DecimalParam = 30.43;
     actionRequest.entity = { entityType: “account”, id: accountId };


    actionRequest.getMetadata = function () {
         return {
             boundParameter: “entity”,
             operationName: “new_EntityAction”,
             operationType: 0,
             parameterTypes: {
                 “StringParam”: {
                     structuralProperty: 1,
                     typeName: “Edm.String”
                 },


                “DecimalParam”: {
                     structuralProperty: 1,
                     typeName: “Edm.Decimal”
                 },


                “entity”: {
                     structuralProperty: 5,
                     typeName: “mscrm.account”
                 }
             }
         }
     };


    Xrm.WebApi.execute(actionRequest).
         then(function (data) {
             // parsing your results here.


        },
         function (error) {
             debugger;
             console.log(error.message);
         });

Before we look at the code above, let’s find out the action.

It’s a bound action for the account entity which has two input parameters – String Parameter & Decimal Parameter

image

Button is in place and then just as i click the button and HTML webresource pops out boom! An error flashing – Cannot read property ‘account’ of null. The same would work if the webresource is embedded within the CRM Form.

For readers who are curious to know how I opened the WebResource, here is the code below.

var webResourceName = “new_/pages/spa.html”;
     var windowOptions = { height: 600, width: 800 };


    var parentAccount = Xrm.Page.getAttribute(“new_parentaccount”).getValue();


    var parentAccountId = ”;
     if (parentAccount != null) {
         parentAccountId = parentAccount[0].id;
     }


    Xrm.Navigation.openWebResource(webResourceName, windowOptions, parentAccountId);

Such an embarrassment in front of a big audience. Somehow I made this understand and they took it pretty well. If you are thinking that whether I included ClientGlobalContext.js.aspx, yeah I did. And did all whatever it takes to make it work. But none worked.

Searched the heck out of google, no luck as well.

Was not in a mood to leave. I started debugging, went inside all the system files stepping through each lines of the thousands of lines of system code.

And finally the Eureka moment. It was failing at the call of Xrm.Utility.getEntitySetName.

But let’s understand why? Well CRM relies on two arrays window.ENTITY_SET_NAMES  OR window.top.ENTITY_SET_NAMES  to get the entity set name from the logical name and window.ENTITY_PRIMARY_KEYS or window.top.ENTITY_PRIMARY_KEYS  to get the primary key property name of the entity.

Because the webresource is opening as a pop-up, both the arrays are coming as null and hence the error.

So before calling Xrm.WebApi.execute i just wrote the following lines.

var entNames = {};

entNames[“account”] = “accounts”;

window.ENTITY_SET_NAMES = JSON.stringify(entNames);


var primaryKeys = {};

primaryKeys[“account”] = “accountid”;

window.ENTITY_PRIMARY_KEYS = JSON.stringify(primaryKeys).

And this time when I run, what a relief. The code just ran fine and finally I could see my debugger being hit in the success block.

But please bear in mind this is unsupported and is never suggested. This post is more to highlight why it does not work in this scenario. May it start’s working in a future release.

However hope it saves some time or now you are aware before hand it will not work for this scenario

Debajit Dutta

(Dynamics MVP)

For consultation/ corporate training visit www.xrmforyou.com or reach out to us at info@xrmforyou.com




Advertisements

DateTime Attribute Onchange event in Dynamics Portals

Chandana's CRM Blog

Today’s blog title sounds to be very easy but, there lies something interesting as well. Well continued to work with Dynamics Portals, starting up with entity form and entity form attributes. I have a requirement like to calculate the age on input of date field.

So I am just trying to trigger an onchange event of date field in Entity Form. DateTime Field in entity form is usually a DateTimePicker which is evident to us. My datetime attribute schema name is “new_datefield”. So i tried simply to trigger on change event like

$(‘#new_datefield’).bind(“change”, function() {  alert(“hello i am change event.”);});

Which doesn’t fire the change event. 😦 Simple but not working. After couple of observations over the datetime attribute. DateTime field on click or expand opens up a datetimepicker where actually I need to attach my event handler to it.

To add a custom event handler to datetimepicker if I…

View original post 94 more words

Multiple Control ID’s Error in Dynamics 365 Portals

Chandana's CRM Blog

Well I have started working as well as learning Dynamics 365 Portals. Seems like portals are quite interesting and bit tricky to play around. Lets move on to the scenario which I have faced.

My task is like to display a page in portal which contains account information. To achieve this I started creating a web page named “Account” which will use the entity form.

In Entity form I select account entity and account detail form to display the same on the portal. Now I am done with my changes and task as well. When I refreshed my portal to view the changes and account detail form, the portal does not show up. Indeed it throws up a weird error!!!!

Capture

I am dumbstruck, was not able to identify what actually went wrong. After some moment able to identify through error log which says like “Multiple Control ID’s…

View original post 54 more words

Show Lookup as Dropdown in Dynamics 365 Portals–Gotchas!

I have been working and providing training a lot recently on Dynamics 365 portals. And whenever I go over Metadata configuration of entity form the option – “Render Lookup as Dropdown” option excites the participants a lot.

Well, in this article I am not going to show how you can render a lookup as dropdown. Rather I would like to highlight what features you loose when you render your lookup as dropdown.

Gotcha 1 – No Values shown in DropDown

When you render your lookup as dropdown, the first thing you observe that the list is empty. Well, this may happen because there is a bit of change in this implementation. Right now the options will only show up is you enable entity permission for the entity which is shown as lookup.

For example – Primary Contact field on the account form. When you render your Primary Contact as dropdown in Portals, you need to have an entity permission for contact entity with Append privilege for the webrole the user is logged in with. The contacts will show up then.

 

Gotcha 1 – Lookup filtering not working.

Well this is something undesirable but as of the day I am writing this blog, related records filtering does not work for lookups rendered as dropdown.

 

Short article but should put you in good stead next time your customer asks for this option.

 

Debajit Dutta

(Dynamics MVP)

For consultation/ training visit www.xrmforyou.com or reach out to us at info@xrmforyou.com

{Step by Step Guide} Query Dynamics CRM Web API using Server to Server Authentication with Application User

I have wrote quite a few articles over the last one year to query Dynamics Web API using ADAL from client side and as well as server side. However lately I am receiving loads of queries on how to Authenticate with web-API without using any user credential or how to authenticate with new Server to Server (S2S) authentication.

I thought of providing some good links already available there. However I feel that some of the steps mentioned are not pictorially represented. Hence penning down this blog for the benefit of my blog readers.

In this example I will give a complete example of querying the list of account through Web API from a External web app and not just getting the bearer token.

There are two steps to this example

1. Get the token Authorization token from Azure

2. Send the authorization token to get the list of accounts from CRM using the Web API endpoint.

 

Step 1: Register your application with Azure to get the Client ID and Client Secret

 

image

  • Enter the necessary information. Name is anything you wish to give. Sign-on Url is my website’s sign-on page.

image

  • Once the application is created then note down the Application ID and then click on Settings. You Application ID here is the Client ID.

image

  • Click on Required Permissions –> API’s –> Select an API and choose – Dynamics CRM Online

image

  • Choose Delegated permissions as highlighted below and the save your settings in Azure.

image 

  • Then click on Keys. Enter the key name to get a key value. Copy it immediately and store it. It is your client secret.

image

 

Step 2: Use ADAL in your Code to get the bearer token

The next step is to get the bearer token. To do this, open your project and through Nu-get package manager, add reference to the latest version of ADAL.

image

 

Below is the code to get the bearer token. Please read the comments to make the code work for your organization.

ClientCredential credential = new ClientCredential("<replace with your client id>", "<replace with your client secret>");

string authorityUri = "https://login.microsoftonline.com/xrmforyou53.onmicrosoft.com/oauth2/authorize"; // here xrmforyou53.onmicrosoft.com is my crm domain. Please replace with your domain
TokenCache tokenCache = new TokenCache();

            AuthenticationContext context = new AuthenticationContext(authorityUri);
            AuthenticationResult result = await context.AcquireTokenAsync("
https://xrmforyou53.crm.dynamics.com", credential); // https://xrmforyou53.crm.dynamics.com is my CRM URL. You need to use your crm url to test this.

            var authToken = result.AccessToken;

 

Please observe, we have not used the credentials of any user anywhere.

 

Step 3: Get the accounts from CRM.

So far you may be thinking that this is what we have already tried before as well. What’s new in this.

Well I take the below piece of code and try to load my account list.

public async Task LoadAccount(string bearerToken)
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //

            var result = httpClient.GetAsync("https://xrmforyou53.crm.dynamics.com/api/data/v9.0/accounts?$select=name").Result;

            var accountJSON = await result.Content.ReadAsStringAsync();

        }

 

However I receive 401. Unauthorized error.

If you are feeling now it’s time to learn something new, you are right. But before we go ahead, let’s understand why you are getting unauthorized error. After all, in Azure I gave the app to access Dynamics as a Organization user.

That step enabled the client application to access Dynamics CRM by using the Application ID and the client secret. Your client application is now able to be authenticated against Azure AD with permission to access CRM Online. However, CRM Online does not know about this "client application" or "user". CRM API will response a 401 if you try to access it.

So let’s jump to step 4.

 

Step 4: Create an Application User in CRM and assign security roles to it.

Well this may be a previous step but I deliberately put it in the last one to make you understand the unauthorized error.

Go to CRM –> Security –> Users and switch the view from the default view to “Application Users”.

image

 

Click on the New button to create a New Application User. You may be landing to the user form by default. Change the form to application user form.

image

 

In the application ID, enter the application ID of your app you obtained from Azure in Step 1.

I put the name of the user as – WebApp Application User

Email I put as – webappuser@xrmforyou53.onmicrosoft.com. I have used my domain. You better use your CRM domain. The name will automatically populate from the email you give. Once you save the record, CRM will auto populate the Application ID URI and the Azure AD Object ID.

 

Now in this example we are trying to retrieve account records. So it’s better you create a custom security role and assign to this user which will give the application user read permission on the Account record. I copied the Salesperson role and then assigned to this application user. Basically whatever operation you want to perform using Web API, you need to provide the same privilege to the application user.

Now when you run the code in Step 3, this time you get the account JSON. The icing on the cake is Application user won’t consume CRM licenses as well.

Hope this was helpful for you guys.

 

Debajit Dutta

(Dynamics MVP)

For consultation/ training visit www.xrmforyou.com or reach out to us at info@xrmforyou.com

{Utility} Automatic Roll-up calculator for Dynamics 365–from XrmForYou

Frustrated about customers complaining that Roll-up fields are not calculating at runtime? Abandoned rollup fields and went for something custom because customer couldn’t afford the calculation to happen every hour? The good news is that you do not need to worry about all these any longer. The new Automatic Rollup Calculator solution from XrmForYou tackles all these scenario and does much more.

Dynamics 365 offers a wonderful UI based editor to define your roll-up fields. It’s quite powerful. However whenever we go to customer and say that roll-up fields are not calculated at run-time, it puts us in some shaky situation. Our tool does the following:

  • Identifies any changes in the child entities involved in the roll-up field definition and automatically calculates the roll-up field values
  • Handles scenario when
    • Child record is created
    • Child record is deleted
    • Child record is updated. Handles both the scenarios when associated parent of the child record is changed or the field of the child entity involved in the calculation of roll-up field is updated.
    • On-demand calculation of all roll-up fields of a record.

And all of these with just few configuration steps. So let’s see how our tool works.

For trial and pricing, please write to us at info@xrmforyou.com. Video and documentation coming soon on www.Xrmforyou.com website.

The tool comes in the form of managed solution. Once you install, it will appear in your solutions area.

Solution Name – XrmForYou.RollupfieldCalculator.

image

Open up the solution and navigate to the configuration Page. You will see a screen like the one shown below.

image

 

For this documentation, I have set up the following structure.

  • Created an Entity – Test Entity
  • Set-up 1:N relationship with Contact
  • Created two roll-up fields
    • Count of Contacts – Rollup field showing the number of contacts associated with the Test Entity
    • Contact Credit Limit Sum – Rollup field showing the aggregate of the credit limit field of the contacts associated with the Test Entity.

Definition of both the fields in screenshots below.

image                  image

Okay. So far so good.

I select my Test Entity from the DropDown and all the roll-up fields of the entity shows up.

image

 

This UI helps me pick and choose which roll-up field I want to enable for automatic calculation

I select both and click on Save Configurations button. The system will start setting the roll-up field configuration for the selected fields. You can monitor the state of the operation by going to Settings –> System Jobs

JobName – x4uru_ActionRegisterSDKStep.

image

image

If the job fails, you need to open and see the error. If the job succeeds, it will disappear from the system jobs list.

Once successful, you are all set.

For testing I create two records – “Test Record 1” & “Test Record 2”.

For both the records the roll-up fields are showing 0 which is expected.

image

 

I open up Test Record 1 and associated 4 contacts.

image

 

If I now refresh, my advanced find view, I can immediately see the roll-up fields being updated.

image

Please note that in order to avoid any performance issues, the roll-up field calculation happens through asynchronously the moment any changes are made to the child entity. Hence if your async job is stuck sometimes you may experience a bit of delay. But usually all this will happen within seconds of updating the child entity.

Now I open up any contact associated with Test record 1 and associate it with Test Record 2.

Immediately when I come back and refresh my advanced find view, I can see the results.

image

 

Cool. Now before I wind up, there is one more feature that the tool comes with. Once you install the solution and open up any entity form, you will see a new button in the Menu called – “Calculate Roll-up Fields”.

image

Say you don’t want to go for automatic calculation but you want the user to have an option of updating all the rollup fields on a record on-demand. You have this option which allows you to do exactly like that.

Click on the button and the dialog pops-up where you can pick and choose the roll-up fields to be updated.

image

Select the desired fields and then click on Update. The page will refresh to show the latest roll-up data.

If you believe this tool works for your organization, you can request for trial and pricing at info@xrmforyou.com.

Video and documentation will be uploaded in our website www.xrmforyou.com soon.

 

-Debajit Dutta

(Dynamics MVP)

Sharepoint Metadata Manager and Attachment Extractor–New version released!

We are delighted to announce the release of the next version of our tool – Sharepoint Attachment Extractor and Metadata Manager. For readers who are new to this tool, this tool enables you to upload documents to Sharepoint with multiple metadata as well as host of other features like

    • Allows you to create and edit Metadata related to files from CRM. This version allows up to five metadata fields per entity and also provides the option to restrict the metadata values to a specific set of values or free text.
    • Dynamic adding and removal of the SharePoint section on the form of an entity just through configuration page that comes with the tool. Also you can place the SharePoint section on multiple forms for the entity.
    • Upload up to five files at one go along with the option to enter metadata for each file. Also size limit of file not constrained by the attachment size limit in CRM
    • Automatically moving the document from the annotations section of CRM to Sharepoint.
    • Behaves in conformance with the security privileges of the user in CRM for the record on which the SharePoint section is being shown.

You can download the detailed documentation from this link – http://www.xrmforyou.com/sharepoint-integrator.html

 

For trial and pricing, please write to us at info@xrmforyou.com

 

So what’s new in Version 2.0?

1. Performance

Our team have worked greatly on the performance issues especially during metadata update and also during upload of five files with metadata. The current version is ~1.5x faster than its previous version in terms of interaction with SharePoint

2. UI in conformance with Dynamics V9.0

The entire look and feel of the Sharepoint Grid control has been revamped in conformance with the new version of CRM. The grid contains a host of features including

  • Column resizing
  • Improved Searching logic
  • Sorting
  • Paging
  • Document reload
  • Drag  & Drop

Screenshots for reference.

image

 

4

 

3

 

3. Ability to specify column ordering for metadata

The tool now comes with the capability to enable column ordering for metadata.

2

 

Untitled

 

All of this and much more to offer. Reach out to us to know how we can help you.

For trial and pricing, please write to us at info@xrmforyou.com

 

-Debajit Dutta

(Dynamics MVP)

www.xrmforyou.com