Sunday, June 19, 2022

X++ Dynamics date2Str Function - Converts the specified date to a string

 To use the date format that the user specified in Regional Settings, use the strFmt or date2Str function with -1 in all the formatting parameters. When the regional settings control the date format, the settings can change from user to user. If -1 is used for either separator parameter, both separators default to Regional Settings.

The sequence parameter values must be any three digit number that contains exactly one occurrence of each digit 1, 2 and 3. The digits 1-2-3 represent day-month-year respectively. For example, 321 would produce the sequence of year, month, and day. Or the value can be -1 to use Regional Settings. No enumeration type should be used for this parameter, because numbers like 321 exceed the range of valid values for enumeration values, which is 0 through 250 inclusive.

The default value of the Flags parameter is the DateFlags::None enumeration value, which means no left-to-right or right-to-left sequence processing is performed.

Here is the description of the function and also a couple of examples on how to implement.


str date2Str( date date, int sequence, int day, int separator1, int month, int separator2, int year [, int flags = DateFlags::None])

Parameter
Description
date
The date to convert.
sequence
A three digit number that indicates the sequence for the components of the date, 1 for day, 2 for month, and 3 for year.
day
A DateDay enumeration value that indicates the format for the day component of the date.
separator1
A DateSeparator enumeration value that indicates the separator to use between the first two components of the date.
month
A DateMonth enumeration value that indicates the format for the month component of the date.
separator2
A DateSeparator enumeration value that indicates the separator to use between the last two components of the date.
year
A DateYear enumeration value that indicates the format for the year component of the date.
flags
A DateFlags enumeration value that indicates whether the language settings on the local computer should be used to calculate the proper left-to-right or right-to-left sequence in the returned string.
{
    date currentDate = today();
    str s;
    int iEnum;
    ;
    s = date2Str
        (currentDate,
        321,
        DateDay::Digits2,

        DateSeparator::Hyphen, // separator1
        DateMonth::Digits2,
        DateSeparator::Hyphen, // separator2

        DateYear::Digits4
        );
    info("Today is:  " + s);
}
/** Example Infolog output
Message (12:36:21 pm)
Today is:  2009-01-13
**/


sstatic void Job1(Args _args)
{
    date dateformat;
    str strformat,strformat2,strformat3,strformat4,strformat5,strformat6,strformat7,strformat8,strformat9,strformat10,strformat11;
    ;
    dateformat = today();
    info(strFmt("Todat is %1",dateformat));
    strformat = date2str(dateformat,123,DateDay::Digits2,DateSeparator::Slash,DateMonth::Digits2,DateSeparator::Slash,DateYear::Digits4);
    strformat2 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Slash,DateMonth::Digits2,DateSeparator::Slash,DateYear::Digits4);
    strformat3 = date2str(dateformat,312,DateDay::Digits2,DateSeparator::Dot,DateMonth::Digits2,DateSeparator::Dot,DateYear::Digits4);
    strformat4 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Hyphen,DateMonth::Digits2,DateSeparator::Hyphen,DateYear::Digits2);
    strformat5 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::None,DateMonth::Digits2,DateSeparator::None,DateYear::Digits2);
    strformat6 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Space,DateMonth::Digits2,DateSeparator::Space,DateYear::Digits2);
    strformat7 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Dot,DateMonth::Digits2,DateSeparator::Dot,DateYear::Digits2);
    strformat8 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::None,DateMonth::Digits2,DateSeparator::None,DateYear::Digits4);
    strformat9 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Space,DateMonth::Digits2,DateSeparator::Space,DateYear::Digits4);
    strformat10 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Dot,DateMonth::Digits2,DateSeparator::Dot,DateYear::Digits4);
    strformat11 = date2str(dateformat,213,DateDay::Digits2,DateSeparator::Slash,DateMonth::Digits2,DateSeparator::Slash,DateYear::Digits4);
 
    info(strFmt("%1",strformat));
    info(strFmt("%1",strformat2));
    info(strFmt("%1",strformat3));
    info(strFmt("%1",strformat4));
    info(strFmt("%1",strformat5));
    info(strFmt("%1",strformat6));
    info(strFmt("%1",strformat8));
    info(strFmt("%1",strformat9));
    info(strFmt("%1",strformat10));
    info(strFmt("%1",strformat11));
}

Tuesday, June 7, 2022

