Search your query

Wednesday, February 15, 2017

Convert SSRS report to PDF file in AX 7 (Dynamics 365)

    /// <summary>
    /// SSRS to PDF
    /// </summary>
    public static void main(Args _args)
    {
        SrsReportRunController          controller = new SrsReportRunController();
        CustTransListContract            rdpContract = new CustTransListContract();
        SRSPrintDestinationSettings     settings;

        try
        {
            // Define report and report design to use
            controller.parmReportName(ssrsReportStr(CustTransList, Report));
            // Use execution mode appropriate to your situation
            //  controller.parmExecutionMode(SysOperationExecutionMode::ScheduledBatch);
            // Suppress report dialog
            controller.parmShowDialog(false);

            // Explicitly provide all required parameters
            controller.parmReportContract().parmRdpContract(rdpContract);

            // Change print settings as needed
            settings = controller.parmReportContract().parmPrintSettings();
            settings.printMediumType(SRSPrintMediumType::File);
            settings.fileFormat(SRSReportFileFormat::PDF);
            settings.fileName(@'d:\SSRS\CustTrans_SSRS.pdf');

            // Execute the report
            //controller.startOperation();
            controller.runReport();
        }
        catch( Exception::Error)
        {
            error("Conversion error");
        }
    }

Tuesday, February 14, 2017

X++ code to browse only Excel File type in browser from AX365 form:



** Need to create a class and extend the FileUploadTemporaryStorageStrategy class.

/// <summary>
/// File upload strategy for Excel files.
/// </summary>

class ExcelFileUploadTemporaryStorageStrategy extends FileUploadTemporaryStorageStrategy
{
    public str allowedFileTypes()
    {
        return ".xlsx,.xls";
    }

}


** Add this class as parameter in FileUploadTemporaryStorageResult class.


FileUploadTemporaryStorageResult result = File::GetFileFromUser(classStr(ExcelFileUploadTemporaryStorageStrategy)) as FileUploadTemporaryStorageResult;

Thursday, February 9, 2017

X++ Code to upload and read the Excel File in Dynamics 365 (Excel Import)

// <summary>
/// Upload and Read the Excel File in Dynamics 365
/// </summary>

        public void uploadAndReadExcelFile()
        {
            FileUploadTemporaryStorageResult result = File::GetFileFromUser() as FileUploadTemporaryStorageResult;

            if (result && result.getUploadStatus())
            {
                str ret;

                using (var package = new OfficeOpenXml.ExcelPackage(result.openResult()))
                {
                    var worksheets = package.get_Workbook().get_Worksheets();
                    var worksheet = worksheets.get_Item(1);
                    var cells = worksheet.get_Cells();
                    var cell = cells.get_Item(1,1);
                    ret = cell.get_Value();
                }

                info(ret);
            }

        }

X++ Code to create and write the Excel File in Dynamics 365 (Excel Export)


/// <summary>
/// Create and Download the Excel file.
/// </summary>

        public void createAndDownloadExcelFile()
        {
            DocuFileSaveResult saveResult = DocuFileSave::promptForSaveLocation("@ApplicationPlatform:OfficeDefaultWorkbookFileName", "xlsx", null, "Testing excel export");
         
            if (saveResult && saveResult.parmAction() != DocuFileSaveAction::Cancel)
            {
                saveResult.parmOpenParameters('web=1');
                saveResult.parmOpenInNewWindow(false);

                System.IO.Stream workbookStream = new System.IO.MemoryStream();
             
             
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

                using (var package = new OfficeOpenXml.ExcelPackage(memoryStream))
                {
                    var worksheets = package.get_Workbook().get_Worksheets();
                    var worksheet = worksheets.Add("First sheet");
                    var cells = worksheet.get_Cells();
                    var cell = cells.get_Item(1,1);
                    cell.set_Value("MyColumnTitle");

                    package.Save();
                }

                memoryStream.Seek(0, System.IO.SeekOrigin::Begin);

                DocuFileSave::processSaveResult(memoryStream, saveResult); // Download the file.
            }
        }

Thursday, February 2, 2017

Download the file into Specific local system directory from file management URL

