Wednesday, 17 October 2018

Send file to temp blob storage in #MSDyn365FO

In this post I will talk about sending a file to a temporary blob storage. A little warning before I get into it.

This is using the Microsoft’s blob storage that is provisioned for us. I haven’t given it a lot of thought on how it would behave in production. Take it at your own risk.

Lets start by looking back on a couple of posts last month on printing a report to a byte array.

http://dynamicsnavax.blogspot.com/2018/09/print-report-as-byte-array-via-x-in.html

http://dynamicsnavax.blogspot.com/2018/09/alternate-way-to-print-report-as-byte.html

You can use those sample pieces of code to get a report as a stream and send it to the below code.

if (stream)
{
    str fileName = 'myfile';
    str contentType = 'application/pdf';
    str fileExtension = SRSPrintDestinationSettings::findFileNameType(SRSReportFileFormat::PDF, SRSImageFileFormat::BMP);

    FileUploadTemporaryStorageStrategy fileUploadStrategy = new FileUploadTemporaryStorageStrategy();
    FileUploadTemporaryStorageResult fileUploadResult = fileUploadStrategy.uploadFile(stream, fileName + fileExtension, contentType , fileExtension);

    if (fileUploadResult == null || !fileUploadResult.getUploadStatus())
    {
        warning("@ApplicationPlatform:FileUploadFailed");
    }
    else
    {
        downloadUrl = fileUploadResult.getDownloadUrl();
        if (downloadUrl == "")
        {
            throw Exception::Error;
        }
    }
}

A download URL will be generated for you. The URL is going to be public and with an expiration (15 minutes I believe).

Below is an error if you try to access it after the expiration period.

image

Monday, 15 October 2018

Find TableId using table browser #MSDyn365FO

I am usually doing this from the development environment. However, I was debugging a customer environment where I only had access to the front end. I had a table that only gave me the RefTableId. I needed to find out the table that record related to.

I used SysTableIdView from table browser. Here is the link.

http://usnconeboxax1aos.cloud.onebox.dynamics.com/?cmp=usmf&mi=SysTableBrowser&TableName=SysTableIdView

image

Sunday, 30 September 2018

Send to Azure Service Bus in #MSDyn365FO

Sending a message to Azure Service Bus is really simple in FinOps.

Below is the job I wrote to send a message to the service bus. It takes a connection string and a queue name for connecting. The message string and key value pair list can be supplied to the properties.


    static str connectionString = 'Endpoint=sb://navaxservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=h5KwXSEFIHxxxxxxxxxxxxxxxxxx';
    static str queueName = 'navaxqueue';

    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        if (connectionString && queueName)
        {
            Microsoft.ServiceBus.Messaging.QueueClient queueClient = Microsoft.ServiceBus.Messaging.QueueClient::CreateFromConnectionString(connectionString, queueName);
            Microsoft.ServiceBus.Messaging.BrokeredMessage brokeredMessage = new Microsoft.ServiceBus.Messaging.BrokeredMessage("My Message");
            
            var properties = brokeredMessage.Properties;

            properties.Add("MyKey1", "MyValue1");
            properties.Add("MyKey2", "MyValue2");
            
            queueClient.Send(brokeredMessage);
        }
    }

Using Service Bus Explorer you can see the result.

image

At the moment Microsoft is working on event based triggers. One of the possible solutions they presented was writing to the service bus. Looking forward to it.

I took inspiration from one of the standard classes I noticed in in 8PU15. It subscribes to the insert/delete of a user record to send the user detail to a service bus. The big bonus is that service bus assembles are included on the machine. I won’t dive any deeper into this class in this blog post.

image

Thursday, 27 September 2018

Alternate way to print a report as a byte array via X++ in #MSDyn365FO

Earlier this month I posted on how to print a report as a byte array. I will do the same but using an alternative method. I will use the print archive instead.

You need to create an extension class for the SRSPrintArchiveContract class to add a parm method for the RecId.

[ExtensionOf(classStr(SRSPrintArchiveContract))]
final class SRSPrintArchiveContract_NAVAX_Extension
{
    public RefRecId    navaxPrintJobHeaderRecId;

    public RefRecId parmNAVAXPrintJobHeaderRecId(RefRecId _navaxPrintJobHeaderRecId = navaxPrintJobHeaderRecId)
    {
        navaxPrintJobHeaderRecId = _navaxPrintJobHeaderRecId;
        return navaxPrintJobHeaderRecId;
    }

    public RecId savePrintArchiveDetails(container binData)
    {
        RecId recId = next savePrintArchiveDetails(binData);

        this.parmNAVAXPrintJobHeaderRecId(recId);

        return recId;
    }

}

