When developing custom web template in Dynamics portals, I quiet often use FetchXML queries. Sometimes, I include variables and loops to create my FetchXML but this doesn’t always go as smooth as I hope it would. More than once, I had the need to check what the real underlying FetchXML was because there was an unwanted behavior or an unexpected result.

To overcome this issue, I made myself a fairly simple “debugging” web template that I try to always include right after my FetchXML. In this web template, I usually include the FetchXML itself, and the amount of results returned.

Let’s dive right in by creating a new web template called “Debug FetchXML”. The code inside of this template is going to look something like this:

{% assign isAdmin = user | has_role: "Administrators" %}
{% assign isDebugMode = request.params["debug"] | boolean | default: false %}
{% if isAdmin and isDebugMode %}
<div class="alert alert-danger alert-dismissible" role="alert">
  {% if queryName %}<h4 class="alert-heading">{{queryName}}</h4>{% endif %}
  <h5>Number of results: </h5>
{% endif %}

The template checks if the user that is logged in is an administrator and if there is a url parameter called “Debug” that is set to true. If both of these conditions are true, the user will see an alert on the page with the information about the FetchXML request.

The only thing that we have to do now is include this web template after our FetchXML. In my case I already have a web template with a fetchXML query called “contactsQuery”.

{% fetchxml contactsQuery %}
  <entity name="contact" >
    <attribute name="fullname" />
    <attribute name="birthdate" />
    <attribute name="emailaddress1" />
    <attribute name="gendercode" />
    <attribute name="jobtitle" />
{% endfetchxml %}
{% assign contacts = contactsQuery.results.entities %}

<table class="table table-striped table-fluid">
        <th>Email address</th>
        <th>Job title</th>
        {% for contact in contacts %}
        {% endfor %}

After the query we need to insert 1 line of code:

{% fetchxml contactsQuery %}
{% endfetchxml %}
{% include 'Debug FetchXML' | queryName: "contactsQuery" | fetchXML: contactsQuery %}

Now lets go ahead and check our webpage. If you don’t see the alert on your screen, add a parameter to your URL in browser “?debug=true”. Now you should see an alert.

Debugging FetchXML

Now you can see the underlying FetchXML. All variables inside the FetchXML will be replaced with the actual value. If you want to double check if your query returns the correct amount of results you can rerun the query in a tool like “FetchXML Builder” in XrmToolBox. If the results do not match, you need to check if the entity permissions inside your portal are set up correctly.