web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Asyc call returning status = 0 and Readystate = 1

(0) ShareShare
ReportReport
Posted on by 410

I am trying to generate a PDF using the reporting server URL, but my api call returns a 0 status at the method 

"encodePdf(responseSession)", which makes it skip the CreateNote method that should have been triggered.
// JavaScript source code
var reportName = "ACCOUNT2.rdl";  //Name of your invoice report
var reportGuid = "f9d93a99-f194-e911-a995-00224800c1e9"; //GUID of your invoice report


function runReportToPrint() {

    var AccountName = Xrm.Page.getAttribute("name").getValue();
    var generatepdf = Xrm.Page.getAttribute("new_generatepdf").getValue();
    if (generatepdf == 1) {
       // AccountName = AccountName.substring(4, 9);
        var params = 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=" + AccountName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";
        window.open(newPth, "_self");
        encodePdf(params);
    }
    else {
        return;
    }
}

function getReportingSession() {
    var recordId = Xrm.Page.data.entity.getId();
    recordId = recordId.replace('{', '').replace('}', '');
   
    var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='account'><all-attributes /><filter type='and'><condition attribute='accountid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>";

    // URL of the report server which will execute report and generate response.
    var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

     //Prepare request object to execute the report.
    var retrieveEntityReq = new XMLHttpRequest();

    retrieveEntityReq.open("POST", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     //Prepare query to execute report.
    var query = "id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:CRM_FilteredAccount=" + strParameterXML;
    //This statement runs the query and executes the report synchronously.
    retrieveEntityReq.send(query);

    //These variables captures the response and returns the response in an array.
    var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
    var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

    var ret = new Array();
    ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);
    ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

    return ret;
}


function encodePdf(responseSession) {

    //Create request object that will be called to convert the response in PDF base 64 string
    var retrieveEntityReq = new XMLHttpRequest();

     //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=" + responseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
    retrieveEntityReq.open("GET", pth, true);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.responseType = "arraybuffer";
    retrieveEntityReq.onreadystatechange = 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]);
            }
            var base64PDFString  = btoa(binary);
            createNote(base64PDFString );
        }
    };
    //This statement sends the request for execution asynchronously. Callback function will be called on completion of the request.
    retrieveEntityReq.send();
}

function createNote(data) {


    var recordId = Xrm.Page.data.entity.getId();
    recordId = recordId.replace('{', '').replace('}', '');

    var AccountName = Xrm.Page.getAttribute("name").getValue();
   // AccountName = AccountName.substring(4, 9);

    var refInvoice = new Object();
    refInvoice.LogicalName = "account";
    refInvoice.Id = recordId;
    var note =
    {
        "objectid": recordId,
        "objecttypecode":"account",
        "filename": AccountName + ".pdf",
        "subject": "Account: " + AccountName,
        "documentbody": data,
        "mimetype": "application/pdf"      
    }
    
    Xrm.WebApi.createRecord("annotation", note).then(
        function success(result) {
            console.log("note created with ID: " + result.id);
            Xrm.Page.data.refresh(false);
            // perform operations on record creation
        },
        function (error) {
            console.log(error.message);
            // handle error conditions
        }
    );
    
}



Please look at my code above.

*This post is locked for comments

I have the same question (0)
  • Victor Onyebuchi Profile Picture
    410 on at

    Kokulan  please look at my code above. Cheers 

  • Victor Onyebuchi Profile Picture
    410 on at

    And the response in the WEBApi call is below:

    onabort: null
    onerror: null
    onload: null
    onloadend: null
    onloadstart: null
    onprogress: null
    onreadystatechange: Æ’ ()
    ontimeout: null
    readyState: 1
    response: null
    responseText: (...)
    responseType: "arraybuffer"
    responseURL: ""
    responseXML: (...)
    status: 0
    statusText: ""
    timeout: 0
    upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
    withCredentials: false
    _async: true
    _headers: ["Accept"]
    _url: "ephraiminc.crm11.dynamics.com/Reserved.ReportViewerWebControl.axd
    ↵
    ↵
    ↵<html>
    ↵<head>
    ↵&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID= HTML>
    ↵
    ↵
    ↵<html>
    ↵<head>
    ↵<scr&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF"
    __proto__: XMLHttpRequest

    I must say, when i copy the url and paste it in the browser, it returns this error -"An error has occurred. 

    Try this action again. If the problem continues, check the Microsoft Dynamics 365 Community for solutions or contact your organization's Microsoft Dynamics 365 Administrator. Finally, you can contact Microsoft Support."

    Is that the first POST method in the getReportingSession() returned the wrong response item?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans