Capturing Dynamics 365 client side exceptions with Azure Application Insights

In the Previous blog (Capturing client-side telemetry), we have seen how to capture the client side performance telemetry using the Application Insights and this blog we will see how to capture the exceptions.

Follow the below steps to capture the exceptions for Dynamics 365,

  1. Log in to Dynamics 365 and create a web resource for Application Insights and add the below-mentioned scripts. Update your Application Insights Instrumentation key in the highlighted area on the script.
if (ApplicationInsights === "undefined") {
 var ApplicationInsights = {};
}

ApplicationInsights = {
 trackApplicationInsightException: function (errorException, properties) {
 var appInsights = window.appInsights || function (config) { function i(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, u = document, e = window, o = "script", s = "AuthenticatedUserContext", h = "start", c = "stop", l = "Track", a = l + "Event", v = l + "Page", y = u.createElement(o), r, f; y.src = config.url || "https://az416426.vo.msecnd.net/scripts/a/ai.0.js"; u.getElementsByTagName(o)[0].parentNode.appendChild(y); try { t.cookie = u.cookie } catch (p) { } for (t.queue = [], t.version = "1.0", r = ["Event", "Exception", "Metric", "PageView", "Trace", "Dependency"]; r.length;) i("track" + r.pop()); return i("set" + s), i("clear" + s), i(h + a), i(c + a), i(h + v), i(c + v), i("flush"), config.disableExceptionTracking || (r = "onerror", i("_" + r), f = e[r], e[r] = function (config, i, u, e, o) { var s = f && f(config, i, u, e, o); return s !== !0 && t["_" + r](config, i, u, e, o), s }), t }(
 {
 instrumentationKey: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
 });
 window.appInsights = appInsights;
 appInsights.trackException(errorException, "JS Exception", properties);
 }
}
  1. For whichever entity the client side exceptions telemetry needs to be captured add the below JavaScript code to the entity JavaScript web resource.
function triggerInvoiceGenerationAction() {
 try{
 //get the current organization name
 var serverURL = Xrm.Page.context.getClientUrl();
 //query to send the request to the global Action 
 var actionName = "new_GenerateInvoiceFromOpportunity";
 var opportunityId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
 var action = "opportunities(" + opportunityId + ")/Microsoft.Dynamics.CRM." + actionName;

//Create the HttpRequestObject to send WEB API Request 
 var req = new XMLHttpRequest();
 req.open("POST", serverURL + "/api/data/v8.0/" + action, true);
 req.setRequestHeader("Accept", "application/json");
 req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 req.setRequestHeader("OData-MaxVersion", "4.0");
 req.setRequestHeader("OData-Version", "4.0");
 req.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
 req.onreadystatechange = null;
 if (this.status == 200 || this.status == 204) {
 alert("Invoice got generated.");
 Xrm.Page.data.refresh();
 } else {
 var error = JSON.parse(this.response).error;
 alert("Error occured during Invoice generation: " + error.message);
 throw (error.message);
 }
 }
 };

req.send();
 }
 catch (err) {
 var properties = { User: Xrm.Page.context.getUserName(), ObjectId: Xrm.Page.data.entity.getId(), FormType: Xrm.Page.ui.getFormType(), Trigger: 'Generate Invoice Button Click' };
 ApplicationInsights.trackApplicationInsightException(err, "JS exception", properties);
 }
  1. You can add as much as details you want to capture by adding to the properties. These properties information will be captured as Exception Properties in the Application Insights.
var properties = { User: Xrm.Page.context.getUserName(), ObjectId: Xrm.Page.data.entity.getId(), FormType: Xrm.Page.ui.getFormType(), Trigger: 'Generate Invoice Button Click' };

ApplicationInsights.trackApplicationInsightException(err, "JS exception", properties); 
  1. All the exceptions will be captured in the Application Insights and by using the dashboards and charts we can see all the exception metrices. Alerts can also be configured be in the Application Insights, so that if more exception occurred and automated Emails will be sent to the configured Email ids.

11

 

12

  1. If the Visual Studio Team Services is configured with the Application Insights, then a work item (bug) can be directly created from the exception and all the exception details will be automatically captured in the work item.

One thought on “Capturing Dynamics 365 client side exceptions with Azure Application Insights

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s