Showing posts with label D365FO. Show all posts
Showing posts with label D365FO. Show all posts

Sunday, June 16, 2024

D365FO: Add financial dimension range in Query using X++

protected void createReportLines()
{
	Query                q;
	QueryRun             qr;
	QueryBuildDataSource qbds, qbdsInventTrans;
	RecId                dimAttrRecId = AgreementHeaderExt_RU::getAgreementDimensionAttribute();

	q = new Query();

	qbdsInventTrans = q.addDataSource(tableNum(InventTrans));

	findOrCreateRange_W(qbdsInventTrans, fieldNum(InventTrans, TableId), strFmt(issueReceiptValue,
																				qbdsInventTrans.name(),
																				enum2int(StatusIssue::Sold),
																				enum2int(StatusReceipt::Purchased)));
	findOrCreateRange_W(qbdsInventTrans, fieldNum(InventTrans, DateFinancial), queryRange(commReportJour.StartDate, commReportJour.EndDate));

	qbds = qbdsInventTrans.addDataSource(tableNum(InventTransOrigin));
	qbds.addLink(fieldNum(InventTrans, InventTransOrigin), fieldNum(InventTransOrigin, RecId));
	qbds.joinMode(JoinMode::InnerJoin);
	qbds.fetchMode(QueryFetchMode::One2One);

	qbds = qbds.addDataSource(tableNum(CustInvoiceTrans));
	qbds.addLink(fieldNum(InventTransOrigin, InventTransId), fieldNum(CustInvoiceTrans, InventTransId));
	qbds.addLink(fieldNum(InventTrans, InvoiceId), fieldNum(CustInvoiceTrans, InvoiceId), qbdsInventTrans.name());
	qbds.joinMode(JoinMode::InnerJoin);

	qbds = qbds.addDataSource(tableNum(CustInvoiceJour));
	qbds.relations(true);
	qbds.joinMode(JoinMode::InnerJoin);

	findOrCreateRange_W(qbds, fieldNum(CustInvoiceJour, InvoiceAccount), queryValue(commReportJour.PartnerCode));

	SysQuery::addDimensionAttributeRange(q,
	qbds.name(),
	fieldStr(CustInvoiceJour, DefaultDimension),
	DimensionComponent::DimensionAttribute,
	commReportJour.AgreementId,
	DimensionAttribute::find(dimAttrRecId).Name);

	qbds = qbds.addDataSource(tableNum(CustInvoiceJour_RU));
	qbds.relations(true);
	qbds.joinMode(JoinMode::ExistsJoin);

	findOrCreateRange_W(qbds, fieldNum(CustInvoiceJour_RU, InventProfileType_RU), con2Str([InventProfileType_RU::CommissionAgent,
																					   InventProfileType_RU::CommissionPrincipalAgent]));

	qbds = qbdsInventTrans.addDataSource(tableNum(InventDim));
	qbds.addLink(fieldNum(InventTrans, InventDimId), fieldNum(InventDim, InventDimId));
	qbds.joinMode(JoinMode::InnerJoin);
	qbds.fetchMode(QueryFetchMode::One2One);

	qr = new QueryRun(q);

	while (qr.next())
	{
		inventTrans         = qr.get(tableNum(InventTrans));
		inventTransOrigin   = qr.get(tableNum(InventTransOrigin));
		custInvoiceTrans    = qr.get(tableNum(CustInvoiceTrans));
		custInvoiceJour     = qr.get(tableNum(CustInvoiceJour));
		inventDim           = qr.get(tableNum(inventDim));

		this.processVendShipments();
	}
}

Tuesday, April 16, 2024

Calculate FromDate/ToDate based on Daily,Weelkly,Monthly in X++

