Dynamics 365 portals new documentation!

Microsoft Dynamics 365 team has been transitioning all documentation to the new docs.microsoft.com site and just launched now is the new documentation for portals. This is a great change to see and is starting to bring the breadth of documentation in alignment with what is available on the legacy Adxstudio Community site. Having it in the Microsoft docs site will help make the content much more accessible and easier to refer to in blogs, forums and all other ways of sharing :).

The documentation is still a little short on the newest components that are available (no chart liquid object and a couple other items) but I look forward to this being continuously updated as new releases come out. This is only the first release of the documentation and I think we can expect it to be updated regularly.

Dynamics 365 portals: Customize Knowledge Articles

One of the more popular features of the Dynamics 365 portals is its ability to expose the knowledge articles from your internal CRM on the public portal or to select audiences. With how the knowledge article functionality is currently implemented in the portal there is not an easy way to customize the article display or enhance it with more functionality like attachments. However with the customization capability of liquid we can create our own display of an article that includes whatever other data is accessible through liquid. In this post we will look at an example and the other elements like search results that need to be modified to properly support this approach.

Firstly let’s start out by creating our custom article liquid template. To do so create a new Web Template and we are going to assume that an ID parameter will always be passed in the query string so we know what article to surface.

{% assign article = entities.knowledgearticle[request.params.id] %}
<div class="container">
  <div class="page-heading">
      {% include 'Breadcrumbs' title: article.title %}
  <div class="page-header">
     {% if article %}{{article.title}}{% else %}No article found{% endif %}
     <div class="pull-right">
	    <div role="toolbar" class="btn-toolbar">
		    <div class="btn-group">
			    <a href="javascript:window.print()" class="btn btn-default btn-sm"><span class="fa fa-print"></span>&nbsp;{{ snippets['Knowledge Management - Print Button Label'] }}</a>
 <div class="row">
  <div class="col-md-12">
   <div class="page-copy">
     {% if article %}
       {{ article.content }}
     {% endif %}

This template simply takes the ID parameter, gets the knowledgearticle entity record and then uses the object to display the breadcrumbs using the title parameter in that template. Then displays the page title using the article title and displays a print button just like the default article template. Finally we display the article content attribute which is where the HTML blob is stored if the article is found.

A common enhancement is to add a display of the associated note attachments to the article. With liquid we can easily access the notes and display them in a fashion to provide a list of downloads. You can see the liquid note documentation here. Below is a simple liquid code that will output the notes that are associated to the article displaying the title linked (manually as note.url seems broken or disabled or changed and not documented in v8.x) as well with the note text as the description.

{% assign notes = article.knowledgearticle_annotations %}
{% if notes.size > 0 %}
 <h3>Associated Documents</h3>
   {% for note in notes %}
     <li><p><a href="/_entity/annotation/{{note.id}}">{{note.subject}}</a><br/>{{note.notetext}}</p></li>
   {% endfor %}
{% endif %}

This can be added where you want the list of attachments to display, for this example it is inserted right after the {{article.content}}. This could be further enhanced to conditionally include only this notes that have documents using the attributes of the annotation entity and condition liquid tags. With your web template completed, you should now create a page template and a web page that uses that page template. Once the web page is created, also create a site marker that references the web page as we will use this later to help us link to the new article page.

There are a lot more things you can add to your articles using liquid. You just need to parse through the relationships associated to the article and then present the data appropriately. I may look at some further enhancements in future posts.

With building a custom article template we need to deal with the fact we no longer want the links navigating to the old MVC based article routing. To do so we need to try to replace all the locations that this routing is in place. The largest one is probably the search. With the search being built off handlebars and liquid as we explored in a preview post – Extend Search Results with Handlebars, you can change the default URL for knowledge article results.

First we need to add a handlebars helper in JavaScript to the search results page so we can put in some conditional logic to change the URL when the result is for a knowledgearticle entity record. This is just a simple addition that allows you to do an if equals in handlebars.

Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b) // Or === depending on your needs
        return opts.fn(this);
        return opts.inverse(this);

