Using JavaScript Download or save any report to Sharepoint or notes Latest 2020
This Post contains unexplained and with not best practice code, in the coming days I will refine this.
This is not Step by Step Guide and not connected, will update the post again
Also not necessary use this in UCI , it only for knowledge sharing and for UCI there many other OOB alternatives as well, will share the link Soon
1. Get Report Session
getReportingSession: function () { var retrieveEntityReq = parent.document.getElementById("IFRAME_expiryreport").contentWindow.document.getElementById("resultFrame").contentWindow.document.documentElement.innerHTML; var x = retrieveEntityReq.lastIndexOf("ReportSession="); var y = retrieveEntityReq.lastIndexOf("ControlID="); var ret = new Array(); ret[0] = retrieveEntityReq.substr(x + 14, 24); ret[1] = retrieveEntityReq.substr(x + 10, 32); return ret; }, convertResponseToPDF: function (newPth) { //Create query string that will be passed to Report Server to generate PDF version of report response. //var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + arrResponseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + arrResponseSession[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF"; var pth = newPth; //Create request object that will be called to convert the response in PDF base 64 string. var retrieveEntityReq = new XMLHttpRequest(); retrieveEntityReq.open("GET", pth, true); retrieveEntityReq.setRequestHeader("Accept", "*/*"); retrieveEntityReq.responseType = "arraybuffer"; retrieveEntityReq.onreadystatechange = function () { // This is the callback function. if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200) { var binary = ""; var bytes = new Uint8Array(this.response); for (var i = 0; i < bytes.byteLength; i++) { binary += String.fromCharCode(bytes[i]); } //This is the base 64 PDF formatted string and is ready to pass to the action as an input parameter. var base64PDFString = btoa(binary); //4. Call Action and pass base 64 string as an input parameter. That’s it Xrm.Utility.showProgressIndicator("Converted report to PDF. Please Wait.."); var note = {}; var recordId = Xrm.Page.data.entity.getId(); recordId = recordId.replace('{', '').replace('}', ''); var NotificName = Xrm.Page.getAttribute("uniquefield").getValue(); var refInvoice = new Object(); refInvoice.LogicalName = "Logical name"; refInvoice.Id = recordId; note.ObjectId = refInvoice; note.ObjectTypeCode = refInvoice.LogicalName; note.Subject = "ContractExpiryLetter: " + NotificName; note.MimeType = "application/pdf"; note.DocumentBody = base64PDFString; note.FileName = NotificName + ".pdf"; XrmServiceToolkit.Rest.Create( note, "AnnotationSet", function (result) { //Alert user //alert("Note Created"); Xrm.Utility.closeProgressIndicator(); //Refresh data so user sees newly created note Xrm.Page.data.refresh(false); }, function (error) { Xrm.Utility.closeProgressIndicator(); alert(error.message); }, true ); } }; //This statement sends the request for execution asynchronously. Callback function will be called on completion of the request. retrieveEntityReq.send(); }
2. Run Report to Print
runReportToPrint: function () { var params = quoteInvoice.getReportingSession(); var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=public&ContentDisposition=OnlyHtmlInline&Format=PDF"; quoteInvoice.convertResponseToPDF(newPth); //window.open(newPth, "_self"); }, callActionOnButtonClick: function (data) { //// GUID Validation if (!quoteInvoice.isGuid(entityId)) { alert("ID is Invalid GUID."); Xrm.Utility.closeProgressIndicator(); return; } }, isGuid: function (value) { /// <summary> /// Checks whether value is type of GUID or not. /// </summary> /// <param name="value" type="type"></param> /// <returns type=""></returns> var validGuid = new RegExp("^({|()?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}(}|))?$") if (value && typeof value === "string" && validGuid.test(value)) { return true; } return false; } };
3. Get Doc Library or Create Doc Library Sharepoint
DocLibrary = { CheckDocumentLibraryAvailable: function () { var fetchXmlQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + " <entity name='sharepointdocumentlocation'>" + " <attribute name='relativeurl' />" + " <attribute name='regardingobjectid' />" + " <attribute name='parentsiteorlocation' />" + " <attribute name='absoluteurl' />" + " <attribute name='name' />" + " <attribute name='sharepointdocumentlocationid' />" + " <order attribute='name' descending='false' />" + " <filter type='and'>" + //" <condition attribute='ownerid' operator='eq-userid' />" + " <condition attribute='statecode' operator='eq' value='0' />" + " <condition attribute='locationtype' operator='eq' value='0' />" + " <condition attribute='servicetype' operator='eq' value='0' />" + " <condition attribute='regardingobjectid' operator='eq' uiname='test' uitype='" + Xrm.Page.data.entity.getEntityName() + "' value='" + Xrm.Page.data.entity.getId() + "' />" + " </filter>" + " </entity>" + "</fetch>"; var req = new XMLHttpRequest(); req.open( "GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/sharepointdocumentlocations?fetchXml=" + encodeURIComponent(fetchXmlQuery), false ); req.setRequestHeader("Prefer", 'odata.include-annotations="*"'); req.onreadystatechange = function () { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var results = JSON.parse(this.response); //console.dir(results); if (results.value.length > 0) { return; } else { DocLibrary.CreateDocumentLibrary(); } } else { alert(this.statusText); } } }; req.send(); }, CreateDocumentLibrary: function () { debugger; var locationid = ''; var fetchXmlQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + " <entity name='sharepointdocumentlocation'>" + " <attribute name='relativeurl' />" + " <attribute name='regardingobjectid' />" + " <attribute name='parentsiteorlocation' />" + " <attribute name='absoluteurl' />" + " <attribute name='name' />" + " <attribute name='sharepointdocumentlocationid' />" + " <order attribute='name' descending='false' />" + " <filter type='and'>" + // " <condition attribute='ownerid' operator='eq-userid' />" + " <condition attribute='statecode' operator='eq' value='0' />" + " <condition attribute='locationtype' operator='eq' value='0' />" + " <condition attribute='servicetype' operator='eq' value='0' />" + " <condition attribute='relativeurl' operator='eq' value='" + Xrm.Page.data.entity.getEntityName() + "' />" + " </filter>" + " <link-entity name='sharepointsite' from='sharepointsiteid' to='parentsiteorlocation' link-type='inner' alias='ac' />" + " </entity>" + "</fetch>"; var req = new XMLHttpRequest(); req.open( "GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/sharepointdocumentlocations?fetchXml=" + encodeURIComponent(fetchXmlQuery), false ); req.setRequestHeader("Prefer", 'odata.include-annotations="*"'); req.onreadystatechange = function () { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var results = JSON.parse(this.response); //console.dir(results); if (results.value.length > 0) { locationid = results.value[0].sharepointdocumentlocationid; } else { alert('Unable to check the Sharpoint integration. Please contact administrator.'); } } else { alert(this.statusText); } } }; req.send(); var relativepath = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "").replace("-", "").replace("-", "").replace("-", "").replace("-", ""); var absolutepath = DocLibrary.ConstructPath(locationid); var locationdetails = { "LocationName": "Location 1", "AbsUrl": absolutepath + relativepath, "RelativePath": relativepath, "ParentType": "sharepointdocumentlocation", "ParentId": locationid, "IsAddOrEditMode": true, "IsCreateFolder": true, "DocumentId": "", "ParentEntityReference": { "@odata.type": "Microsoft.Dynamics.CRM." + Xrm.Page.data.entity.getEntityName() } }; locationdetails["ParentEntityReference"][Xrm.Page.data.entity.getEntityName() + "id"] = Xrm.Page.data.entity.getId(); var createReq = new XMLHttpRequest(); createReq.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/AddOrEditLocation", false); createReq.setRequestHeader("OData-MaxVersion", "4.0"); createReq.setRequestHeader("OData-Version", "4.0"); createReq.setRequestHeader("Accept", "application/json"); createReq.setRequestHeader("Content-Type", "application/json; charset=utf-8"); createReq.onreadystatechange = function () { if (this.readyState === 4) { createReq.onreadystatechange = null; Xrm.Utility.closeProgressIndicator(); if (this.status === 200) { //Success - No Return Data - Do Something } else { Xrm.Utility.alertDialog(this.statusText); } } }; createReq.send(JSON.stringify(locationdetails)); },
4. Upload Function
UploadDocument: function (filename, base64PDFString) { var parameters = { "Content": base64PDFString, "Entity": { "@odata.type": "Microsoft.Dynamics.CRM.sharepointdocument", "locationid": "", "title": filename + ".pdf" }, "OverwriteExisting": true, "ParentEntityReference": { "@odata.type": "Microsoft.Dynamics.CRM." + Xrm.Page.data.entity.getEntityName() }, "FolderPath": "" }; parameters["ParentEntityReference"][Xrm.Page.data.entity.getEntityName() + "id"] = Xrm.Page.data.entity.getId(); var req = new XMLHttpRequest(); req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/UploadDocument", 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 (filename.indexOf("OppSummary") == -1) Xrm.Utility.closeProgressIndicator(); if (this.status === 204) { //Success - No Return Data - Do Something } else { Xrm.Utility.alertDialog(this.statusText); } } }; req.send(JSON.stringify(parameters)); } };
As Mention above is not in Steps or Connected, I Will add steps soon. thanks
*This post is locked for comments