boolean canRun = false;
TransDate fromDate, toDate, prevDate;
TransDate currentDate = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());
switch (Reporting.Schedule)
{
	case ReportingSchedule::Daily :
		fromDate = currentDate - 1;
		toDate = currentDate - 1;
		canRun = true;
		break;
	case ReportingSchedule::Weekly :
		PreferredLocale preferredLocale = (new xSession()).PreferredLocale();
		prevDate = HcmDateTimeUtil::calculateDateWithOffset(PeriodUnit::Day,7,false, currentDate);
		fromDate = DateTimeUtil::getStartOfWeekDate(preferredLocale, prevDate);
		toDate   = DateTimeUtil::getEndOfWeekDate(preferredLocale, prevDate);
		canRun   = dayOfWk(currentDate) == 1; //1 for monday
		break;
	case ReportingSchedule::Monthly :
		prevDate = prevMth(currentDate);
		fromDate = DateStartMth(prevDate);
		toDate   = endmth(prevDate);
		canRun   = dayOfMth(currentDate) == 1; //1 for first day of the month
		break;
}

Tuesday, September 26, 2023

Generating 1D or 2D barcode in X++

Barcode barcode = BarcodeCode128::construct();
barcode.string(true, localInventDim.inventSerialId);
BarCodeString barCodeString = barcode.barcodeStr();
public str getBarcode(str _barCodeText)

  {

   BarcodeCode128 barcode;

   barcode = Barcode::construct(BarcodeType::Code128);

   barcode.string(true, _barCodeText);

   barcode.encode();

   return barcode.barcodeStr();

   }

Monday, September 25, 2023

Gets the primary index of a table

// <summary>
    /// Gets the primary index of a table.
    /// </summary>
    /// <param name="_tableName">
    /// A table name.
    /// </param>
    /// <returns>
    /// Returns field id.
    /// </returns>
    public static Container getPrimaryIndex(TableName _tableName)
    {
        SysDictIndex        keyIndex;
        DictField           dictField;
        int                 fieldIndex;
        container           res, isMandatory;
        SysDictTable sysDictTable = new SysDictTable(tableName2id(_tableName));
        if(sysDictTable)
        {
            TableId tableId = sysDictTable.id();
            keyIndex = new SysDictIndex(tableId, sysDictTable.primaryIndex());
            if (keyIndex)
            {
                for (fieldIndex = 1; fieldIndex <= keyIndex.numberOfFields(); fieldIndex++)
                {

                    if (fieldId2name(tableId, keyIndex.field(fieldIndex)) != fieldStr(DMFDefinitionGroupExecution,ExecutionId) &&
                        fieldId2name(tableId, keyIndex.field(fieldIndex)) != fieldStr(DMFDefinitionGroupExecution,DefinitionGroup))
                    {
                        dictField = new DictField(tableId, keyIndex.field(fieldIndex));
                        res += dictField.id();
                        isMandatory += dictField.mandatory();
                    }
                }
            }
        }

        return [res, isMandatory];
    }

Monday, January 23, 2023

Export SSRS report to SharePoint using X++

internal final class RunnableClass1
{   
    /// /// Runs the class with the specified arguments.
    /// The specified arguments.
    public static void main(Args _args)
    {
        DocuType docuType;
        select firstonly * from docuType
                    where docuType.PrintMgmtDocumentType == PrintMgmtDocumentType::SalesOrderInvoice;

        str URI = docuType.sharePointUrl();
        System.UriBuilder builder = new System.UriBuilder(URI);
        str extId = xUserInfo::getExternalId();
        Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider provider;
        Microsoft.Dynamics.AX.Framework.FileManagement.DocumentLocation documentLocation = new Microsoft.Dynamics.AX.Framework.FileManagement.DocumentLocation();       
        provider = new Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider(docuType.Host, docuType.Site, docuType.FolderPath, extId);
        System.Byte[] reportBytes = new System.Byte[0]();
        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        reportBytes = RunnableClass1::renderReportToBinaryArray("100002");
     //   reportBytes = enc.GetBytes("YOUR STRING/TEXT");
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(reportBytes);
        //memoryStream = comma.getStream();
        documentLocation = provider.SaveFile(newGuid(), '100002.PDF', System.Web.MimeMapping::GetMimeMapping('100002.PDF'), memoryStream);
    }