Now we can make use of this new helper in the Faceted Search – Results Template Web Template. Within the {{#each items}} we are going to modify the contents of the h3 tag to have some conditional logic to change the default link it uses to be our site marker we previously created.

{{#if_eq entityLogicalName "knowledgearticle"}}
  <a title="{{title}}" href="{%endraw%}{{articleSiteMarker.url}}{%raw%}?id={{entityID}}">{{title}}</a>
  <a title="{{title}}" href="{{url}}">{{title}}</a>

Basically all we have added is a condition that when the result is from a knowledgearticle entity then use our site marker URL passing the entityID as the id as the href of the anchor tag.

Make sure you also at the very top of this web template include a reference to your site marker.

{% assign openTag = '{{' %}
{% assign closingTag = '}}' %}
{% assign articleSiteMarker = sitemarkers["Article"] %}

With the chance of their being some routing that still is hard coded somewhere in the portal we can put some logic on the out of box article default page that will cause it to route to our new page as well. The easiest way to modify this is to login to the portal with an administrative account so you can use the front-side editor to make your changes. Navigate to an existing article you know by using the following route format https://{portal_url}/knowledgebase/article/ka-01000, and replace the ka-01000 with an article code you know exists.

Once on the page then edit using the front-side editor and go to the Options tab. Within the Custom JavaScript section add the following:

var pathArray = window.location.pathname.split( '/' );
var articleCode = pathArray[pathArray.length - 1];
{% assign articleSiteMarker = sitemarkers["Article"] %}
document.location = "{{articleSiteMarker.url}}?code=" + articleCode;

And within the Custom CSS add the following:

body {
  display: none;

This will cause a redirect to your new page while hiding the old one during the redirect. We now also need to enhance our custom web template for the article to take the code parameter as well. Replace the assign liquid at the top of the existing template with the following:

{% if request.params.id %}
  {% assign article = entities.knowledgearticle[request.params.id] %}
{% endif %}
{% if request.params.code %}
  {% fetchxml articlefetch %}
    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
      <entity name="knowledgearticle">
        <all-attributes /> 
        <filter type="and">
          <condition attribute="islatestversion" operator="eq" value="1" />
          <condition attribute="articlepublicnumber" operator="eq" value="{{request.params.code}}" />
  {% endfetchxml %}
  {% assign article = articlefetch.results.entities[0] %}
{% endif %}

With all our changes we should now have a custom article page that takes either the entityId or the article code as a parameter, search results routing directly to the new article and a catch for hard coded links to also redirect to the new page template. The same code here will have produced an article with the following format. You of course with liquid templating functionality can continue to customize and enhance this for your requirements.

Note with all these changes we have removed the content access level functionality. You can add this back by developing the appropriate liquid code to make the necessary checks.

Update 6/23/2017: Just announced at the July 2017 Update Executive Briefings, knowledge articles on the portal will be getting an enhancement to expose notes and attachments. This method in this post will still be of interest to those that find that the display is too limiting or there are other components in which they want to include in their knowledge article display.

Dynamics 365 portals: JavaScript as Web Files

With a lot of the previous posts about liquid there has been a lot of JavaScript involved as well. We have referenced JavaScript libraries on CDN’s (Content Distribution Networks) as well as wrote JavaScript inline in Web Templates. You may not want to use CDN’s and even package your own JavaScript into minified files so that they can easily be reused elsewhere. Out of the box Dynamics 365 portals is blocked from uploading JavaScript files as Web Files, but we can makes some changes to allow JavaScript files to be allowed as Web Files.

If you sign-in to the Dynamics 365 portal as an administrator and create a new child file with a .js file as the attachment it will seem that it will work as expected but when you browse to that new web file URL you will be presented with a blank screen. If you look at your browser tools you may notice that the portal actually returned a HTTP 404 (File Not Found) error. But in this case it does not redirect you to the standard Page Not Found portal page. So what happened? The portal seems to know the URL (or route) of the file I uploaded but isn’t showing any of the content. If you navigate to the back-end CRM and go to the Portals > Web Files entity, you will notice your Web File is infact there, but when you open it you may notice its missing your Note record with an attachment.

Web Files utilize notes (annotations) to store the actual file that will be surfaced with the Web File. If you try now creating a note with your attachment the issue will be revealed that the attachment was blocked due to “the attachment is not a valid file type”.

The standard Dynamics 365 configuration is set to block all file attachments with the file extension .js. This is due to security concerns that the JavaScript could be used to execute code within your CRM that causes unsafe actions or potentially even remotely accesses other services, all depending on the JavaScript code. The JavaScript code you likely want to use with the portal though is not a security risk to the CRM but we do need to be cautious as to not create a security hole for all the other CRM users.

First let’s change the allowed file types for CRM so that we can upload a JavaScript file. Navigate in CRM to Settings > Administration, then select System Settings. On the General tab find the Set blocked file extensions for attachments and within this long list locate js and remove it and the trialing semi-colon. Select OK to save the System Settings.

Now if you navigate back to Portals > Web Files, locate your previously created Web File without the note attachment and now try creating a note with an attached JavaScript file it will successfully create the note. If you now navigate on the portal to the Web File URL you should either see the JS content or the browser will prompt you to download the JS file. If you also now try to create a new Web File from the front-side editor tools in the portal this will also now operate as expected.

You can now reference this JavaScript Web File like any other JavaScript file in your Web Templates or elsewhere.

<script src="/path/name-of-file.js"></script>

Once you have uploaded your JavaScript files being your own JavaScript or libraries like chart.js or fullcalendar.js or the many other libraries, you should revert the System Settings to again block the .js file type to remove any security risk of your end users accidentally uploading malicious JavaScript code. Just navigate to Settings > Administration, open System Settings and within the Set blocked file extensions for attachments, add back the js extension with a semi-colon if not the last item.

Dynamics 365 portals Spring Roadmap and Portal Source Code

If you frequent the Dynamics 365 Roadmap site (built on portals 🙂 ) you may notice a new area has been added for the CRM based Applications (Sales, Customer Service, Field Service, Project Service) for portals features. A number of items for all areas of Dynamics 365 has been posted as we near the Spring release of Dynamics 365 (v8.3), but this is a first for the portal to have been posted which seems to be the makings of a Spring Roadmap for the product. There are some exciting items on there including a release of the portal source code, Azure AD B2C and more. Below is all the items posted to the roadmap as well as some comments on each.

Let’s get to the big one first, portal source code.

Source code for Portals
A one time release of Portals code will be released to the Microsoft Download Center under MIT license for developers to download.

This feature enables Portals to be deployed to Dynamics 365 on-premise environments, and allows developers to customize the code to suit their specific business needs.

This is a huge news, complete open source of all portals code! This should also be taken with some caution though. Let’s understand what this means.

  • One time release – it will never be updated, ever, ever again.
  • Under MIT License – free, and full open source software (OSS), no direct support from Microsoft.
  • Microsoft Download Center – not taking pull requests, no contributing back to a master branch

Some awesome news but a big caution for corporations looking to invest in a supported product. With it being a one time release it is basically a point in time and will not be updated with bug fixes, new features nor will it be supported by Microsoft. The future is very much still online with portals as a service which will continue to be updated with bug fixes, new features and fully supported by Microsoft. If you choose the OSS path then support could come from partners, or other corporations but they will all come with their own costs and potentially different versions of the portal. Being OSS MIT means that anyone can take the source change it and re-publish it, so we could end up with endless different versions of OSS portals. These are the pitfalls with any OSS product so just be very aware if you are someone interested in it.

If your an on premise customer that was still considering v7 of Adxstudio Portals then you should strongly consider this as the cost is a lot less 😉 (free vs $20k+ and even getting a license). However the same cautions apply and if your looking for a fully supported product then online with portal service is the future of the product. If you were looking at Adxstudio Portals v7 because of it’s event or retail functionality then that is still a gap in the OSS version as well.

For developers, this will be a gold mine for those to see the inner workings of the portals product. Look at how the Adxstudio and Microsoft product teams built features, implemented the CRM SDK, and gain a better understanding of how the product operates or why it does something a certain way or modify it to your liking.

Myself and Adoxio will have more to say on Open Source Portals shortly and the direction Adoxio will be taking.

The next big roadmap item…

Support Azure AD-B2C for Portal authentication using a single sign-on (SSO) configuration

For Portals that require a consumer based login, this feature will now support the ability to:

  • Configure your portal authentication to use a Single Sign-On configuration
  • Support Azure AD-B2C for customer authentication
  • Manage your Portal security in Azure

* depends on Azure AD-B2C availability in the region(s) Portals are deployed

I blogged about B2C working in CRM portals late last year, but at the time B2C while supported in portals was not exactly recommended by Microsoft due to some user experience elements not being as desired. It’s great to see that it will be natively supported and recommended with the user experience elements corrected and even more included features released. I can’t more strongly recommend using B2C as your authentication in the portal and moving your authentication outside of Dynamics 365 so that it can be used by all applications and not just the portal. One identity for all your external applications.

Some other interesting new functionality coming soon:

Post installation language add-ons
This feature makes it easier to manage new additions to the existing portal language support.

Great to see, so many portals start off in 1 language and later want to add additional support and this will make that painless now.

Admin wizard to add an entity to the Portal
Easily publish any entity on your Portal using our new administrative wizard. When data is updated in the entity, it will automatically be available to Portal users who have access to these data.

This is likely a tool that will automatically make entity lists, entity forms, and entity permissions with all the web pages setup for you. Will make exposing new entities in the system extremely easy for out of box functionality.

Portal interaction tracking
Track your customer’s interactions with your Portal and funnel it to Dynamics 365 Customer Intelligence to plot a 360 view.

Sort of like Google Analytics but with all the relationships to your other Dynamics 365 data!

Whew! That is a lot of awesome news of features that are going to be coming to the portals shortly. There are a couple more smaller features, you can checkout the full listing on the roadmap site. The exact release dates for all of these is not mentioned, the earliest would be with the Spring release of portals. Previous releases of portals from Microsoft have typically lagged approximately a month behind the Dynamics 365 release. They could also come in monthly updates between now and the fall release.

We will have to keep an eye on the roadmap for future features being announced!

Dynamics 365 portals: Use aggregate FetchXML queries and Chart.js

A frequently requested feature of all types of portals is to display Dynamics 365 data in different displays like charts. The Dynamics 365 portal has a pre-built chart function that utilizes the out of box CRM charting functionality so that you can take the charts you create in CRM and display then easily on the portal. This functionality is somewhat limited but using the techniques discussed in Using liquid to return JSON or XML we can easily build a services that uses FetchXML aggregate queries to build data returns to summarize or roll-up data. With the aggregated query results you can quickly work with many of the JavaScript charting libraries like d3.js, chart.js, flot.js or many others to display a rich interactive view of the data that the default chart liquid component can’t do. In this post is a simple implementation of Chart.js which is a powerful, but simple library that has a very small footprint to build some charts with the FetchXML aggregate data.

Let’s start by creating the web template that is going to return the JSON data for the chart to display. As in the previous examples we will use the fetchxml liquid tag to retrieve the data but using the aggregate function of FetchXML to summarize data. Our example is going to continue using the course schedules and instructors, for this chart we would like to get a count of schedules by instructor.

{% fetchxml feed %}
<fetch version="1.0" output-format="xml-platform" mapping="logical" aggregate="true">
  <entity name="dpx_courseschedule">
    <attribute name="dpx_coursescheduleid" alias="schedule_count" aggregate="countcolumn" />
    <attribute name="dpx_instructorid" alias="dpx_instructorid" groupby="true" />   
{% endfetchxml %}[
  {% for item in feed.results.entities %}
      "count": "{{ item.schedule_count }}",
      "instructor": "{{ item.dpx_instructorid.name }}",
      "instructorid": "{{ item.dpx_instructorid.id }}"
    }{% unless forloop.last %},{% endunless %}
  {% endfor %}

You’ll notice this FetchXML is different from previous examples. Firstly in the opening fetch tag it removes the distinct property and adds aggregate="true". Within the entity tags the attributes are limited to one to count by with the aggregate="countcolumn" for the dpx_coursescheduleid and then because we want the count by instructor the attribute for dpx_instructorid has the property groupby="true". As in previous examples we take the results, iterate through them and create a JSON array. Also don’t forget to set the web template Mime Type to application/json and ensure that you give the return JSON template a URL using the instructions in Use liquid to return JSON or XML.

With aggregate FetchXML queries you can include filter criteria so if you want to dynamically filter the data in the aggregation you can easily add parameters that are then added as filters. You could do some cool combinations with other components that use the same technique like the previous post on FullCalendar so that as you change months or filter down your calendar data it also is filtering the chart with the same parameters.

Now that we have a JSON data return template we can build the web template that will process it with the chart.js library. Below is the basic scaffolding for our template which is a canvas HTML5 element, the chart.js Javascript library and then a document ready with the get of the canvas element.

<canvas id="myChart"></canvas>

<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  $(function(){  // document ready    
      var ctx = $("#myChart");

Firstly within document ready we need to make a call to retrieve the data using a jQuery AJAX GET method to the JSON return template URL. With the returned JSON we will transform it into a chart.js data object so that it can be added easily to any chart type. To do so we are going to create a couple of arrays, one for labels and one for data values, then populate them by iterating through the resulting JSON array from the AJAX call.

$(function(){ // document ready
      method: "GET",
      url: "/courses-aggregate-json/"
    .done(function( results ) {
      var labels = [], datavalues = [];
      for (i = 0; i < results.length; i++) { 

      var dataobj = {
          labels: labels,
          datasets: [{
              data: countdata

      var ctx = $("#myChart");

      // bind data to chart object

With the returned data now formatted for chart.js data object we can initialize the chart element with a chart type and the data object. The chart.js options for the pie type are also set to animate its display and have the legend displayed at the bottom of the chart.

// inserted within the done of the ajax get
// after the transform of return JSON and creation of dataobj

var ctx = $("#myChart");

var myChart = new Chart(ctx, {
  type: 'pie',
  data: dataobj,
  options: {
    legend: {
      display: true,
      position: "bottom"

After getting this web template a URL with a page template and web page you should end up with your pie chart. Although its probably looking a little gray as we didn’t assign any colors.

If you read the previous post on FullCalendar then we know that our instructors entity actually contains an attribute that holds a hex color code value which we could use to color the chart. With following code which should be located at the top of the script tag prior to the document ready method, we can get those color codes, as well as create a function that will find the color for a specific instructor.

{% fetchxml feed %}
  <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
    <entity name="dpx_instructor">
      <attribute name="dpx_instructorid" />
      <attribute name="dpx_colorcode" />
{% endfetchxml %}

var instructorData = [{% for item in feed.results.entities %} {
      "instructorid": "{{ item.id }}",
      "color": "{{ item.dpx_colorcode | default:"#ffff00" }}"
    }{% unless forloop.last %},{% endunless %}
  {% endfor %}];

function findInstructorColor(lookupId) {
  for(var a = 0; a < instructorData.length; a++) {
    if(instructorData[a].instructorid == lookupId)
      return instructorData[a].color;

With this code we are doing similar to the previous JSON return template but within the JavaScript so on render of the template it dynamically renders an object called instructorData which is a JSON array with the instructorid and color.

In the transform into the data object section update it with a new array called color and populate the array in the result iteration (line 6) which uses the findInstructorColor method, then include that new array in the dataobj (line 13).

var labels = [], countdata = [], color = [];

for (i = 0; i < results.length; i++) { 

var dataobj = {
  labels: labels,
  datasets: [{
    data: countdata,
    backgroundColor: color

With these changes you should now have a much nicer looking pie chart with color!

Using JavaScript charting libraries in combination with the FetchXML aggregate queries can allow you to start creating some really cool looking dashboards that go beyond the out of box functionality of portals. You can even use some Bootstrap components to help you do some nice formatting in combination with charts.

If your interested in learning more about liquid techniques I will be giving a webinar with xRMVirtual on April 26th at 12pm EST – Advanced Liquid Templates for Dynamics 365 portals.