Write A File In D365

Share this:

In the last article, you learned how to read a file, and process the data in D365. Now, learn how to write a file in D365. There are several different ways you can get data out of Microsoft Dynamics 365 for Finance and Operations. You can use the data management framework, data entities, Odata, Excel, or X++. In this article, I will explain the most common reasons why you might use each approach. Then, I will go into detail on how to write x++ code to write data to a file in D365.

Data Management Framework

The data management framework is an incredible tool designed to help import and export data in D365. Use the data management frame to read a file, as well as write a file in D365.

This option allows users to use the data entities created by Microsoft to read and write to the most common types of data in D365. And while the data may be spread across multiple tables, the data entities make it much easier to create a file with records contains data that exist across those tables.

Additionally, the data management framework can process files running on a batch server. This way, users do not have to wait while the system reads or writes to an especially large file.

Please read this article to learn How to Use A D365 Data Entity in the Data Management Framework and write a file in D365.

However, the data management framework can be a little overwhelming for D365 users that just want to click a link and receive a file containing the data they want.

Data Entities

Fortunately, data entities can be used in more places than just the Data Management Framework. Outside integration systems can call them to read data from within D365. See this article on how to setup postman to call D365 data entities.

This is extremely helpful for systems that need to move data on a recurring basis.

However, the downside to this approach is that it does require an external system to call D365. To do that, you must perform additional setup and send more information to securely connect to D365, and export the needed information.

OData

Similar to Data Entities, OData requires an external system to securely connect to D365.

OData has the advantage in that it can run X++ code to both write data and retrieve data in the same call. Additionally, they can run x++ code to retrieve values that are not explicitly stored on a field in the database.

See this article on how to Setup Postman to Call D365 Services.

Export To Excel

Additionally, Microsoft Dynamics 365 for finance and supply chain has the ability to export data in any grid to an Excel file. This can be done simply by clicking a button. Please see this article on how to Export Data To Excel In D365.

X++

While all the above approaches are great, sometimes it is helpful to be able write a file in D365 using x++.

Specifically, x++ is the name of the programming language used within D365. Therefore, by writing code, you can have the most control of what data is written to your file.

Next, I will show you how to write x++ code to export data to a file in D365. You can modify this example code for your specific purpose.

Create A Project

Before writing x++ code, we need a project. Review my article on How To Create A D365 Project in Visual Studio. Or, follow the steps below.

First, in a development environment, open Visual Studio. Create a new D365 project, by going to File>New>Project. Then, search and select the ‘Finance Operations‘ project template, and click Next.

Second, provide a name for your project. For this example, I called it ‘tutorialWriteFileInD365’. Then, click the Create button.

Third, after the project is created, right click on the project node, and select Properties. Set the Model to your custom model. In my case, my model is named dynamics365musings. Then click ok.

For more details, read my article on How To Create A Model In D365.

Create A Class

Before writing the x++ code needed to write a file in D365, we need to create class to put the code in.

First, right click on the project node, and select Add>New Item…

Second, select the ‘Dynamics 365 Items’ node on the left side. Next, select ‘Class’ as the object to create. Then, enter a name for the class. In this example, I named the class ‘TutorialWriteFile‘. Then, click ‘Add‘.

Write Text To A File

Finally, we can add the code needed to write a file in D365.

Let us add the code first, then I will explain how it works.

Double click on the new class you created, and add the following method.

public void SendStringAsFileToUser()
    {
        str stringToWrite = "ItemId, ItemName, ItemGroup \r\n";
        InventTable inventTable;
        int counter = 0;

        while select inventTable
        {
            //write the next line of the csv file
            //sampleString += "1000, My ball, 10 \r\n";
            stringToWrite += strFmt("%1, %2, %3 \r\n", inventTable.ItemId, inventTable.itemName(), inventTable.itemGroupId());

            counter++;
            if (counter > 20)
            {
                break;
            }
        }
        
        File::SendStringAsFileToUser(stringToWrite, "MyFile.csv");
    }

File Formats

Now, allow me to explain the code.

There are many different types of files we could create.

  • Comma separated files
  • XML files
  • JSON files
  • many more

The main difference in each type of file is the format in which you store the information you write to the file. XML uses tags around each piece of information. JSON uses curly braces. Comma separated files use commas.

Set The Header

In this example, I will create a comma separated file. A comma separated file usually has a first row of information called a header. This tells the user what type of information is in each column of data.

Notice, in the code, we create a variable named ‘stringToWrite‘. This variable stores all of the text we want to write to the file. And, we set it equal to “ItemId, ItemName, ItemGroup \r\n”.

str stringToWrite = "ItemId, ItemName, ItemGroup \r\n";

This means that the first column of data will contain the ItemId of the item. Then, the second column will contain the ItemName of the item. Lastly, the item group will added.

The “\r\n” text are some special characters that tells the computer that there should be a line break. Or, this is often called a carriage return. This is very important to add to make our comma separated file work right.

Populate The Rows

After adding the header text to the ‘stringToWrite‘ variable, we need to add the main data.

In this example, the code has a ‘while select‘ statement to loop through the records in the inventTable table, and add the information in each record to the ‘stringToWrite‘ variable.

Notice, I use the strFmt function, to help concatenate text together, with commas in between, and a line break at the end. I have written this line instead and it do the same thing.

stringToWrite += inventTable.ItemId + ", " + inventTable.itemName() + ", " + inventTable.itemGroupId() + " \r\n";

Lastly, instead of looping through every item in the system, I decided to break out of the loop after 20 times, just to make the example quicker to run.

