Thursday, July 20, 2023

If condition in computed column.

If Condition in Computed Column

If Condition in Computed Column

Hi all,

Here, we will see how to use the if condition in a computed column. In my requirement, I want to return 0 if RefType is SaftyInvent; otherwise, the value of future days from the same view.

For detailed understanding about computed columns, please check the previous blog.

TestReqTransView is a view created using the ReqTrans table.

X++ Code

private static server str compColumnDelayDays()
{
    DictView reqTransView = new DictView(tableNum(TestReqTransView));
    str reqTransDs = reqTransView.query().dataSourceTable(tableNum(ReqTrans)).name();

    return SysComputedColumn::if(
        SysComputedColumn::equalExpression(
            SysComputedColumn::comparisonField(
                dataentityviewstr(TestReqTransView),
                reqTransDs,
                fieldStr(ReqTrans, Reftype)
            ),
            SysComputedColumn::comparisonLiteral(ReqRefType::SafetyInvent)
        ),
        '0',
        SysComputedColumn::returnField(
            tableStr(TestReqTransView),
            reqTransDs,
            fieldId2name(tableNum(TestReqTransView), fieldNum(TestReqTransView, FUTURESDAYS))
        )
    );
}
    

Mark invent quantity in D365FO using X++

   

Hi All,
Below is the code to mark sales line with correspond Purch line. I used this for completing the marking for migrated purchase line.

X++ Code

 /// <summary>
 /// Mark sales line with purch line
 /// </summary>
 /// <param name = "_issueInventTransId">SalesLine inventrans Recid</param>
 /// <param name = "_receiptInventTransId">PurchLine inventtrans RecId</param>

 public static void completeInventMarking(InventTransId _issueInventTransId, InventTransId _receiptInventTransId)
    {

        InventTransId       issueInventTransId   = _issueInventTransId;
        InventTransId       receiptInventTransId = _receiptInventTransId;
        TmpInventTransMark  tmpInventTransMark;
        Map                 mapUpdated;

        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)
{
            Qty qtyToMark = issueInventTrans.Qty;

            tmpInventTransMark.QtyMarkNow =  qtyToMark;
            tmpInventTransMark.QtyRemain  -= tmpInventTransMark.QtyMarkNow;

            mapUpdated = new Map(Types::Int64, Types::Record);

            mapUpdated.insert(tmpInventTransMark.RecId, tmpInventTransMark);

             TmpInventTransMark::updateTmpMark(
                        receiptInventTransOriginId,
                        receiptInventTrans.inventDim(),
                        -qtyToMark,
                        mapUpdated.pack());
        }

    }

SalesPackingSlip Report and saving it as a PDF file using x++ code

Calling Sales Packing Slip Report through X++ Code

Hello Blogger Viewers,

Today, I am excited to share with you some X++ code that allows you to call the Sales Packing Slip report programmatically. This can be useful in scenarios where you need to automate the process of generating packing slip reports. Let's dive into the code!

        
SrsReportRunController ssrsController = new SrsReportRunController();
SalesPackingSlipContract salesPackingSlipContract = new SalesPackingSlipContract();
CustPackingSlipJour custPackingSlipJour;
SRSPrintDestinationSettings printerSettings;

select custPackingSlipJour where custPackingSlipJour.PackingSlipId == "200258-PAS-UK01";

// Define which report design to run.
ssrsController.parmReportName(ssrsReportStr(SalesPackingSlip, Report));

// Define how we want to execute the report (right now or batch style).
ssrsController.parmExecutionMode(SysOperationExecutionMode::Synchronous);

// Hide the report dialog.
ssrsController.parmShowDialog(false);

// Set the record and table IDs for the report contract.
salesPackingSlipContract.parmRecordId(custPackingSlipJour.RecId);
salesPackingSlipContract.parmTableId(custPackingSlipJour.TableId);

// Link the contract to the controller so we know how to run the data provider.
ssrsController.parmReportContract().parmRdpContract(salesPackingSlipContract);

// Link the printer settings to the controller.
printerSettings = ssrsController.parmReportContract().parmPrintSettings();