    public static System.Byte[] renderReportToBinaryArray(SalesInvoiceId _salesInvoiceId)
    {
        str                     ret;
        CustInvoiceJour         custInvoiceJour;
        System.Byte[] reportBytes;
        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());
                        
             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 reportBytes;
    }

}

pass marked records to another form in D365FO

[DataSource]
    class ActivityLogDetails
    {
        /// <summary>
        ///
        /// </summary>
        public void init()
        {
            super();

            if (element.args() && element.args().caller() && element.args().record())
            {
                this.query().dataSourceTable(tableNum(ActivityLogDetails)).clearDynalinks();
                helper= MultiSelectionHelper::createFromCaller(element.args().caller());
                helper.createQueryRanges(this.query().dataSourceTable(tablenum(ActivityLogDetails)),fieldstr(ActivityLogDetails, RecId));

                if (element.args().menuItemName() == menuItemDisplayStr(MarkSalesActivityLogReserved))
                {
                    activityLogStatus = ActivityLogStatus::Reserved;
                }
                else if (element.args().menuItemName() == menuItemDisplayStr(MarkSalesActivityLogRejected))
                {
                    activityLogStatus = ActivityLogStatus::Rejected;
                }
                else
                {
                    throw error("@SYS22996");
                }
            }
            else
            {
                throw error(Error::missingRecord(tableId2PName(tableNum(ActivityLogDetails))));
            }

            Ok.enabled(false);
        }

    }

Send Email from D365FO

 public void sendMail()
    {
        SysMailerMessageBuilder messageBuilder = new SysMailerMessageBuilder();
        Email   toEmail;
        Email   fromEmail;
         
        try
        {
            FromEmail = "fromemail@xyz.com";
            toEmail   = "toemail@xyz.com";

            messageBuilder.setBody("Hello from D365", false);
            messageBuilder.setSubject("Email Test from D365");
            messageBuilder.addTo(toEmail);
            // Note: not calling setFrom() defaults to the current user for SMTP client, whereas
            // when sent to Outlook any setFrom() value will be ignored since profiles on the client are used
            messageBuilder.setFrom(fromEmail);

            // Open the generated email in the configured client
            // Sends a message interactively, allowing the user to view and modify the message before
            SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());
            // Try using sendNonInteractive method too
        }
        catch (Exception::Error)
        {
            throw error("@SYS33567");
        }
    }

D365FO: Update inventory marking

if (updateMarking)
{
	InventDim inventDim = InventDim::find(currInventTransferLine.inventDimId);
	InventDimParm inventDimParm;
	inventDimParm.initFromInventDim(inventDim);

	InventTransOriginId receiptInventTransOriginId = InventTransOrigin::findByInventTransId(currInventTransferLine.InventTransId).RecId;

	InventTransOriginId issueInventTransOriginId = InventTransOrigin::findByInventTransId(currPurchLine.InventTransId).RecId;

	qty markedQty = InventTransOrigin::updateMarking(
						receiptInventTransOriginId,
						issueInventTransOriginId,
						-currInventTransferLine.QtyTransfer,
						'',
						SortOrder::Ascending,
						false,
						inventDim,
						inventDimParm);

	if (markedQty)
	{
		markedQty = InventTransOrigin::updateMarking(
						issueInventTransOriginId,
						receiptInventTransOriginId,
						currInventTransferLine.QtyTransfer,
						'',
						SortOrder::Ascending,
						false,
						inventDim,
						inventDimParm);
	}
}

update_recordset using queryrun class in D365FO

//intialize the query
Query                  salesActivityLineQuery = new Query();
QueryBuildDataSource    SalesActivityLineDS = salesActivityLineQuery.addDataSource(tableNum(SalesActivityLine));
SalesActivityLineDS.addRange(fieldNum(SalesActivityLine_DIS, RecId)).value(con2Str(conSalesActivityLineRecId));

