Search Suggest

January 2022
Hotel Customer Feedback Power BI Dashbaord
D365FO
  • D365FO
  • X++
  • Currency
  • Dynamics

In this article I will show you how to execute a macro in SQL statements in D365FO or How to process data using a macro in a SQL statement in D365FO, before going to the depth of the topic we have to learn the basic concept of macros in Microsoft dynamics 365 finance and operations.

If you are a beginner or new to dynamics 365 Finance & Operations, you can use Microsoft's Free Virtual Machine. Learn How to Set Up a Free Virtual Machine for Dynamics 365 Development

What is Macro?

In a standard D365 FO application, there are macros that are reused many times across the application. By Using the macros approach, we can save development time by allowing you to reuse the piece of X++ SQL statements. These macros are actually full or partial X++ SQL queries that can be called with various arguments. If your macro is going to be used in several places it would make sense to create the macro in the AOT as you will then be able to reuse the macro.

The purpose of defining SQL in a macro is to reuse it a number of times in various places. We use %1 as an argument. More arguments can be used as per our requirements.

In this article, we will create one small macro which holds a single where clause to display the active but expired items from two different products tables TblMedcines and TblSnacks. Then, we will create a class that uses the created macros to display a product list. As we know the purpose of the macro is can be used a number of times in various places. So our macro you can call anywhere you required to get the list of products that are expired, but still active in the tables.

Basic Steps

  1.  Create a new Dynamics 365 Project and create two tables TblSnacks and TblMedcines
  2.  Create one macro named ExpiredActiveProducts and add the below codes.
  3.  Create a new Runnable class called ProductTableMacro.

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO

How it works

First, we have created two tables TblMedcines and TblSnacks. TblMedcines stores the basic details of medicines with columns MedicineId, MedicineName, MedicineDescription, ExpiryDate, and Status as shown in the figure.

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO
Same way TblSnacks stores the basic details of sweets with columns SweetId, SweetName, SweetDescription, ExpiryDate, and Status as shown in the figure.

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO


Second, we have created one macro that holds the where clause. Normally, the purpose of defining SQL in a macro is to reuse it a number of times in various places. We use %1 as an argument. More arguments can be used as per our requirements. Here I put an easy example for easy understanding 

(%1.Status == "Active" && %1.ExpiryDate>= Today()).

This macro is defined with one argument %1 which we will input as table names. The condition of the macro is 

TbaleName. Status="Active" and TableName. ExpiryDate= Today().

Here Today() is a built-in function that returns the current date. So this macro returns all the active records which are expired and inactive from any table which holds two columns with the names "Status" and "ExpiryDate".

Next, we created one job with the select statement. here we called the previously created macro in the where clause and passed the table name as the argument (%1).

The query works like any other query, but the advantage is that the code in the macro can be reused elsewhere.

For TblMedicines

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO

In the above code, we are calling the macro and passed argument TblMedicines. The macro is called with a syntax #ExpiredActiveProducts(), which returns all the medical records which are expired but active in the table. 

When we run the job and check the results, as shown in the following screenshot:

Run the job and check the results, as shown in the following screenshot:


For TblSnacks

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO

In the above code, we are calling the macro and passing the argument as TblSnacks. The macro is called with a syntax #ExpiredActiveProducts(), which returns all the sweets records which are expired but active in the table. 

When we run the job and check the results, as shown in the following screenshot:

What is Macro in D365 ? How to Execute Macro in SQL Statement in D365FO


Copy and paste the codes below to your visual studio runnable class.

class ProductTableMacro
{
     
   public static void main(Args _args)
   {
       TblMedcines medicines;
 
       while select medicines
       where #ExpiredActiveProducts(medicines)
       {
           info(strFmt( "%1 - %2", medicines.MedicineName, medicines.MedicineDescription));
       }
 
   }
 
}  
From the above example, it is very clear that a macro is which can be used a number of times in various places will increase the speed and reduce the length of the code as well. 
Happy coding with D365 Snippets 🙂.