public static void main(Args _args)
{
        DocuRef                     docuReference;
        DocuValue                   docuValue;
        DocuAction                  docuActionClass;
        str                               url;
        Browser                     br = new Browser();
        var                         generator = new Microsoft.Dynamics.AX.Framework.Utilities.UrlHelper.UrlGenerator();

       
       docuReference = DocuRef::find(curExt(), RefRecId) // select the DocuRef table buffer record.

        if(docuReference)
        {
                docuValue = docuReference.docuValue();               
                 url = docuValue.Path;

                if (!url || docuValue.Type == DocuValueType::Others)
                {
                    str accessToken = DocumentManagement::createAccessToken(docuReference);
                    url =           Microsoft.Dynamics.AX.Framework.FileManagement.URLBuilderUtilities::GetDownloadUrl(docuValue.FileId, accessToken);
                } // getting only file management URL without Host.

                var currentHost   = new System.Uri(UrlUtility::getUrl());

                generator.HostUrl = currentHost.GetLeftPart(System.UriPartial::Authority);  
               // this above code is used to find the Host URL; for example, url = "https:usnconeboxax1aos.cloud.onebox.dynamics.com/"; 

                url = generator.HostUrl+"/"+ url;
  
                System.Net.WebClient wc = new System.Net.WebClient();

                wc.DownloadFile(url, @"C:\myfile.xlsx"); // specify the file path in second parameter.


If you want to convert this file into IO Stream (Memory stream): Use below code.

               System.IO.Stream        stream = File::UseFileFromURL(url);

Convert this stream into file again:

              var fileStream = new System.IO.FileStream(@"C:\myfile1.xlsx.", System.IO.FileMode::Create, System.IO.FileAccess::Write);
                stream.CopyTo(fileStream);

          }
}

X++ code to create file management URL and download the file from Browser

public static void main(Args _args)
{
        DocuRef                     docuReference;
        DocuValue                   docuValue;
        DocuAction                  docuActionClass;
        str                         url;
        Browser                     br = new Browser();
         

        docuReference = DocuRef::find(curExt(), RefRecId) // select the DocuRef table buffer record.

        if(docuReference)
        {
                docuValue = docuReference.docuValue();              
                 url = docuValue.Path;

                if (!url || docuValue.Type == DocuValueType::Others)
                {
                    str accessToken = DocumentManagement::createAccessToken(docuReference);
                    url =           Microsoft.Dynamics.AX.Framework.FileManagement.URLBuilderUtilities::GetDownloadUrl(docuValue.FileId, accessToken);
                }

               if(url)
              {
                     br.navigate(url, false, false); // This code is used to download the file from browser.
              }

Wednesday, February 1, 2017

Code to Convert Binary Stream into PDF file


    /// <summary>
    /// base64 (Binary) to PDF Converter
    /// </summary>

    public static void base642PDFConverter(Str _baseContent)
    {
        System.Byte[] pdfDocBuffer;
        System.IO.FileInfo fi_pdfDoc;
        System.IO.FileStream fs;
        str Content;
        ;
        // Grant clrinterop permission.
        new InteropPermission(InteropKind::ClrInterop).assert();

        pdfDocBuffer = System.Convert::FromBase64String(_baseContent);

        fi_pdfDoc = new System.IO.FileInfo(@'d:/SSRS/TestConversion.pdf');

        fs= new System.IO.FileStream(fi_pdfDoc.get_FullName(), System.IO.FileMode::Create,
        System.IO.FileAccess::Write);

        fs.Write(pdfDocBuffer, 0, pdfDocBuffer.get_Length());

        info("PDF is created in specified folder path.");

        fs.Close();

        //Revert the access
        CodeAccessPermission::revertAssert();
    }

Code to convert PDF file into Binary Stream


     /// <summary>
    /// PDF to base64 (Binary) Converter
    /// </summary>

    public static void main(Args args) //PDF2base64Converter
    {
        System.Byte[] pdfDocBuffer;
        System.IO.FileInfo fi_pdfDoc;
        System.IO.FileStream fs;
        str Content;
 
        // Grant clrinterop permission.
        new InteropPermission(InteropKind::ClrInterop).assert();

        //Load the file
        fi_pdfDoc = new System.IO.FileInfo(@'d:/SSRS/CustTrans_SSRS.pdf');

        //Initiallize the byte array by setting the length of the file
        pdfDocBuffer= new System.Byte[int642int(fi_pdfDoc.get_Length())]();

        // Stream the file
        fs= new System.IO.FileStream(fi_pdfDoc.get_FullName(), System.IO.FileMode::Open,        
        System.IO.FileAccess::Read);

        fs.Read(pdfDocBuffer, 0, pdfDocBuffer.get_Length());

        // Convert the file into a base64 string
        Content = System.Convert::ToBase64String(pdfDocBuffer, 0, pdfDocBuffer.get_Length());

        //Revert the access
        CodeAccessPermission::revertAssert();

        info(Content);
   }