//Initialize Map and specify the field and field value to be updated
Map fieldSetMap1 = new Map(Types::String, Types::String);
fieldSetMap1.insert(fieldStr(SalesActivityLine_DIS, Status), any2Str(ActivityLineStatus_DIS::Rejected));

//Update
Query::update_recordset(fieldSetMap1, salesActivityLineQuery);

Tuesday, December 13, 2022

D365FO: Inventory marking between purchase order and transfer order

/// create/Update marking between purhcase order and transfer order
    /// </summary>
    /// <param name = "_inventTransId">receipt InventTrans PO</param>
    /// <param name = "_refInventTransId">Issue InventTrans TO</param>
    /// <param name = "_qtyToMark">qty</param>
    public void updateMarking(InventTransId   _inventTransId,
                                InventTransId   _refInventTransId,
                                Qty             _qtyToMark = 0)
    {
        Qty qtyToMark;
        try
        {
            TmpInventTransMark	  tmpInventTransMark;

            InventTransId         issueInventTransId   = _inventTransId;
            InventTransId         receiptInventTransId = _refInventTransId;

            InventTransOriginId receiptInventTransOriginId = InventTransOrigin::findByInventTransId(receiptInventTransId).RecId;
            InventTrans receiptInventTrans = InventTrans::findByInventTransOrigin(receiptInventTransOriginId);
            
            InventTransOriginId issueInventTransOriginId = InventTransOrigin::findByInventTransId(issueInventTransId).RecId;
            InventTrans issueInventTrans = InventTrans::findByInventTransOrigin(issueInventTransOriginId);
            
            InventTransMarkCollection collection = TmpInventTransMark::markingCollection(
            InventTransOrigin::find(receiptInventTransOriginId), receiptInventTrans.inventDim(), receiptInventTrans.Qty);
 
            collection.insertCollectionToTmpTable(tmpInventTransMark);

            select firstonly tmpInventTransMark
                where tmpInventTransMark.InventTransOrigin == issueInventTrans.InventTransOrigin
                    && tmpInventTransMark.InventDimId       == issueInventTrans.InventDimId;
 
            if (tmpInventTransMark.RecId != 0)
            {
                qtyToMark = issueInventTrans.Qty;
               
                tmpInventTransMark.QtyMarkNow =  qtyToMark;
                tmpInventTransMark.QtyRemain  -= tmpInventTransMark.QtyMarkNow;
              
                Map mapUpdated = new Map(Types::Int64, Types::Record);
                mapUpdated.insert(tmpInventTransMark.RecId, tmpInventTransMark);
 
                TmpInventTransMark::updateTmpMark(
                    receiptInventTransOriginId,
                    receiptInventTrans.inventDim(),
                    -qtyToMark,
                    mapUpdated.pack());
            }
        }
        catch (Exception::Error)
        {
            throw error(strFmt("FailMarkInventtransaction", _refInventTransId));
        }
    }

Monday, December 12, 2022

D365FO IDisposable context class

Scenario: pass additional parameter to a method that doesnt have a parametr signature 
After the execution of using code block , Dispose method will be called.

IDisposible is a singleton instance of a class per session, for example if you open two different tabs and run the code you will get two different instance of the class
class DocTypeFile_CUSTOM_Context implements System.IDisposable
{
    static DocTypeFile_CUSTOM_Context  docTypeFileContext;

    public  boolean overrideDefaultDocType = false;
    public boolean printSalesInvoiceReport;
    public boolean printSalesConfReport;
   // public PrintMgmtDocumentType printMgmtDocumentType;
   public DocuTypeId doucTypeId = strMin();
  
    public void new()
    {
        if(docTypeFileContext)
        {
            throw error("NestingIsNotSupported");
        }
        docTypeFileContext = this;
    }