// Set the print medium type to HTML and always overwrite the file if it exists.
printerSettings.printMediumType(SRSPrintMediumType::File);
printerSettings.fileFormat(SRSReportFileFormat::PDF);
printerSettings.overwriteFile(true);
printerSettings.fileName(@'C:\'+'PackingListReport'+custPackingSlipJour.PackingSlipId+'.pdf');

// Start the report execution.
ssrsController.startOperation();
        
    

After executing this code, you will be able to see the generated PDF file in your "Downloads" folder. This approach provides a convenient way to automate the process of generating Sales Packing Slip reports.

I hope you find this code snippet helpful for your X++ development. If you have any questions or suggestions, feel free to leave a comment below.

Happy coding!

Sunday, April 30, 2023

how to create number sequence in d365fo

 Hi All, 

Welcome to Blog.

Today we are going to learn how to create number sequence. But before we start let's understand about number sequence framework. Microsoft Dynamics AX has a number sequence framework to generate alphanumeric number sequences that are used to identify transaction documents such as purchase orders, Sales Orders. This topic describes how to implement the number sequence framework for a new module in Microsoft Dynamics AX. In this topic will learn how to create new number sequence reference in Accounts Payable module and will use newly created number sequence in our custom form.

Steps to follow one new number using number sequence:

     1.   Create new string type EDT.

 Name it like: TutBikeId or according to your requirement.

Set label and size properties.

2.    Create new class to set Number sequence data type.

Name it like: ModulenameBikeIdNumSeq , My muodulename is Test so I am using Test as prefix for all the objects.


Internal final class TestBikeIdNumSeq extends NumberSeqApplicationModule

{

[SubscribesTo(classstr(NumberSeqGlobal),delegatestr(NumberSeqGlobal,buildModulesMapDelegate))]

    static void buildModulesMapSubsciber(Map numberSeqModuleNamesMap)
    {

NumberSeqGlobal::addModuleToMap(classnum(TestBikeIdNumSeq), numberSeqModuleNamesMap);

    }


 // this is depend on the which module you want to generate the number sequence.

    public NumberSeqModule numberSeqModule()

    {

        return NumberSeqModule::Cust;

    }

     protected void loadModule()

    {

        NumberSeqDatatype datatype = NumberSeqDatatype::construct();

        datatype.parmDatatypeId(extendedTypeNum(TestBikeId));

        datatype.parmReferenceHelp(literalStr("Unique key used for the Bike iD."));

        datatype.parmWizardIsContinuous(false);

        datatype.parmWizardIsManual(NoYes::No);

        datatype.parmWizardFetchAheadQty(10);

        datatype.parmWizardIsChangeDownAllowed(NoYes::No);

        datatype.parmWizardIsChangeUpAllowed(NoYes::No);

        datatype.parmSortField(1); 

        datatype.addParameterType(NumberSeqParameterType::DataArea, true, false);

        this.create(datatype);

    }

}

 

3.    Create new runnable class to load the number sequence.

internal final class TestBikeIdLoadNumSeq

{   

    public static void main(Args _args)

    {

        TestBikeIdNumSeq TestBikeIdNumSeq = new TestBikeIdNumSeq ();

        TestBikeIdNumSeq.load();

    }

 }

4.    Build and synchronize your project and run the above runnable class using below URL.

F&O url/?cmp=dat&mi=sysclassrunner&cls=TestBikeIdLoadNumSeq 

5.    After running the job, go the parameters form you added the number sequence reference to, then, go to the 'Number sequence' tab and verify that a new row is shown.

In my example, I see the new number sequence reference show on the ‘Accounts receivable parameters’ form.

6.  Next go to Organization administration>Number sequences>Number sequences. Then click the 'Generate' button to run the wizard.

Click Next

Finally, review the 'Completed' page, and click 'Finish'.

Remember the number sequence code generated or find using below filters.

7.    Setup new number code on to AR parameter > number sequence > bike id 

8.    Create new string type field on your custom table.

Set extended type property to above created EDT. Ex- TutBikeId

9.    Override the create method of your form data source and add below code.

public void create(boolean _append = false)
 {

            TestBikeId testBikeId;

            NumberSequenceReference numberSequenceReference; 

            super(_append); 

            ttsbegin;

numberSequenceReference= NumberSeqReference::findReference(extendedTypeNum(TestBikeId));

            if (numberSequenceReference)
            {
                testBikeId = NumberSeq::newGetNum(numberSequenceReference).num();
                TestTutorialBikeTable.BikeId = testBikeId;
            } 

            ttscommit;

        } 

10. Build and synch your project.

11. Create new record on the form and check.

Friday, March 24, 2023

Create table in email body using X++ code.



Hi All,
Today we are going to see how to create table in email body without using email templates. Please refer below example.

Note - Please make sure your email parameter setup is done and you able to send test email.

Expected result: 






















X++ Code
internal final class TestJobTableInEmailBody
{
    public static void main(Args _args)
    {
        SysMailerMessageBuilder messageBuilder = new SysMailerMessageBuilder();

        SysInfoLogStr   emailBodyWithHtml;
        EmailBase       fromEmail = 'no-reply-vendorportal@testgroup.com';
        EmailBase       toEmail = 'vijay.yelmame14@gmail.com';
        EmailBase       ccEmail;
        PurchTable      PurchTable;
        boolean emailSend;

        try
        {
            emailBodyWithHtml = "<table border = '1'><tr><td><b>Payment<b></td><td><b>Currency Code<b></td><td><b>DeliveryPostalAddress<b></td><td><b>Delivery Date<b></td></tr>";

            while select * from PurchTable where 
                PurchTable.OrderAccount =='TEst-VEN'
            {
                emailBodyWithHtml += "<tr><td>"+PurchTable.Payment+"</td><td>"+PurchTable.CurrencyCode+"</td><td>"+any2Str(PurchTable.DeliveryPostalAddress)+"</td><td>"+any2Str(PurchTable.DeliveryDate)+"</td></tr>";
            }
            emailBodyWithHtml += "</Table>";

            messageBuilder.setBody(strFmt(strRem(emailBodyWithHtml, '\r')),true);

            messageBuilder.setSubject("Test Email");
            messageBuilder.addTo(toEmail);
            //messageBuilder.addCc(ccEmail);
            messageBuilder.setFrom(fromEmail);

            emailSend = SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());

        }
        catch
        {
            warning("@Res:NotificationEmailNotSent");
        }
    }

}