event-handlers-in-d365-fo-with-example

In dynamics AX 2012, customization on tables, forms, and classes was done by simply overriding methods on them, But In Dynamics 365 for Operations, the preferred mechanism for customizations to existing objects is to use event handlers to react to various events rather than overriding methods on tables, forms, and classes.

If you are a beginner or new to dynamics 365 Finance & Operations, you can use Microsoft's Free Virtual Machine. Learn How to Set Up a Free Virtual Machine for Dynamics 365 Development

For example, to change what happens when a button is clicked in AX 2012 you override the clicked method and put code either before or after the super() call. In Dynamics 365 for Operations, you can react to the OnClicked event by copying the event handler method for the event and pasting the method into a class. 

Below is an example of an event handler method that reacts to the OnClicked event of a button on a form and controls the behavior of methods by using two types of events, proceeding Event ( that occurs before the method's super() is called) and succeeding Event (that occurs after the method super() is called).

With D365 event handlers play a very important and hence we need to know how and when to use them to maximum benefit. Also for Improving the Development Efficiency and Performance of D365 Applications Use of an event handler is always recommended, and it is the safest way to modify any existing functionality in Dynamics 365 for Finance and Operations. However, it may not fit every requirement, but always try to use an event handler in every possible place. 

You can use an event handler on Classes, Forms, and Tables. On any method, whether it's on a Table, Class, or Form, you can write pre or post-event handler, while on Tables and Forms you will also get standard Events under Event nodes such as onInserting, onDeleted, and so on.

To understand this concept better, let's take the example of On Inserting Event Handler with Table. When we use event handlers on the basis of your selection criteria, the event handler method will execute. For example, if you choose post Event handler, it will execute just after that method execution is finished. Refer to the following code to understand post Event handler.

Post-event handler is the same, but the only difference is that it will execute after the parent method. Apart from pre-and post-event handlers, Dynamics 365 for Finance and Operations provides event handling on system events/methods such as onDeleting, OnDelete, OnInsert, and so on. 

These event handlers have a different syntax than the Pre-Post event handler, but the concept is the same. To use these event handlers, simply expand the Events node on Tables and Forms. Classes don't have events. Expand the Events node and choose the required event, then right-click and select Copy Event Handler Method and paste it into your event handler class.

Example

For a better understanding of the concept let us take one example of the CustTable event handler. After saving a customer record we have to change the customer group automatically through x++ code.

  1. Open the CustTable in the designer window.
  2. Expand the Events node.
  3. Right, Click on the OnInserted method and select Copy Event Handler Method.
  4. Then Create one class in your project give the name EventHanlderCustTable.
  5. Paste event handler code inside the class.
Event Handlers in D365 with Example


Now let's say we have a scenario in which we need to default some value in the table's field before insertion takes place, we will modify the code as shown below:

class EventHandlerCustTable
{

[DataEventHandler(tableStr(CustTable), DataEventType::Inserted)]
public static void CustTable_onInserted(Common sender, DataEventArgs e)
{
CustTable custTable = sender as CustTable;
// 90 is the Customer group code for Intercompany Cutomer
if(custTable.CustGroup=="90")

{
// 80 is the Customer group code for Other Customer
custTable.CustGroup="80" ;
Global::error("Created Customer is an Intercompany Cutomer and will be added to the Customer Group Other Customer");

// you can write your logic here.
}


}

} 

Now build the code and run it, you will see whenever some record is inserted into CustTable. You can test your code, for this go to Account Receivable > All Customers. While creating the customer if you are choosing the Customer Group code as "90", it will show the message given inside Globale:: error method as shown below. The example given here is not a standard one. You can write your own logic as per the requirements.

Event Handlers in D365 with Example

Conclusion

In Microsoft Dynamics 365 Finance & Operation writing customization by using event handlers is improving the development efficiency and performance. this is the safest and fastest way of modifying any existing functionality, even though it may not be fit for all situations, always use event handlers in every possible place. If this post is useful share it with your friends. 

Happy coding with D365 Snippets 🙂.


Tags

Event Handler Methods in Dynamics 365 for Operations
What is the purpose of an event handler?
What is the difference between pre/post event handler and chain of commands?
Configure event handlers for a table.
Event hanlder in D365
Customizing D365 with event handlers
Pre-event handler and post-event handler
Table On Inserting Event Handler In Dynamics 365

Suppose you have a small requirement where you have to pick and display current log in user informations like name , department , position etc.The code below will help out in fetching current user Information in AX 7 or D365 FO. Here i fetching the basic details of logged user including User Id, Person Name and working position. In dynamics 365 fo user details and associated personal information are keeping in difference tables. But by using the below x++ codes , you can easily fetch the details.

If you are a beginner or new to dynamics 365 Finance & Operations, you can use Microsoft'f Free Virtual Machine. Learn How to Set Up a Free Virtual Machine for Dynamics 365 Development

For this you create a runnable class then copy and paste below codes to the main method. 

class RunnableUserInfo
{
  
   public static void main(Args _args)
   {
       
       HcmWorkerRecId              hcmWorkerRecId;
       HcmPositionWorkerAssignment hcmPositionWorkerAssignment;
       HcmPositionDetail           hcmPositionDetail;
       OMOperatingUnit             omOperatingUnit;
   
       hcmWorkerRecId = HcmWorker::userId2Worker(curUserId());
       hcmPositionWorkerAssignment =   HcmPositionWorkerAssignment::getActivePositionWorkerAssignment(hcmWorkerRecId);
       hcmPositionDetail = HcmPositionDetail::findByPosition(hcmPositionWorkerAssignment.Position);
       
       DirPartyName PersonName = DirPersonUser::userId2Name( curUserId());
   
       info(strFmt("User Id : %1 - Name : %2 - Position: %3",
               curUserId(),PersonName,hcmPositionWorkerAssignment.description()));
   }
 
}

After successfull build of the project you will get the output. You can ellaborate the codes as per your requirement, by writing more codes you can also fetch more user details.

How to get current logged user information using x++ code in D365fo

All the tutorials are for beginners , if you dont hav a virtual machine for your learning purposes you can use microsofts free Virual machine. if this tuotorial is useful , please share to others.

Happy coding with D365 Snippets

Tags

Get Current User and User Name in d365
Get Current User and User Name in AX
How to get current user information using x++ D365
How to get current user information using x++ AX 7
Get Current User Name in  X++ in D365FFO
Get Current User Name in  X++ in AX

In this article i write a small tip "how to open external URL in D365 using x++ code?". If you want to navigate the user’s browser to a different URL programmatically (and not by providing a link they can click) this can be done very easily by using the new class Browser.With the new version Dynamics AX or D365 there are new APIs that are needed because of the technological changes.

how-to-open-external-url-in-d365-using-xpp-code

The Browser class only has one single method, navigate, which has three parameters (of which only the first is mandatory): 

     - URL (string)
     - Prompt (boolean)
     - Open in new tab (boolean) 

In Visual Studio Create One Runnable Class, In the main method write the below code .

class ExternalURL
{        
    
    /// The specified arguments.
    public static void main(Args _args)
    {
        Browser browser = new Browser();
        browser.navigate('http://d365snippets.com', true, false);
    }
}

simple example using a runnable class could look like this . If you run it, it’ll open a new tab with the starting page of this blog.For best practice you create a action menu set its object type to class and set object with runnable class name. Add this menu item to required menu extension. Save compile On clicking menu item from navigation.A popup windows open,if your browser pop window is blocked, Allow popup option.If this code helps you please share to others. 

Happy coding with D365 Snippets