    public void dispose()
    {
        docTypeFileContext = null;
    }

    static public DocTypeFile_CUSTOM_Context current()
    {
        return  docTypeFileContext;
    }

}
/// <summary>
///     To handle the report design to print based on caller
/// </summary>
[ExtensionOf(classStr(SalesInvoiceController))]
final class SalesInvoiceController_CUSTOM_Extension
{
    /// <summary>
    ///     choose report design
    /// </summary>
    protected void outputReport()
    {
		//initalize disposible context class 
        using (var docTypeFileContext = new DocTypeFile_CUSTOM_Context())
        {
            SRSPrintDestinationSettings srsPrintDestinationSettings = formLetterReport.getCurrentPrintSetting().parmPrintJobSettings();
           
            if (srsPrintDestinationSettings.printMediumType() == SRSPrintMediumType::File)
            {
			   docTypeFileContext.overrideDefaultDocType = true;
               docTypeFileContext.doucTypeId = "File";
            }

            next outputReport();
        }
    }

}
[ExtensionOf(tableStr(DocuType))]
final class DocuType_CUSTOM_Extension
{
    static DocuTypeId typeFile()
    {
        DocuTypeId docuTypeId;
        docuTypeId = next typeFile();

        DocTypeFile_CUSTOM_Context  docTypeFileContext = DocTypeFile_CUSTOM_Context::current();

        if(docTypeFileContext && docTypeFileContext.overrideDefaultDocType)
        {
            docuTypeId = docTypeFileContext.doucTypeId;
        }

        

        return docuTypeId;
    }

}

Monday, December 5, 2022

Release Number sequence X++

  NumberSeq::release(numSeq.parmNumberSequenceCode(), "Number Seq to be released");
Example
  NumberSeq::release("@AR26", CustTable.AccountNum);

Wednesday, November 30, 2022

D365FO: Zip/Unzip memory stream to byte[] array X++

Sometimes we have to deal with big file streams, during that scenario there is an option to zip/unzip the file using gzip in X++.

for example: Pass files larger than 25MB to logic apps, logic app has a file size limit of 25 MB
using System.IO;
using System.IO.Compression;


class ZipUnzip
{
    public static System.Byte[] Compress(System.Byte[] data)
    {
        var compressedStream = new MemoryStream();
        var zipStream = new GZipStream(compressedStream, CompressionMode::Compress);
        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        return compressedStream.ToArray();
    }

    public static System.Byte[] Decompress(System.Byte[] data)
    {
        var compressedStream = new MemoryStream(data);
        var zipStream = new GZipStream(compressedStream, CompressionMode::Decompress);
        var resultStream = new MemoryStream();

        System.Byte[] buffer = new System.Byte[4096]();
        int read;

        do
        {
            read = zipStream.Read(buffer, 0, buffer.Length);
            resultStream.Write(buffer, 0, read);
        }
        while(read);

        return resultStream.ToArray();
    }

}

Thursday, November 24, 2022

D365FO: RESET TTS LEVEL

internal final class resettts
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        while (appl.ttsLevel() > 0)
        {
            info(strfmt("Level %1 aborted",appl.ttsLevel()));
            ttsAbort;
        }
    }

}

D365FO: Test Webservices using SoapUI

 

In soap UI create a new test suite and create a new POST Http request with below values

Request URL: https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/token

client_id : xxxxxxx-xxx-xxxx-xxx-xxxxxxxxxx

client_secret : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Resource : https://onebox.sandbox.operations.dynamics.com

grant_type : client_credentials

 Post Query string : checked

 


Run the request copy the access token from the JSON window into a notepad

Append bearer before the access token

Example

