Client Side API
In order to support custom functions and custom pages, an API has been created to give access to Dynamics 365 records, through the portal security layer...
Feature Overview
In order to support custom functions and custom pages, an API has been created to give access to Dynamics 365 records, through the portal security layer, as well as through an extra API filter.
Razor View API
There is a MVC server side helper class that will allow you to easily read records and execute fetch. This layer filters through the standard entity permissions for the currently logged on user, but skips the API filter layer (explained below), therefore all dynamics fields are available to you. Since this is executed server side by the razor view engine, you are in control of what is actually rendered to the client side. Using this API helper class, you can render dynamic content from various entities to the end user. This allows you to display information in a summary form, or give personalised messages in descriptions or headers.
Note that you will require a custom page with a custom template to make use of this feature.
Steps to implement
In the Umbraco backoffice, under settings, create a new document type with template.
On the Template you can specify any compositions or properties you may need for your page. These are populated when you create a new page using this document type, and is then parsed and rendered by the template.
In order to be able to create pages of this type, you will need to give another page permission to have this type of page as a sub-page. Typically you would do this on the Home document type. Go to the desired document type (e.g. Home) and click on the permissions in the top right corner. Note that permissions here is a bit misleading, and refers to the content types you can create underneath this content type.
Navigate to content, select the parent page (typically the home page), click create and select your document type.
You can complete the fields on your document type for this page, and give it a name.
Navigate to settings, templates and find your document type's template. You can use a master layout page, like layout.cshtml, or you can build a page completely from scratch. Using layout will give you the standard menu and a few other things, which will speed up your page development.
Here is some sample code to make use of the MVC helper class:
// Add the following using statements to the top section of your page:
@using KlevrPortal.Core.Services;
@using DynamicsInterface;
@using Microsoft.Xrm.Sdk;
The following code shows small examples of each of the available functions:
@{
//to get a reference to the API Service class:
var api = DependencyResolver.Current.GetService<APIService>();
//within the page, use the following code to retrieve custom properties form your page, for instance to get a property called EntitySchemaName:
@Model.GetProperty("EntitySchemaName").GetValue()
//To retrieve the current user's Contact GUID:
@api.CurrentUserId()
//to retrieve a single record:
var acc = api.GetRecord("account", new Guid("a45e6d39-32a2-eb11-b1ac-0022481449c3"));
//Returned record is either null if no permission or not found, or an object of Type Entity (standard CRM SDK entity class)
//e.g. To get a value from the record:
<div> Account Name: @acc.GetAttributeValue("name") </div>
//To retrieve multiple records:
var fetch = api.GetRecords("<fetch><entity name='account'><attribute name='name' /></entity></fetch>", Guid.Empty, Permissions.Read);
// first param is a fetchml string.
// Second param is the current record's id. Some fetchxml queries may contain an @currentrecord value, and this will be injected.
// Remember the fetch is modified to include the permission conditions to ensure the current user has access to the requested records.
// third param is the required permissions. In most cases this will be read, since this will read and return records,
// but you may wish to validate if the user has update or delete access to a record too.
// The result is a tuple. Item1 contains the modified secured fetchxml, mostly for debugging purposes.
// Item2 is an entitycollection, the same as a RetrieveMultiple result from the Dynamics SDK.
// The following code provides an example of retrieving values form the query
<div>Result length: @fetch.Item2.Entities.Count()</div>
<div>First Result: @fetch.Item2.Entities[0].GetAttributeValue("name")</div>
//CRUD Operations uses the Dynamics SDK entities. Use try-catch blocks to catch exceptions.
//Permissions are the most likely cause of failure. All calls will be evaluated against portal permission configuration for the current logged in user
Entity sampleacc = new Entity("account");
acc["name"] = "test create";
Guid res;
//Create entity
try
{
res = api.CreateRecord(sampleacc);
<div>Create Account Guid: @res.ToString()</div>
}
catch (Exception e)
{
<div>@e.Message</div>
}
//Update Entity
try
{
sampleacc["name"] = "test update";
api.UpdateRecord(sampleacc);
<div>Update Account succeeded.</div>
}
catch (Exception e)
{
<div>@e.Message</div>
}
//Delete entity
try
{
api.DeleteRecord(sampleacc.ToEntityReference());
<div>Delete Account succeeded.</div>
}
catch (Exception e)
{
<div>@e.Message</div>
}
//Invoke Custom Action. NOTE! This does not validate permissions at all. Think about rogue attacks browsing directly to this page. Ensure you have checks in this code to ensure it's a valid scenario to execute this function!
try
{
ParameterCollection p = new ParameterCollection();
p["Target"] = new EntityReference("klevr_application", new Guid("29b041b9-0041-ec11-8c62-00224815918a"));
p["param2"] = (int)5;
p["param3"] = "test";
var ret = api.ExecuteAction("klevr_test", p);
EntityReference er = (EntityReference)ret["out"];
<div>Custom action output: @er.Id.ToString()</div>
}
catch (Exception e)
{
<div>@e.Message</div>
}
}
CurrentUserId
- Syntax: Guid ApiService.CurrentUserId();
- Returns the Dynamics contact ID of the currently logged on user, or Guid.Empty for anonymous.
GetRecord
- Syntax: Entity ApiService.GetRecord(string entityLogicalName, Guid entityId);
- Returns the record, if the user has read permissions to it.
GetRecords
- Syntax: Tuple<string, EntityCollection> ApiService.GetRecords(string fetch, Guid currentRecord, Permissions p);fetch: Valid and complete fetchxml. Will be augmented with permissions. currentRecord: Used to replace
@currentrecordvalues in your fetch. Can be Guid.Empty if not used. Permissions: enum containing Create, Read, Update, Delete. Used to select which permissions to apply to the query.
CreateRecord
- Syntax: Guid ApiService.CreateRecord(Entity e);
- Returns the Guid of the newly created record, or throws an exception if there is an error, or insufficient permissions.
UpdateRecord
- Syntax: void ApiService.UpdateRecord(Entity e);
- Throws an exception if there is an error, or insufficient permissions.
DeleteRecord
- Syntax: void ApiService.DeleteRecord(EntityReference e);
- Throws an exception if there is an error, or insufficient permissions.
ExecuteAction
- Syntax: ParameterCollection ApiService.ExecuteAction(string action, ParameterCollection parameters);action: Schema name of action to execute. parameters: Standard CRM SDK ParameterCollection object containing the parameters.
This does not pass through any security or permission checks, because it is not possible to determine which records are affected in which way inside a custom action, and therefore you need to ensure that the code using this method validates all input and access. Think about a rogue user navigating directly to this page, and how that may affect the system.
Client Side API
The client side API is accessible from JavaScript using XMLHttpRequests. Because this is exposed client side, and accessed form the client side, it goes through an additional layer of security that needs to be configured in the Umbraco backoffice. This additional security layer allows you to configure which entities and fields are accessible through the client side API, to ensure that if it is abused, it won't allow the user to do anything other than what the site is configured to allow.
Configuring allowed entities and fields
In the Umbraco backoffice, navigate to content, and if you do not yet have a page of type "Dynamics API Configuration", then create a new one under the home page. Note this page does not have a template, and therefore even though it gets a URL, the URL will display a page not found error. You can also have multiple configuration pages, and when calling the API, you can select which page to apply, although in most cases 1 should be sufficient.
On the Page itself, in the permissions property, add content.
The content will ask for an entity name, read and write (or both) and a list of field names.
You can specify multiple sections for the same entity. They will all be unioned. Typically you might have a section for readable fields and another section for updateable fields, so max 2 per entity, although you can create more without issues, it is unnecessary.
You have to specify each field on the entity that you wish to read or update. When retrieving a record all the readable fields will be retrieved. When updating a record, only allowed fields will be updated. Any extra fields included in the payload will cause the entire action to return an error, and prevent any update from occurring. For create and delete actions, the standard entity permissions are applied.
All API functions expect the same JSON object for the body , some functions will use different parts of it. The complete object is defined as follows:
var record = {
configid: 2198,
// The ID of the Dynamics API Config page.
//You can get this from the info tab on the page in the backoffce.
//If it refers to a page that is not of the correct type, an error will be returned.
entityId: "383BDF3B-CA75-4C10-9AF0-47F83CC390D5",
// The guid of the record you are referring to. Ignored for create
entitySchemaName: "klevr_application",
// Schema name of the targeted entity
record: {
"klevr_name": "Test Portal API success!",
// JSON object representing the record. Ignored for read and delete
// Format is the same as for a retrieved record, and matches the D365 types
// for instance, a lookup is represented as follows:
"klevr_lookup": {
"Id":"dcf0948d-f5d9-eb11-bacb-00224815864e",
"LogicalName":"klevr_country",
"Name":"Andorra",
},
//and a picklist would look like:
"statecode": {
"Value": 0
}
}
};
WhoAmI
- Endpoint: /umbraco/api/TableDataApi/WhoAmI
- Method: GET
- Params: None
- Result: a JSON object (based on request content type) with Name and Id. Name contains the current user's username, and Id contains their Dynamics Contact Guid.
RetrieveRecord
- Endpoint: /umbraco/api/TableDataApi/RetrieveRecord
- Method: Post
- Result: Will return all fields defined as read in the API configuration page if successful.
RetrieveRecords
In order for this setup to work. A page must be built in the back office that contains a list of the records you want to retrieve.
- Endpoint:/umbraco/api/TableDataApi/GetAllData/?id=<Page ID that contains the list, see above>¤tRecord=<GUID>
- Method: Get
- Result: This will return a JSON string of an array containing the fetch information, and then all records contained on the list if successful.
CreateRecord
- Endpoint: /umbraco/api/TableDataApi/CreateRecord
- Method: Post
- Result: Will return a JSON string containing the GUID of the newly created record if successful.
UpdateRecord
- Endpoint: /umbraco/api/TableDataApi/UpdateRecord
- Method: Post
- Result: Will return a JSON string containing the GUID of the updated record if successful.
DeleteRecord
- Endpoint: /umbraco/api/TableDataApi/DeleteRecord
- Method: Post
- Result: will return an OK if successful.
M:M Associate Records
- Endpoint: /umbraco/api/M2MDataApi/AssociateRecords
- Method: Post
- Body: { "id" : "Umbraco page id containing M:M subgrid", "subid": "item number of subgrid on page", "currentrecord":"Guid of record A", "associatedRecord": "Guid of record B" }
- Result: will return an OK if successful. Will validate create permissions on M:M table
M:M DisassociateRecords
- Endpoint: /umbraco/api/M2MDataApi/DisassociateRecords
- Method: Post
- Body: { "id" : "Umbraco page id containing M:M subgrid", "subid": "item number of subgrid on page", "currentrecord":"Guid of record A", "associatedRecord": "Guid of record B" }
- Result: will return an OK if successful. Will validate delete permissions on M:M table
Execute Custom Action
- Endpoint: /umbraco/api/TableDataApi/ExecuteAction
- Method: Post
- Body: { "configid": Umbraco API Definition Page ID where custom action is defined, action: "Schemaname of action", parameters: JSON Object containing the parameter name an value pairs. Values must define the type in an "@odata.type" property, or be a plain string mathing a string field. Valid types:EntityReference (specify LogicalName and Id) Boolean (specify value as boolean) DateTime (specify value as parseable dattime string) Decimal (specify value) Float (specify value) Integer (specify value) Money (specify value) Picklist (specify value as index of picklist) String (specify value) Entity (specify LogicalName and Id) Example: {"Target" : {"@odata.type": "EntityReference", "Id": "29b041b9-0041-ec11-8c62-00224815918a", "LogicalName": "klevr_application"}, "param2": {"@odata.type": "Integer", "value": 5}, "param3": "test"} };
- Result: will return JSON string representing the output parameters of the custom action.
If any of the methods fail, typically due to permissions, incorrect field or field values, you will receive a HTTP statuscode of 400 with an error message. Permission errors will mostly result in "Bad Request".
Here's an example of calling the API:
function getRecord() {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function (r) {
console.log('retrieved ' + r.target.responseText);
});
oReq.open("POST", "/umbraco/api/TableDataApi/RetrieveRecord");
oReq.setRequestHeader("Content-Type", "application/json");
var record = {
configid: 2198,
entityId: "7e07d7a9-6de0-eb11-bacb-002248154ab9",
entitySchemaName: "account",
};
oReq.send(JSON.stringify(record));
}
Example: Ensuring only 1 sub-record is created
Background
This example demonstrates how to use the API to validate that only 1 record is created from within a subgrid. For instance, ensuring that only 1 application per application round can be created. This example can also be extended to ensure only one draft application is created, but multiple applications can be submitted. Once submitted, the next draft can be created.
The idea is to do the following: Create an "intermediate" page that will be used as the target of a new record on a subgrid. This page will use the server side API to run a fetch query to find the ID of an existing record. If the record is not found, the user will be redirected to the page to create a new one, however if a record is found, the user will instead be redirected to the edit page for this record.
Steps
In the backoffice, under settings ➡️ document types, create a new document type with template. You do not need any properties on the document type, unless you will exptend this sample for more complex solutions.
Open the template for the document type, and paste the following code:
@inherits Umbraco.Web.Mvc.UmbracoViewPage
@using KlevrPortal.Core.Services;
@using DynamicsInterface;
@using ContentModels = Umbraco.Web.PublishedModels;
@{
Layout = null;
var api = DependencyResolver.Current.GetService<APIService>(); //Get reference to the dynamics server side API
var currentRecord = Request.Params["refid"]; // get a parameter from the querystring. This is passed from the new button on a subgrid, and contains the id of the record that the user was on when clicking the new button.
var fetchqry = "<fetch>" +
"<entity name='klevr_application'>" +
"<attribute name='klevr_applicationid' />" +
"<filter type='and'>" +
"<condition attribute='klevr_applicationroundid' operator='eq' value='@currentrecord' />" +
"</filter>" +
"</entity>" +
"</fetch>"; // a fetch statement. Note the use of @currentrecord.
//The api.GetRecords function below will replace this with the value of its second parameter.
//the permissions.Read specifies that it should apply the permissions that grant the user at least read rights
//You can alter this to Permissions.Write to ensure the user has write access to the existing record
var fetch = api.GetRecords(fetchqry, new Guid(currentRecord), Permissions.Read);
//generate the url. We want to redirect to the page that will create the intended record type, using the same querystring as was passed to this page
var dest = "/application/?" + Request.QueryString;
if (fetch.Item2.Entities.Count() > 0)
{ //if we did find a record, add the ID of the found record to the url, which will open the existing record, instead of creating a new one.
dest += "&id=" + fetch.Item2.Entities[0].GetAttributeValue("klevr_applicationid").ToString();
}
//redirect the user to the URL.
Response.Redirect(dest);
}
The comments explain the working of the code. Ensure you update the fetchxml to reflect your intended entity and the link (var dest = "/application/?") to the page for creating and updating your sub-record.
settings ➡️ document templates ➡️ Home, ➡️ Permissions (top right), add your template type.
Go to the content tab, and create a new page under home using your template.
Configure the new button on your subgrid to redirect to the new page you just created.
Test the solution by navigating to the subgrid and clicking on the new button, both with and without an existing record.
Last updated on