This is the alternative method I wrote.


    public static str printSalesInvoiceBase64StrV2(SalesInvoiceId _salesInvoiceId)
    {
        str                     ret;
        CustInvoiceJour         custInvoiceJour;

        select firstonly custInvoiceJour
            where custInvoiceJour.InvoiceId == _salesInvoiceId;

        if (custInvoiceJour)
        {
            str ext = SRSPrintDestinationSettings::findFileNameType(SRSReportFileFormat::PDF, SRSImageFileFormat::BMP);
            PrintMgmtReportFormatName printMgmtReportFormatName = PrintMgmtDocType::construct(PrintMgmtDocumentType::SalesOrderInvoice).getDefaultReportFormat();
                                     
            SalesInvoiceContract salesInvoiceContract = new SalesInvoiceContract();
            salesInvoiceContract.parmRecordId(custInvoiceJour.RecId);

            SrsReportRunController  srsReportRunController = new SrsReportRunController();
            srsReportRunController.parmReportName(printMgmtReportFormatName);
            srsReportRunController.parmExecutionMode(SysOperationExecutionMode::Synchronous);
            srsReportRunController.parmShowDialog(false);
            srsReportRunController.parmReportContract().parmRdpContract(salesInvoiceContract);

            SRSPrintDestinationSettings printerSettings = srsReportRunController.parmReportContract().parmPrintSettings();
            printerSettings.printMediumType(SRSPrintMediumType::Archive);
            printerSettings.fileFormat(SRSReportFileFormat::PDF);
            printerSettings.parmFileName(custInvoiceJour.InvoiceId + ext);
            printerSettings.overwriteFile(true);
                    
            srsReportRunController.startOperation();

            RefRecId printJobHeaderRecId = printerSettings.parmSRSPrintArchiveContract().parmNAVAXPrintJobHeaderRecId();

            if (printJobHeaderRecId)
            {
                DocuRef        docuRef;
            
                select firstonly docuRef
                    where docuRef.RefRecId == printJobHeaderRecId && 
                        docuRef.ActualCompanyId == curExt();
                                           
                BinData binData = new BinData();
                binData.setData(DocumentManagement::getAttachmentAsContainer(docuRef));
                ret = binData.base64Encode();
            }
        }

        return ret;
    }

Note that it will pop up with an info log saying it got sent to print archive.

image

If you navigate to the print archive, you will see the record.

image

I don’t mind either way. The first method looks messy with calling some dlls like the SRSProxy etc.

The second method adds overhead by sending to the print archive table. Over time, some cleaning up has go on here.

Wednesday, 12 September 2018

Gotcha with Extending Retail Channel transaction table

I will start by pointing you to a good article Andreas Hofmann from Microsoft has written. It steps you through what you need to extend a transactional table in the Retail Channel and bring that back to HQ via the P Job.

https://dynamicsnotes.com/extending-a-transactional-retail-channel-table-with-additional-data-hq-x-table-extension-cdx-extension-table-crt-data-service/

Now to summerise the issue I faced recently (being a retail rookie).

Following the blog post I created a custom Int64 field on the RetailTransactionSalesTrans. However, when I ran the P job it failed with this error.

“Failed to convert parameter value from a String to a Int64”

I did some investigation by trying to find out what it is actually doing. Essentially the job will do an outer join to your custom extension table. Even though your custom field is 0 by default. You won’t be creating an extension record for every single transaction record. The p job will do an outer join between RetailTransactionSalesTrans to your custom CustomRetailTransSalesTrans, you will notice some blanks in your file that is coming to HQ.

See figure below what the file looks like.

image

Remember also, that the sync happens by downloading and uploading flat files. That is why you have it trying to convert from string to int64. Hence, the error.

You can see the files by going to the Upload sessions and downloading the zip file.

image

As a colleague told me today. The advice is, use a string and treat it as a string from Channel to HQ.

Friday, 7 September 2018

Print a report as a byte array via X++ in #MSDyn365FO

In the last post I showed how to print the sales invoice as a pdf. In this post we will do the same but generate a byte array of the pdf report.