bearer  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCIsImtpZCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCJ9.eyJhdWQiOiJodHRwczovL3RkY2NhZHlwcmVwcm9kLnNhbmRib3gub3BlcmF0aW9ucy5keW5hbWljcy5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9lOGRjZjZlNi0zYWNjLTRhZjktOWNiMi03N2Y2ODhjYjY4OGIvIiwiaWF0IjoxNjQ0NDg3ODcwLCJuYmYiOjE2NDQ0ODc4NzAsImV4cCI6MTY0NDQ5MTc3MCwiYWlvIjoiRTJaZ1lDaWI4ZjNWOUNmL2p1aG5Xd1FzWTNXcUFnQT0iLCJhcHBpZCI6IjEyYzFhY2RmLTAzNjktNDk3OC1hYWQzLTM3OGQxY2I3NTM5ZSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2U4ZGNmNmU2LTNhY2MtNGFmOS05Y2IyLTc3ZjY4OGNiNjg4Yi8iLCJvaWQiOiIzNDJlNDMyOC02ZGM3LTQ1MjItYjcwMS1iOWQ4Yzc1N2NmNzUiLCJyaCI6IjAuQVFzQTV2YmM2TXc2LVVxY3NuZjJpTXRvaXhVQUFBQUFBQUFBd0FBQUFBQUFBQUFMQUFBLiIsInJvbGVzIjpbIkNvbm5lY3Rvci5GdWxsQWNjZXNzIl0sInN1YiI6IjM0MmU0MzI4LTZkYzctNDUyMi1iNzAxLWI5ZDhjNzU3Y2Y3NSIsInRpZCI6ImU4ZGNmNmU2LTNhY2MtNGFmOS05Y2IyLTc3ZjY4OGNiNjg4YiIsInV0aSI6IkJoSjFEaUYxb2thd0NsOURtZVE5QUEiLCJ2ZXIiOiIxLjAifQ.EKQ8IVQEzHmJ5W2L0p80HnPKCP86tOgXyT5FuM4OBDeNotxbSPSXPhqq9CV3qNBSUY9l0KXcbla1rDNd7SrZv079oeOsCZaDoTp4L4D8IeYfTAzoSKhmcm3ljaLZIBw4XWC5kcG1pn_o19uDDj9OzBDM9RzUrfwyy-X-TOewBApQe5oEzhwMoTsFrzod6u_8x_tXtWoqjCfWwzbC7bH9jsDMc3cKX4NdebHDdeklIDY9j1kHc3rTYxDlhcu6kLQeN2WVajuuhs52s56YXfJj4Dpz7alTsfIpHeCc5icnijwJx3BQ03kUH2cqFfl6KttowO-cjiBUix2dX3HqTAfN1Q

 

Copy the access modified text then go to the request and add Authorization into the Header of the request and paste the text as value




 

Also remove the optional tags in the call context.

D365FO:Cancel Purchase order through X++

 Create a new class and extend standard PurchCancel class

class PurchCancel_CUSTOM extends PurchCancel
{
    public void cancelPO(PurchTable _PurchTable)
    {
        PurchCancel_CUSTOM purchCancel = PurchCancel_CUSTOM::construct();
        purchCancel.parmPurchTable(_PurchTable);
       // purchTable = _PurchTable;
        purchCancel.run();
    }

    static PurchCancel_CUSTOM construct()
    {
        return new PurchCancel_CUSTOM();
    }

    void new()
    {
        super();
    }
}

Wednesday, November 16, 2022

SalesInvoice change file name when using print management with File DocumentType