AX 2012: Create a Simple Batch Job

 AX 2012: Create a Simple Batch Job

In this post we’ll learn how to create a very basic custom Batch job using SysOperation framework. We’ll use the base controller class SysOperationServiceController and develop a custom service operation class to achieve the goal.

Requirement:

To create a Batch job to mark all the records as processed in a custom table MAKSalesTable.

Project overview:

The project shows how simple yet powerful the SysOperation framework is for developing custom batch jobs as opposed to RunBase framework since the minimum development needed to create a fully functional batch job is to create a custom service operation class defining a single method giving the implementation for the batch operation to be performed.

Development steps:

1. Create a service operation class MAKSalesTableService having the following class declaration:

class MAKSalesTableService
{
}

2. Create a new method in the class giving a suitable name like processRecords having the following definition:

[SysEntryPointAttribute(false)]
public void processRecords()
{
    MAKSalesTable   makSalesTable;
    int             counter = 0;

    //Determines the runtime
    if (xSession::isCLRSession())
    {
        info('Running in a CLR session.');
    }
    else
    {
        info('Running in an interpreter session.');

        //Determines the tier
        if (isRunningOnServer())
        {
            info('Running on the AOS.');
        }
        else
        {
            info('Running on the Client.');
        }
    }

    //Actual operation performed
    while select forUpdate makSalesTable
    {
        ttsBegin;
        makSalesTable.Processed = NoYes::Yes;
        makSalesTable.update();
        ttsCommit;

        counter++;
    }

    info(strFmt("Successfully processed %1 records.", counter));
}

3. Create an action menu item MAKSalesTableService pointing to SysOperationServiceController.

4. Set the parameters of the action menu item to the service operation just created, MAKSalesTableService.processRecords.

image

5. Compile the service operation class and generate incremental IL.

6. Click on the action menu item to run the batch job. Check the Batch processing checkbox to run the job in CLR runtime which is the batch server execution environment.

image

image

7. Click System administration > Inquiries > Batch jobs to view the status of the job. You may also click on the Log button to view the messages written to infolog during the job execution.

image

image

Preconditions:

Before running the batch job, all the records were unprocessed:

image

Post conditions:

After running the batch job, the list page shows that all the records are now marked as processed:

image



Using X++ : Export Data from table to a CSV File

X++ : Export Data from table to a CSV File

 CSV file itself doesn't contain any formatting information. You can verify this by opening the file in Notepad - you will see the values displayed correctly. When you open CSV in Excel, you can let Excel automatically determine the column data types, or you can define them yourself.


static void SF_ExportToCSVFile(Args _args)