I tried to make the code as readable as possible and hopefully can use it on other reports..


    public static str printSalesInvoiceBase64Str(SalesInvoiceId _salesInvoiceId)
    {
        str                     ret;
        CustInvoiceJour         custInvoiceJour;

        select firstonly custInvoiceJour
            where custInvoiceJour.InvoiceId == _salesInvoiceId;

        if (custInvoiceJour)
        {       
            str ext = SRSPrintDestinationSettings::findFileNameType(SRSReportFileFormat::PDF, SRSImageFileFormat::BMP);
            PrintMgmtReportFormatName printMgmtReportFormatName = PrintMgmtDocType::construct(PrintMgmtDocumentType::SalesOrderInvoice).getDefaultReportFormat();     
                                                                                                        
            SalesInvoiceContract salesInvoiceContract = new SalesInvoiceContract();
            salesInvoiceContract.parmRecordId(custInvoiceJour.RecId);            

            SrsReportRunController  srsReportRunController = new SrsReportRunController();
            srsReportRunController.parmReportName(printMgmtReportFormatName);
            srsReportRunController.parmExecutionMode(SysOperationExecutionMode::Synchronous);
            srsReportRunController.parmShowDialog(false);            
            srsReportRunController.parmReportContract().parmRdpContract(salesInvoiceContract);
            srsReportRunController.parmReportContract().parmReportExecutionInfo(new SRSReportExecutionInfo());
            srsReportRunController.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());

            SRSPrintDestinationSettings printerSettings = srsReportRunController.parmReportContract().parmPrintSettings();
            printerSettings.printMediumType(SRSPrintMediumType::File);
            printerSettings.fileFormat(SRSReportFileFormat::PDF);        
            printerSettings.parmFileName(custInvoiceJour.InvoiceId + ext);
            printerSettings.overwriteFile(true);
                                               
            SRSReportRunService srsReportRunService = new SrsReportRunService();
            srsReportRunService.getReportDataContract(srsReportRunController.parmReportContract().parmReportName());
            srsReportRunService.preRunReport(srsReportRunController.parmReportContract());
            Map reportParametersMap = srsReportRunService.createParamMapFromContract(srsReportRunController.parmReportContract());
            Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[]  parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);

            SRSProxy srsProxy = SRSProxy::constructWithConfiguration(srsReportRunController.parmReportContract().parmReportServerConfig());
                        
            System.Byte[] reportBytes = srsproxy.renderReportToByteArray(srsReportRunController.parmreportcontract().parmreportpath(),
                                            parameterValueArray,
                                            printerSettings.fileFormat(),
                                            printerSettings.deviceinfo());
 
            if (reportBytes)
            {
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(reportBytes))
                {
                    ret = System.Convert::ToBase64String(memoryStream.ToArray());
                }
            }
        }

        return ret;
    }


Printing the byte array string as an info log looks like this.

image


To test the encoding and decoding, I have used online tools like this:

https://www.freeformatter.com/base64-encoder.html


Other sources for your reference:

https://meritsolutions.com/render-report-memory-stream-d365-aka-ax7/

https://d365technext.blogspot.com/2018/07/email-ssrs-report-as-attachment-d365fo.html


I will continue this series of posts to some exciting capabilities. Until next time, enjoy.

Tuesday, 4 September 2018

Print a Sales Invoice via X++ in #MSDyn365FO

Often you want to print a report via X++. One of the more common reports is the sales invoice.

Below is some code you could use to download a pdf copy. I am just picking the first invoice and printing to pdf.

Next few posts will be dependent on this. I will try to build up the scenario. Smile


    public static void printSalesInvoice()
    {
        CustInvoiceJour         custInvoiceJour;
      
        select firstonly custInvoiceJour
            where custInvoiceJour.SalesId != '';

        if (custInvoiceJour)
        {
            str ext = SRSPrintDestinationSettings::findFileNameType(SRSReportFileFormat::PDF, SRSImageFileFormat::BMP);            
            PrintMgmtReportFormatName printMgmtReportFormatName = PrintMgmtDocType::construct(PrintMgmtDocumentType::SalesOrderInvoice).getDefaultReportFormat();
                                     
            SalesInvoiceContract salesInvoiceContract = new SalesInvoiceContract();
            salesInvoiceContract.parmRecordId(custInvoiceJour.RecId);

            SrsReportRunController  srsReportRunController = new SrsReportRunController();
            srsReportRunController.parmReportName(printMgmtReportFormatName);
            srsReportRunController.parmExecutionMode(SysOperationExecutionMode::Synchronous);
            srsReportRunController.parmShowDialog(false);
            srsReportRunController.parmReportContract().parmRdpContract(salesInvoiceContract);

            SRSPrintDestinationSettings printerSettings = srsReportRunController.parmReportContract().parmPrintSettings();
            printerSettings.printMediumType(SRSPrintMediumType::File);
            printerSettings.fileFormat(SRSReportFileFormat::PDF);
            printerSettings.parmFileName(custInvoiceJour.InvoiceId + ext);
            printerSettings.overwriteFile(true);
                    
            srsReportRunController.startOperation();
        }
    }