Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Microsoft Dynamics AX 2012 Development Cookbook

You're reading from   Microsoft Dynamics AX 2012 Development Cookbook Customizing Dynamics AX to suit the specific needs of an organization is plain sailing when you use this cookbook of modifications. With more than 80 practical recipes it's the perfect handbook for all Dynamics AX developers.

Arrow left icon
Product type Paperback
Published in May 2012
Publisher Packt
ISBN-13 9781849684644
Length 372 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Mindaugas Pocius Mindaugas Pocius
Author Profile Icon Mindaugas Pocius
Mindaugas Pocius
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Microsoft Dynamics AX 2012 Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
1. Preface
1. Processing Data FREE CHAPTER 2. Working with Forms 3. Working with Data in Forms 4. Building Lookups 5. Processing Business Tasks 6. Integration with Microsoft Office 7. Using Services 8. Improving Development Efficiency 9. Improving Dynamics AX Performance

Creating a comma-separated value file


Comma-Separated Value (CSV) files are widely used across various systems. Although nowadays modern systems use XML formats for data exchange, CSV files are still popular because of the simplicity of their format.

Normally, the data in the file is organized so one line corresponds to one record, and each line contains a number of values normally separated by commas. Record and value separators could be any other symbol, depending on the system requirements.

In this recipe, we will learn how to create a custom comma-separated file from code. We will export a list of ledger accounts—the CSV format.

How to do it...

Carry out the following steps in order to complete this recipe:

  1. 1. Open the AOT, and create a new class named CreateCommaFile with the following code:

    class CreateCommaFile
    {
    }
    public static client void main(Args _args)
    {
    CommaTextIo file;
    container line;
    MainAccount mainAccount;
    #define.filename(@'C:\Temp\accounts.csv')
    #File
    file = new CommaTextIo(#filename, #io_write);
    if (!file || file.status() != IO_Status::Ok)
    {
    throw error("File cannot be opened.");
    }
    while select MainAccountId, Name from mainAccount
    {
    line = [
    mainAccount.MainAccountId,
    mainAccount.Name];
    file.writeExp(line);
    }
    info(strFmt("File %1 created.", #filename));
    }
    
  2. 2. Run the class. A new file named accounts.csv should be created in the specified folder. Open that file with Notepad or any other text editor to view the results:

How it works...

In the variable declaration section of the main() method of the newly created CreateCommaFile class, we define a name for the output file, along with other variables. Normally, this should be replaced with a proper input variable. Here, we also define a standard #File macro, which contains a number of file-handling modes, such as #io_read, #io_write, #io_append, and so on, file types, delimiters, and other things.

Next, we create a new CSV file by calling the new() method on a standard CommaIo class. It accepts two parameters—filename and mode. For mode, we use #io_write from the #File macro to make sure a new file is created and opened for further writing. If a file with the given name already exists, then it will be overwritten. In order to make sure that a file is created successfully, we check if the file object exists and its status is valid, otherwise we show an error message.

In multilingual environments, it is better to use the CommaTextIo class. It behaves the same way as the CommaIo class does plus it supports Unicode, which allows us to process data with various language-specific symbols.

Finally, we loop though the MainAccount table, store all account numbers and their names in a container, and write them to the file using the writeExp() method.

In this way, we create a new comma-separated value file with the list of ledger accounts.

There's more...

You probably already noticed that the main() method has the client modifier, which forces its code to run on the client. When dealing with large amounts of data, it is more effective to run the code on the server. In order to do that, we need to change the modifier to server. The following class generates exactly the same file as before, except that this file is created in the folder on the server's file system:

class CreateCommaFileServer
{
}
public static server void main(Args _args)
{
CommaTextIo file;
container line;
MainAccount mainAccount;
FileIoPermission perm;
#define.filename('C:\\Temp\\accounts.csv')
#File
perm = new FileIoPermission(#filename, #io_write);
perm.assert();
file = new CommaTextIo(#filename, #io_write);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
while select mainAccount
{
line = [
mainAccount.MainAccountId,
mainAccount.Name];
file.writeExp(line);
}
CodeAccessPermission::revertAssert();
info(strFmt("File %1 created.", #filename));
}

File manipulation on the server is protected by Dynamics AX code access security and we must use the FileIoPermission class to make sure we match the requirements.

Finally, we call CodeAccessPermission::revertAssert() to revert the previous assertion.

You have been reading a chapter from
Microsoft Dynamics AX 2012 Development Cookbook
Published in: May 2012
Publisher: Packt
ISBN-13: 9781849684644
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image