/// <summary>
///     To handle the report design to print based on caller
/// </summary>
[ExtensionOf(classStr(SalesInvoiceController))]
final class SalesInvoiceController_MY_Extension
{
    /// <summary>
    ///     choose report design
    /// </summary>
    protected void outputReport()
    {
        Args controllerArgs = this.parmArgs();
        SRSCatalogItemName  reportDesign;
        if((controllerArgs.menuItemName() == menuItemOutputStr(SalesInvoice_CUSTOM)) || custInvoiceJour.isProforma() || (controllerArgs.menuItemName() == menuItemOutputStr(SalesInvoice)))
        {            
            reportDesign = ssrsReportStr(SalesInvoice_Custom,Report_Custom);
        }
        else 
        {
            reportDesign = ssrsReportStr(SalesInvoice_Custom,Report);
        }
        this.parmReportName(reportDesign);
        this.parmReportContract().parmReportName(reportDesign);

        SRSPrintDestinationSettings srsPrintDestinationSettings = formLetterReport.getCurrentPrintSetting().parmPrintJobSettings();
        SRSPrintMediumType srsPrintMediumType = srsPrintDestinationSettings.printMediumType();
        formletterReport.parmReportRun().settingDetail().parmReportFormatName(reportDesign);

        if (srsPrintDestinationSettings.printMediumType() == SRSPrintMediumType::File)
        {
            srsPrintDestinationSettings.fileName(custInvoiceJour.InvoiceId);
        }
        srsPrintDestinationSettings.overwriteFile(true);

        next outputReport();
    }

Wednesday, June 9, 2021

How to add reference fields in forms that don't have a data source

 

Create a temp table with reference fields you wanted 


Add the Temp table as a data source in the required from without any join source


To initialize values when opening form

    [FormDataSourceEventHandler(formDataSourceStr(PdsResetVendorBatchDetails, PdsVendBatchInfo), FormDataSourceEventType::Initialized)]
    public static void PdsVendBatchInfo_OnInitialized(FormDataSource sender, FormDataSourceEventArgs e)
    {
            FormRun formRun = sender.formRun() as FormRun;

            switch (formRun.args().dataset())
            {
                case tableNum(InventBatch) :

                    InventBatch  inventBatch = formRun.args().record() as InventBatch;

                    PdsVendBatchInfoTMP PdsVendBatchInfo1 = sender.cursor();


                    FormReferenceControl Manufact = formRun.design().controlName(formControlStr(PdsResetVendorBatchDetails, PdsVendBatchInfo_Manufact)) as FormReferenceControl;
                    FormReferenceControl ManufactSite = formRun.design().controlName(formControlStr(PdsResetVendorBatchDetails, PdsVendBatchInfo_ManufactSite)) as FormReferenceControl;
                
                    PdsVendBatchInfo1.Manufact = inventBatch.Manufact;
                    PdsVendBatchInfo1.ManufactSite = inventBatch.ManufactSite;

                    PdsVendBatchInfo1.doInsert();
                
                    sender.setRecord(PdsVendBatchInfo1);

                    Manufact.value(inventBatch.Manufact);
                    ManufactSite.value(inventBatch.ManufactSite);
                    break;
            }
    }

 

Lookup

public static void dirPartyLocationLookup(FormReferenceGroupControl _ctrl, DirPartyRecId _party)
    {
        container               conLocationRoles;
        LogisticsLocationRole   logisticsLocationRole;
        QueryBuildDataSource    qbdsDirPartyLocation, qbdsDirPartyLocationRole;

        Query   query = new Query();
        SysReferenceTableLookup sysTableLookup = SysReferenceTableLookup::newParameters(tablenum(DirPartyLocation), _ctrl);

        while select RecId from LogisticsLocationRole
            where LogisticsLocationRole.IsManufactSite
        {
            conLocationRoles += LogisticsLocationRole.RecId;
        }

        sysTableLookup.addLookupfield(fieldNum(DirPartyLocation, Location));
        sysTableLookup.addLookupfield(fieldNum(DirPartyLocation, Party));
        
        qbdsDirPartyLocation = query.addDataSource(tablenum(DirPartyLocation));
        
        qbdsDirPartyLocationRole = qbdsDirPartyLocation.addDataSource(tablenum(DirPartyLocationRole));
        qbdsDirPartyLocationRole.joinMode(JoinMode::ExistsJoin);
        qbdsDirPartyLocationRole.relations(true);

        qbdsDirPartyLocationRole.addRange(fieldNum(DirPartyLocationRole, LocationRole)).value(con2Str(conLocationRoles));
       
        if(_party)
        {
            qbdsDirPartyLocation.addRange(fieldNum(DirPartyLocation, Party)).value(queryValue(_party));

            qbdsDirPartyLocation.addRange(fieldNum(DirPartyLocation, Location)).value(SysQuery::valueNot(0));
        }
        else
        {
            qbdsDirPartyLocation.addRange(fieldNum(DirPartyLocation, Party)).value(SysQuery::valueEmptyString());
        }

        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
    }

