Dynamics 365 Web API - Create Notes With Attachment

Introduction

Today I will explain how to create notes with attachment in CRM using Web API. In order to create attachment we need to convert the content to Base64String and pass the content as string in request body to CRM.

Code to create Notes with Attachment using Javascript XMLHttpRequest,

var entity = {};
entity.subject = "ABCDDDDDDDDDDDDd";
entity.notetext = "Test Details\n\n";
entity.filename = "File.txt";
entity.isdocument = true;
entity.documentbody = "TU0gVGV4dCBGaWxl";
entity["[email protected]"] = "/accounts()";
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/annotations", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            var uri = this.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

Code to create notes with attachment using Web API

var entity = {};
entity.subject = "ABCDDDDDDDDDDDDd";
entity.notetext = "Test Details\n\n";
entity.filename = "File.txt";
entity.isdocument = true;
entity.documentbody = "TU0gVGV4dCBGaWxl";
entity["[email protected]"] = "/accounts()";
Xrm.WebApi.online.createRecord("annotation", entity).then(function success(result) {
    var newEntityId = result.id;
}, function(error) {
    Xrm.Utility.alertDialog(error.message);
});

Note

  1. While setting object ID or regrading lookup we have to specify entity name with field schema name [email protected] otherwise you will get an error from CRM web service.
  2. documentbody value should be converted to Base64String
  3. We can pass HTML tag in notetext field to show formatted values
  4. isdocument should be set to Yes

Hope this helps!