Wednesday, August 26, 2015

Creation of .txt/.csv files with AX 2009

Requirement: Export database log to a .csv/.txt file in AX 2009
Process:
Step 1: Create a class with name “exportDataBaseLog” and methods. Create an action menu item with name “exportDataBaseLog” and lebel “Export to csv”
Step 2: Add action menu item (exportDataBaseLog) in form “Database log” (path: Administration> Inquiry> Database log) 












On click of button “Export to csv” a dialog will open for asking name of file















When we click on browse we will get a screen asking for file and location














On “Save” again we will see same dialog with name of file















On click Ok an info log will appear for location and file.























Elaborated technical approach
Step 1:  Create a class with name “exportDataBaseLog” and methods(for .txt we can replace .csv by .txt)
class exportDataBaseLog extends RunBaseBatch
{
    // Packed variables
    FileNameSave            filename;
    System.Exception    e;
    QueryRun            queryRun;
    //str                 filename;

    // Dialog fields
    DialogField     dlgFileName;

    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filename
    #endmacro
}
public Object dialog()
{
    DialogRunbase       dialog = super();
    #resAppl
;
    dialog.filenameLookupFilter(["csv  files","*.csv"]);
    dlgFileName = dialog.addFieldValue(typeid(FileNameSave),filename);

    return dialog;
}
public boolean getFromDialog()
{
    ;
    filename   = dlgFileName.value();
    return super();
}
void createLogInCSV()
{
    TextIO                  file;
    FileIOPermission        fileIOPermission;
    container               line,header,header2;
    SysDataBaseLog          dataBaseLog;
    List                    modifiedFieldValueList;
    ListEnumerator          enumerator;
    Map                     OldValue, newValue;
    container               tmp;
    FormListItem            item;
    fieldId                 fieldId;

    #File
    ;
    new FileIOPermission(this.fileName()+'.csv','w').assert();
    file = new TextIO(this.fileName()+'.csv',#io_write,1250);

    file.outFieldDelimiter(',');
    header = ['Database Log export'];
    header2 = ['Name of table','Record Identification','Type of change','Created date and time','created by','Field name','Value','Previous value'];
    file.write(header);
    file.write(header2);
    while select dataBaseLog order by CreatedDateTime desc
    {
        line = connull();
        modifiedFieldValueList = dataBaseLog.getDataAslist();
        enumerator = modifiedFieldValueList.getEnumerator();
        while (enumerator.moveNext())
        {
            tmp = enumerator.current();
            fieldId = conpeek(tmp, 1);
            line= [TableId2pName(dataBaseLog.table),
strReplace(dataBaseLog.Description,',',';'),
enum2str(dataBaseLog.LogType),                    datetime2str(dataBaseLog.createdDateTime),
dataBaseLog.createdBy,
FieldId2Name(dataBaseLog.table,fieldId),
strrem(dataBaseLog.contents2Str(conpeek(tmp, 2),fieldId),','),
strrem(dataBaseLog.contents2Str(conpeek(tmp, 3),fieldId),',')];
            file.write(line);
        }
    }
   
info(strfmt("Please check log excel in path %1", filename));

}
public void run()
{
    #OCCRetryCount

    try
    {
        ttsbegin;
        this.createLogInCSV();
        ttscommit;
    }
    catch (Exception::Deadlock)
    {
        retry;
    }

    catch (Exception::UpdateConflict)
    {
        if (appl.ttsLevel() == 0)
        {
            if (xSession::currentRetryCount() >= #RetryNum)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }

}
public container pack()
{
    return [#CurrentVersion,#CurrentList];
}
public boolean unpack(container packedClass)
{
    Version version = RunBase::getVersion(packedClass);
;
    switch (version)
    {
        case #CurrentVersion:
            [version,#CurrentList] = packedClass;
            break;
        default:
            return false;
    }

    return true;
}
static void main(Args args)
{
    exportDataBaseLog    dataBaseDetailedLogExtract;
;
    dataBaseDetailedLogExtract = exportDataBaseLog::construct();

    if (dataBaseDetailedLogExtract.prompt())
        dataBaseDetailedLogExtract.run();
}

Result: TestCSVFile.csv
 


2 comments:

  1. please tell me how to write this.fileName() function

    ReplyDelete
  2. Hi, there's 4 type of .CSV.
    CSV UTF-8, CSV Comma delimited, CSV Macintosh and CSV MS-DOS. how to define each them using x++?

    ReplyDelete