    public static void DirPartyIdLookup(FormControl _ctrl)
    {
        Query   query = new Query();

        SysReferenceTableLookup sysTableLookup = SysReferenceTableLookup::newParameters(tablenum(DirPartyTable), _ctrl);

        sysTableLookup.addLookupfield(fieldNum(DirPartyTable, PartyNumber));
        sysTableLookup.addLookupfield(fieldNum(DirPartyTable, Name));

        query.addDataSource(tablenum(DirPartyTable));
        
        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
    }

Tuesday, May 25, 2021

Set Financial Dimensions by X++ code in AX 2012/Setting one Dimension value in the combination

    /// <summary>
    /// replace specific financial dimension value in DefaultDimension based on the LedgerParameters setup
    /// </summary>
    /// <param name = "_defaultDimensionFrom">DefaultDimension recId the value should be taken from</param>
    /// <param name = "_defaultDimensionTo">DefaultDimension recId the value should be assigned to</param>
    /// <returns>returns new DefaultDimension recId if conditions are met</returns>
    public static DimensionDefault replaceDefaultDim(DimensionDefault _defaultDimensionFrom, DimensionDefault _defaultDimensionTo)
    {
        if(!_defaultDimensionFrom)
        {
            return _defaultDimensionTo;
        }

        LedgerParameters ledgerParameters = LedgerParameters::find();

        if (ledgerParameters.DepartmentSetFinancialDimension &&
            ledgerParameters.DepartmentDimensionAttribute)
        {
            DimensionAttribute                  dimAttr;
            DimensionAttributeValue             dimAttrValue;
            DimensionAttributeValueSetStorage   davss;

            davss = DimensionAttributeValueSetStorage::find(_defaultDimensionTo);

            dimAttr = DimensionAttribute::find(ledgerParameters.DepartmentDimensionAttribute);

            DimensionAttributeValueSetStorage dimStorage = DimensionAttributeValueSetStorage::find(_defaultDimensionFrom);
            DimensionValue dimValue = dimStorage.getDisplayValueByDimensionAttribute(dimAttr.RecId);

            dimAttrValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttr, dimValue);

            if(dimAttrValue && !davss.containsDimensionAttributeValue(dimAttrValue.RecId))
            {
                davss.addItem(dimAttrValue);

                return davss.save();
            }
        }

        return _defaultDimensionTo;
    }

Friday, April 30, 2021

Conversion from UTCDateTime to Date or Time in AX

Here is an example of correct conversion between UTCDateTime value and Date and Time value which is associated with user preferred time zone:
public static void testDateTimeConversion()
{
    utcDateTime dateTime;
    date dateInUserTimeZone;
    TimeOfDay timeInUserTimeZone;

    dateTime = DateTimeUtil::utcNow();

    dateInUserTimeZone = DateTimeUtil::date(DateTimeUtil::applyTimeZoneOffset(dateTime, DateTimeUtil::getUserPreferredTimeZone()));
    timeInUserTimeZone = DateTimeUtil::time(DateTimeUtil::applyTimeZoneOffset(dateTime, DateTimeUtil::getUserPreferredTimeZone()));

    dateTime = DateTimeUtil::newDateTime(dateInUserTimeZone, timeInUserTimeZone, DateTimeUtil::getUserPreferredTimeZone());
}

Table browser URL in D365FO

Critical Thinking icon icon by Icons8