Monday, November 12, 2018

Use Xrm.WebApi in a stand alone Web Resource

I ran into this issue working on the last update to CRM REST Builder when adding the Xrm.WebApi functionality. Note this won’t effect you if you’ve got a web resource embedded in a form.

Attempting to execute a simple retrieve for example:
Xrm.WebApi.online.retrieveRecord("account"…
And I was greeted with this error:

Unexpected token u in JSON at position 0

What does that even mean? I bit of searching and I ran across this Stack Overflow question. So it seems Xrm.WebApi is looking for a variable which maps entity names with their corresponding entityset names. Easy fix since I had all the data so I dynamically built a variable with all the mappings which looked a bit like this (you only need to add the entities you're working with):
window["ENTITY_SET_NAMES"] = ['{"account":"accounts", "contact":"contacts"}'];
Got further along and started working implementing actions and functions and ran into the same error once again, WTF. After some tedious debugging through the Microsoft code I found there is another dependency on a similar variable. This one maps entities to their primary id fields. So I added something like this with all these mappings:
window["ENTITY_PRIMARY_KEYS"] = ['{"account":"accountid", "contact":"contactid"}'];
After that my problems were solved.