The code that adds most of the data to the stringToWrite variable is shown below.

        InventTable inventTable;
        int counter = 0;

        while select inventTable
        {
            //write the next line of the csv file
            stringToWrite += strFmt("%1, %2, %3 \r\n", inventTable.ItemId, inventTable.itemName(), inventTable.itemGroupId());

            counter++;
            if (counter > 20)
            {
                break;
            }
        }

Write To A File

Now that we have a string variable populated with all the data we need, we can write a file in D365.

In prior versions, this required several lines of code. Now, Microsoft has provides a ‘File’ class that makes writing to a file very easy.

Simply, add this one line of code.

File::SendStringAsFileToUser(stringToWrite, "MyFile.csv");

To explain, the first parameter takes the string you want to write to the file. In our case, pass the ‘stringToWrite‘ variable. Next, the second parameter, takes the name of the file you wish to have the browser create. In our case, I named it “MyFile.csv“.

Note, the ‘.csv‘ part of the file name is important so that when programs like excel open the file, they know how to properly show it.

Call The Code

After writing the code to write a file in D365, let us try it out.

In order to call it, we need three things.

  • Create a class with a ‘main’ method that call ours method.
  • Create an action menu item to call that class.
  • Add the action menu item to a menu.

Create A Class With A Main Method

Importantly, the way to have a menu item run code in a class directly, instead of having a button on a form, you need to have a class with a main method.

First, right click on your project and select Add>New Item. Select ‘class‘, and name the class ‘CallTutorialWriteFile‘. Then, click ‘Add‘.

Second, add the following code to your class.

class CallTutorialWriteFile
{
    public static void main(Args _args)
    {
        TutorialWriteFile tutorialWriteFile = new TutorialWriteFile();
        tutorialWriteFile.SendStringAsFileToUser();

    }

}

Notice, all this class does is instantiate an instance of the class we created earlier, then, calls the method we created ‘SendStringAsFileToUser‘. You could have put all this code in one class. But breaking them into two is a usually preferred for reusability.

Create An Action Menu Item

After creating a class, we need an action menu item to call it.

First, right click on the project, and select Add>New Item. Select ‘Action Menu Item‘, entera name, such as ‘CallTutorialWriteFile‘, then click ‘Add‘.

Second, double click on the action menu item in the project. Next, right click the menu item in the designer and select ‘Properties‘.

Third, set the ‘Object Type‘ to ‘Class‘. Next, set the ‘Object‘ to ‘CallTutorialWriteFile‘, or whatever you named your class. Then, set the Label to what should be shown to the front end user.

Add Action Menu Item To Menu

Finally, add the Action Menu Item to the Menu so that it is visible in the browser.

First, in the Application Explorer, expand User Interface>Menu Extensions.

If you have extended the menu you wish to add your menu item to before, you will see it listed. In this case, right click on the node, and select ‘Add to project’.

If, however, you have not extended the menu before, go to User Interface>Menus, find the menu you wish to add your menu to. Then, right click it, and select ‘Create extension‘.

Second, open the menu in the designer. Then, drag the Action Menu Item from your project to a submenu in the Menu.

In my example, I first created a Sub Menu named ‘Tutorials‘. Then, I dragged the menu item into that node.

Notice, dragging the CallTutorialWriteFile‘ Menu Item onto the Menu will automatically set the ‘Menu Item Type‘, and ‘Menu Item Name‘ properties.

Third, build your solution by going to Build>Build solution.

Demonstration

In a browser, navigate to your Dynamics 365 URL. Go to the Accounts Receivable module, and click on the menu item you created.

After some seconds, notice that your browser has created a file name MyFile.csv. Depending on what browser you are using, your browser will show this differently.

Go to the downloads folder on your computer and open the file.

You can open the file in Microsoft Excel, or another program of your chosing.

The file should look like this.

Conclusion

There are several different ways you can export data from Microsoft Dynamics 365 for Finance and Supply Chain. The best approach will depend on what data you need to export, which system needs to read it, and what format you need it in. In this tutorial, you learned how to write a file in D365 using x++ code. While this may take more effort than some of the other approaches, this will give you the most control in exactly how the data is written to the file.

Peter Ramer
Peter Ramer is a part of the Managed Application Services team at RSM working on Microsoft Dynamics 365. He focuses on the Retail and Commerce industries. When he is not solving problems and finding ways to accelerate his clients' business, he enjoys time with his three kids and amazing wife.

Share this:

9 thoughts on “Write A File In D365

Add yours

  1. Great article! It’s always helpful to have different methods to export data from Microsoft Dynamics 365, and your detailed explanation of how to write a file using X++ code is very informative.

  2. Hi Peter,

    Your article is well-explained with clear step-by-step instructions. I found it very helpful! I do have a question, though, and would greatly appreciate your assistance. What if we need to save the file at a specific path instead of the ‘Downloads’ folder?

    Thanks in advance!

    1. I need to test it. But I think you can go to the options in your browser and specify a default download folder that is different than the ‘downloads’ folder. Then, the files will download to the new location.
      Or, I believe you can change settings in the browser to ask you every time where you want to save it.
      But, I don’t believe there is anyway to make D365 prompt you as to where to save the file. I think the idea is that for security reasons the user should always have control of that, and never the website. I think this is true for all websites.

    1. Unfortunately you can’t pick a specific folder each time. It will always download to whatever folder you specify as your download folder. By default it is a folder named Download. But you can update your browser settings to specify a different folder.
      The reason for this is that the D365 website doesn’t have knowledge of the drives and folders on your computer. But your installed browser does.

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