Friday, January 13, 2023

Create computed column on view in D365FO using created date time column.

Dear All,

In this article will see how to create computed column in view. As we all know view are returning records from SQL from multiple tables, but some time we are getting requirement to create calculated column using the available column. Similarly, in below example as well we are going to create calculated column using createdDateTime field of PurchLine table.

We can achieve this requirement using display method, but it will not give you the filter and sorting options so let's learn and implement it together.

Requirement: Return a date difference between CreatedDateTime and today's date and show values to the form grid with filter and sorting should be available on return value column.

Solution: Create computed column on view, add view as a DataSource on form and add computed column field into grid.

Implementation: 

Step 1: 
Add new static method on view and add code according to your logic.










 
X++ Code for method -





Step 2: Add computed column on view.
Right click on view and select column according to your requirement. 







Step 3: Select method in View method property of new created column.









Step 4: Add DataSource column in form Grid. Assuming you are aware on form design so explaining this step-in details. Link 

Step 5: Build and synchronize your project.

Step 6: Verify SQL level changes: 
Filter views by name in AxDb and find how your column is created.





SQL view for this computed column.



Step Last: Validate changes on form, try to apply filters and sort using standard sorting functionality. 


That's It.

Happy Daxing.

Friday, January 6, 2023

How to apply custom range on AOT query in D365 Finance and Operations

Hi All,
Here in this blog will see how to apply custom range on AOT query.

Requirement: Add range on AOT query to get the records created before given days (createdDateTime - PriorDays)

Steps 1 - Add new field in the parameters. Please refer below screen shot.



Step 2 - Create new class and use attribute for range method. Refer below screen shot.

internal final class TestQueryRangeUtil
{
    
    [QueryRangeFunctionAttribute()]
    public static str greaterThanDateByParameter()
    {
        int relativeDays = SalesParameters::find().TestPriorDays;
        utcdatetime  currentDateTime;

        currentDateTime = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::getSystemDateTime(),               DateTimeUtil::getUserPreferredTimeZone());

        return '> ' +              SysQueryRangeUtil::value(DateTimeUtil::date(DateTimeUtil::addDays(currentDateTime,relativeDays)));  
    }

}
Step 3:Create range on AOT query and add below given expression as value.

(TESTQueryRangeUtil::greaterThanDateByParameter())








Thats it. Happy Coding.

How to Create Multiselection Lookup in D365FO

How to Create Multiselection Lookup in D365FO How to Create Multiselection Lookup in D365FO In this blog p...