{

    TextBuffer              textBuffer  = new TextBuffer();

    InventTable             inventTable;

    FileIoPermission        perm;

    counter                 Lines;


    #define.ExampleFile(@"c:\test\test.csv")

    #define.ExampleOpenMode("W")

    

;

    try

    {

        // Set code access permission to help protect the use of

        perm = new FileIoPermission(#ExampleFile, #ExampleOpenMode);

        perm.assert();

        textBuffer.appendText("Item Id,");//must be "," suffix

        textBuffer.appendText("Item Name,");//must be "," suffix

        textBuffer.appendText("Item Type");

        textBuffer.appendText("\n");//next line must be "\n" suffix


        while select InventTable

            where   inventTable.ItemId like "04-1*"

        {

            textBuffer.appendText(strfmt("%1,",inventTable.ItemId));

            //must be repace "," to ""

            textBuffer.appendText(strfmt("%1,",global::strReplace(inventTable.itemName(),",","")));

            textBuffer.appendText(enum2str(inventTable.ItemType));

            textBuffer.appendText("\n");

        }

        Lines = textBuffer.numLines();

        try

        {

            if (textBuffer.toFile(#ExampleFile))

                info( strfmt("File Generated as %1.total insert %2 Lines",#ExampleFile,Lines-1));

        }

        catch ( Exception::Error )

        {

            error ("Generated file error.");

        }

        // Close the code access permission scope.

        CodeAccessPermission::revertAssert();

    }

    catch (Exception::Deadlock)

    {

        retry;

    }

}




Upload file to FTP X++

 

Upload file to FTP  X++

One of a very common requirements for any ERP systems is to have FTP file upload support to upload files from AX to FTP server. We do have many libraries, tools available to do that. However, it is best to have native X++ code without referencing any DLLs to upload your files to FTP from AX. Following code shows the example of uploading files to FTP.

The code written below can be easily used to upload files, However, if you have to process this as a batch you need to consider that batch runs on server/CIL and for this you need to set permissions and also if that still doesn't work, you can change the method to static server.
The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network but in our case, transfers file from AX client to file directory present on FTP server. You can easily find the code on the web on how to upload a file to FTP through X++ code but not in detail. In this post, I will try to explain detail about each line what it does during execution. So, let’s start.

static void SF_FTPJob(Args _args)
{
 System.Object ftpo;
   System.Object ftpResponse;
   System.Net.FtpWebRequest request;
   System.IO.StreamReader reader;
   System.IO.Stream requestStream;
   System.Byte[] bytes;
   System.Net.NetworkCredential credential;
   System.String xmlContent;
   System.Text.Encoding utf8;
   System.Net.FtpWebResponse response;
   ;
   // Read file
   reader = new System.IO.StreamReader(@'C:\test\testfileFTPAX.txt');
   utf8 = System.Text.Encoding::get_UTF8();
   bytes = utf8.GetBytes( reader.ReadToEnd() );
    //info(strFmt("%1",any2str(bytes)));
   reader.Close();
   // little workaround to get around the casting in .NET
   ftpo = System.Net.WebRequest::Create("ftp://IP:Port/FolderName/testfileFTPAX.txt");
   request = ftpo;

   credential = new System.Net.NetworkCredential("UserID","Password");
   request.set_Credentials(credential);
   request.set_ContentLength(bytes.get_Length());
   request.set_Method("STOR");
 
   requestStream = request.GetRequestStream();
   requestStream.Write(bytes,0,bytes.get_Length());
   requestStream.Close();

   ftpResponse = request.GetResponse();
   response = ftpResponse;

   info(response.get_StatusDescription());
}









D365 FO Coloring records - Change grid row color in list page/form

 How to change grid row color in list page/ form in Dynamics  ?


Solution :

Go to Form Datasource and override Displayoption() method and write code according to your requirement.

The displayOption() method on any form's data source can be used to change some of
the visual options. Before displaying each record, this method is called by the system with
two arguments--the first is the current record and the second is a FormRowDisplayOption
object--whose properties can be used to change a record's visual settings just before it
appears onscreen. In this example, we check whether the current user is disabled, and if
they are, we change the background property to light red by calling the backColor()
method with the color code.

Example :

 public void displayOption(Common _record, FormRowDisplayOption _options)
{
    SalesTable prodtablelocal;
   
    prodtablelocal = _record;
   
    Switch(prodtablelocal.SalesStatus)
    {
    Case SalesStatus::Delivered:
    _options.backColor(WinAPI::RGB2int(255, 153, 255)); //Lime
 
    Break;
    Case SalesStatus::Invoiced:
    _options.backColor(WinAPI::RGB2int(#Red));
 
    Break;
    Case SalesStatus::Backorder:
    _options.backColor(65408); //Light Green
    //_options.affectedElementsByControl(Salestable_SalesId.id());
    _options.textColor(12582912);
    Break;
    }
}

Here is the result





D365 Grid/List row color change using method override

 Today, I received the requirement from my functional to change the row color for Purchase Order List Page Grid   on any specific condition... 


As we all knows in custom form its really easy using Displayoption()  to achieve but in my case I need to do this on exists form using method override/Event handler of Data source.. 

There is an event available in data source OnDisplayOptionInitilized. I copied the event handler and paste on my class.



Following are the code 
[FormDataSourceEventHandler(formDataSourceStr(PurchTable, PurchTable), FormDataSourceEventType::DisplayOptionInitialize)]
    public static void PurchTable_OnDisplayOptionInitialize(FormDataSource sender, FormDataSourceEventArgs e)
    {
        PurchTable purchTable; //= sender.cursor(); wrong
        FormDataSourceDisplayOptionInitializeEventArgs eventArgs = e as FormDataSourceDisplayOptionInitializeEventArgs;
        purchTable = eventArgs.record(); //correct

         

        if(today() < purchTable.VendFromDate)
        {
            eventArgs.displayOption().textColor(WinAPI::RGB2int(0, 0, 255));  // Blue
        }
        else if (today() > purchTable.VendToDate)
        {
            eventArgs.displayOption().textColor(WinAPI::RGB2int(255,0,0)); // Red
        }
        else
        {
            eventArgs.displayOption().textColor(WinAPI::RGB2int(76, 187, 23)); // Green
            
        } 
    }

Here is the result







Wednesday, June 1, 2022

D365fo - Get Main account from ledger dimension

 Dimensions in Microsoft Dynamics 365 for Finance and Operations or in Microsoft Dynamics AX 2012 are always have a very important role. Playing with dimensions is always a hectic thing. To get main account from ledger dimension in D365FO is a very common requirement.


In this article, you will get the one line code to get the Main Account from Ledger Dimension using LedgerDimensionFacade class. See the following code:

//Get MainAccountId from LedgerDimension

//The argument (LedgerDimensionValue) is LedgerDimension which you can get from table or any other source 
as per your requirement

info(strFmt("%1",LedgerDimensionFacade::getMainAccountFromLedgerDimension(LedgerDimensionValue).MainAccountId));

//Get Name of MainAccountId from LedgerDimension

//The argument (LedgerDimensionValue) is LedgerDimension which you can get from table or any other source as per your requirement

info(strFmt("%1",LedgerDimensionFacade::getMainAccountFromLedgerDimension(LedgerDimensionValue).Name));

                            

          

In this way, you can get Main Account from Ledger Dimension in D365FO. If this helps you, please Like, Comment and Share to help other people.


If you found any ambiguity or a better solution, please feel free to ask.

Monday, May 16, 2022

D365 F&O - Connect Power BI to D365 Finance and Operations Using OData

 Dynamics 365 Finance and Operations comes out of the box with over 600 standard reports and inquiries , These reports and inquiries may meet the majority of reporting requirements but if you want to take your data and analytics to the next level you will need Power BI. 

(you can find the how to Create D365 F&O Data Entity post).

Power BI can open up a whole new world of analytics and insights.

If you have never used Power BI or have never connected Power BI to Dynamics 365 Finance and Operations, it can be a bit tricky to get connected and start building reports. In this post I will take you through step by step how to connect Power BI to Dynamics 365 Finance and Operations, build your first report, and publish it to your Power BI workspace.

Connect Power BI to Dynamics 365 Finance and Operations

After you have downloaded the Power BI Desktop, launch the Power BI Desktop application. In the ribbon click the “Get data” button and click “More…”.

Click the “Online services” tab, click the “Dynamics 365 (online)” option and click “Connect”.

In the Web API URL paste in your Dynamics 365 Finance and Operations environment URL. Make sure that at the end of the URL you add “/data”. Then click “Ok”.

The next step is to authenticate. Click the “Organization account” tab and click the “Sign in” button. Sign in with the same username and password you use to sign into Dynamics 365 Finance and Operations. Then click the “Connect” button.

Once you have authenticated you will need to select the data entities you will need to build you Power BI reports. To do this you can search for the entities you need and select each one by clicking the checkbox. You can also preview the data in the pane to the right. Once you have selected all the data entities you need click the “Load” button. This will begin loading the data into Power BI (Data Entities).

Once the data loads you will see the tables appear on the right hand side of the form.

Build Your Power BI Report

Next, we need to define the relationships between the data. Typically, a star schema is used with one fact table related to multiple dimension tables. In this case my fact table will be the sales lines and the dimensions I need will reside on the sales order header table. On the left side of the form click the “Model” button.

To create the relationship, you can drag the related field which is the primary key to the related field in the other table. In this case the key is the sales order number which links the sale order header records to the sales order lines records.

Next click on the visual you want to create. Then drag each field you want to add to the visual to the “Axis”, “Values”, or legend sections depending on the type of visual you are using.

Publish Your Power BI Report

When you are ready to publish the report, you can click File > Publish > Publish to Power BI. Select the workspace you want to publish to and click the “Ok” button.

Now you can go back to powerbi.com and view your published Power BI report with the Dynamics 365 Finance and Operations data. If you have a Power BI Pro license you can also share your reports with others.

Takeaways

Power BI is an extremely powerful tool for data analytics and insights. This article was intended to help you connect Power BI to Dynamics 365 Finance and Operations, so you can start to use all the tools available in the Power BI feature set. If you are not familiar with the star schema approach to data modeling, I would recommend learning that approach. Also, there are many resources online that cover some of the more basic and advanced features of Power BI that can help you accelerate your learning.