Wednesday, 22 February 2017

Create batch job through X++ code

Hi,

Case-1:

static void TID_ExecuteBatchJobDistribution(Args _args) { BatchHeader header; SysRecurrenceData sysRecurrenceData; Batch batch; BatchJob batchJob; RetailConnScheduleRunner _RetailConnScheduleRunner; // Class extends RunBaseBatch BatchInfo processBatchInfo; BatchRetries noOfRetriesOnFailure = 4; ; // Setup the RunBaseBatch Job header = BatchHeader::construct(); _RetailConnScheduleRunner = new RetailConnScheduleRunner(); processBatchInfo = _RetailConnScheduleRunner.batchInfo(); processBatchInfo.parmRetriesOnFailure(noOfRetriesOnFailure); processBatchInfo.parmCaption(_RetailConnSchedule.Name); // Description Batch Job processBatchInfo.parmGroupId('RTL'); // Batch Gorup processBatchInfo.parmBatchExecute(NoYes::Yes); header.addTask(_RetailConnScheduleRunner); // Set the recurrence data sysRecurrenceData = SysRecurrence::defaultRecurrence(); SysRecurrence::setRecurrenceStartDateTime(sysRecurrenceData, DateTimeUtil::addSeconds(DateTimeUtil::utcNow(), 20)); // Set range of recurrence SysRecurrence::setRecurrenceNoEnd(sysRecurrenceData); SysRecurrence::setRecurrenceUnit(sysRecurrenceData, SysRecurrenceUnit::Minute); // Set reccurence pattern header.parmRecurrenceData(sysRecurrenceData); // Set the batch alert configurations header.parmAlerts(NoYes::No, NoYes::Yes, NoYes::No, NoYes::Yes, NoYes::Yes); header.save(); // Update the frequency to run the job to every two minutes ttsbegin; select forupdate batchJob join batch where batchJob.RecId == batch.BatchJobId && batch.ClassNumber == classnum(RetailConnScheduleRunner); sysRecurrenceData = batchJob.RecurrenceData; sysRecurrenceData = conpoke(sysRecurrenceData, 8, [10]); batchJob.RecurrenceData = sysRecurrenceData; batchJob.update(); ttscommit; }

Case-2:

public static void scheduleBatch()
{
BatchHeader batchHeader; BatchInfo localBatchInfo; YourRunBaseBatchClass yourRunBaseBatchClass; SysRecurrenceData sysRecurrenceData = SysRecurrence::defaultRecurrence(); ;
yourRunBaseBatchClass = YourRunBaseBatchClass::construct();
// Retry 3-times
sysRecurrenceData = SysRecurrence::setRecurrenceEndAfter( sysRecurrenceData, 3);
//Retry 1-min
sysRecurrenceData = SysRecurrence::setRecurrenceUnit(sysRecurrenceData, SysRecurrenceUnit::Minute, 1); localBatchInfo = yourRunBaseBatchClass.batchinfo(); localBatchInfo.parmGroupId("YourBatchGroupId"); batchHeader = batchHeader::construct(); batchHeader.addTask(yourRunBaseBatchClass); batchHeader.parmRecurrenceData(sysRecurrenceData); batchHeader.save(); }

Happy DAXing...

Execute Menu Items through code

Hi,
I've seen some people trying to find out how to execute or run Menu Items programatically on the internet.

So I thought I'd best blog about it.

We have three types of Menu Items: Action, Output and Display.

An action is frequently a class that performs some business operation, an output is a report and a display is a form.

Menu Items are represented by the MenuFunction class. Here's some code example to run Menu Items through code:

?
1
2
3
4
MenuFunction menuFunction;
menuFunction = new MenuFunction(menuItemDisplayStr(MyDisplayMenuItem),
MenuItemType::Display);
menuFunction.run();

Of course the code above may be changed to execute different kinds of Menu Items, for example, the code below runs an Output Menu Item:
?
1
2
3
4
MenuFunction menuFunction;
menuFunction = new MenuFunction(menuItemOutputStr(MyOutputMenuItem),
MenuItemType::Output);
menuFunction.run();

And if you need to pass any arguments to the Menu Item you're trying to execute, you can pass it with an Args object. The run method accepts an Args parameter, like this:

?
1
2
3
4
5
6
7
Args args = new Args();
args.record(myArgumentRecord);
args.caller(this);
new MenuFunction(menuItemOutputStr(MyOutputMenuItem),
MenuItemType::Output).run(args);

You should always use functions to get the name of the menu item instead of using a hardcoded string. This guarantees that if someone changes the name of the menu item, your code stops compiling and you have time to fix it before shipping it. The following are the three functions used to get the menu items' name. Their names are pretty straightforward:


Happy DAXing...

How to export table data into csv file through RunBaseBatch class in AX 2012


How to export table data into csv file in AX 2012

Export data into csv file using X++ code in AX 2012

Hi,
CSV is a comma separated values file, which allows data to be saved in a table structured format. Traditionally they take the form of a text file containing information separated by commas.
You can export table data outside of AX into file which separates value of field with a comma. e.g., “Mohammed”, “Raziq”, “Ali”, “Hussain”,”OU”, “MCA”,”27″. Row data are separated by commas.
Lets proceed with an example to understand how to export table into CSV file. The following code writes selected table data into file with proper validations.
CommaTextIo class plays major role in writing/reading file csv in AX 2012

Case-1: In case, to export data in a single csv file

static void Job36(Args _args)
{
    CommaTextIo     file;
    container       line;
    boolean         csvHeader = false;
    VendParameters  vendParameters;
    FilePath        filePath;
    Filename        filename;
    Email           vendorEmail;
    VendAccount     vendAccount;
    DBVendPaymentJournalTmp_NA  vendPaymentJournalTmpLoc;

    select vendParameters;
    {
        filePath = vendParameters.DBPaymProposalExportPath;
    }

    if (filePath == '')
    {
        error("Please set up the location for export file.");
        return;
    }

    #define.filename('\\%1')
    #File
    while select vendPaymentJournalTmpLoc
        order by MainAccountId asc
    {
        if (!file)
        {
            filename = filePath + strFmt(#filename, vendPaymentJournalTmpLoc.MainAccountId) +#CSV;
            new FileIOPermission(filename, #io_write).assert();
            file = new CommaTextIo(filename, #io_write);
        }
        if( !file || file.status() != IO_Status::Ok)
        {
            throw error("@SYS19358");
        }

        if (!csvHeader)        
        {
            //Put headers
            line = ['@SYS17795','@SYS6303','@SYS1711','@SYS114255','@SYS24500','@SYS9624'];
            file.writeExp(line);
            csvHeader = true;
        }
        line = [vendPaymentJournalTmpLoc.JournalNum,vendPaymentJournalTmpLoc.Name,vendPaymentJournalTmpLoc.Posted,
                vendPaymentJournalTmpLoc.NumberOfJourChecks,vendPaymentJournalTmpLoc.MainAccountId,
                vendPaymentJournalTmpLoc.AccountName];
        file.writeExp(line);
        vendAccount = vendPaymentJournalTmpLoc.MainAccountId;
        vendorEmail = VendTable::find(vendPaymentJournalTmpLoc.MainAccountId).email();        
    }
        info(strFmt('File exported successfully. Please find it at %1',filePath));
}

Case-2: In case, to export data and save csv file per Vendor account

static void Job36(Args _args)
{
    CommaTextIo     file;
    container       line;
    boolean         csvHeader = false;
    VendParameters  vendParameters;
    FilePath        filePath;
    Filename        filename;
    Email           vendorEmail;
    VendAccount     vendAccount;
    DBVendPaymentJournalTmp_NA  vendPaymentJournalTmpLoc;

    select vendParameters;
    {
        filePath = vendParameters.DBPaymProposalExportPath;
    }

    if (filePath == '')
    {
        error("Please set up the location for export file.");
        return;
    }

    #define.filename('\\%1')
    #File
    while select vendPaymentJournalTmpLoc
        order by MainAccountId asc
    {
        //if (!file)
        if (vendPaymentJournalTmpLoc.MainAccountId != vendAccount)
        {
            filename = filePath + strFmt(#filename, vendPaymentJournalTmpLoc.MainAccountId) +#CSV;
            //new FileIOPermission(filename, #io_write).assert();
            file = new CommaTextIo(filename, #io_write);
        }
        if( !file || file.status() != IO_Status::Ok)
        {
            throw error("@SYS19358");
        }

        //if (!csvHeader)
        if (vendPaymentJournalTmpLoc.MainAccountId != vendAccount)        
        {
            //Put headers
            line = ['@SYS17795','@SYS6303','@SYS1711','@SYS114255','@SYS24500','@SYS9624'];
            file.writeExp(line);
            csvHeader = true;
        }
        line = [vendPaymentJournalTmpLoc.JournalNum,vendPaymentJournalTmpLoc.Name,vendPaymentJournalTmpLoc.Posted,
                vendPaymentJournalTmpLoc.NumberOfJourChecks,vendPaymentJournalTmpLoc.MainAccountId,
                vendPaymentJournalTmpLoc.AccountName];
        file.writeExp(line);
        vendAccount = vendPaymentJournalTmpLoc.MainAccountId;
        vendorEmail = VendTable::find(vendPaymentJournalTmpLoc.MainAccountId).email();        
    }
        info(strFmt('File exported successfully. Please find it at %1',filePath));
}

Happy DAXing...

Tuesday, 21 February 2017

Insert_recordset, Update_recordset, and delete_from single transaction command.

Hi,
In AX, you can manipulate a set of data by sending only one command to the database. This way of manipulating data improves performance a lot when trying to manipulate large sets of records. The commands for manipulations are insert_recordsetupdate_recordset, and delete_from. With these commands, we can manipulate many records within one database transaction, which is a lot more efficient than using the insert, update, or delete methods.
Lets discuss about these commands one by one.
  • Insert_recordset
    A very efficient way of inserting a chunk of data is to use the insert_recordset operator, as compared to using the insert() method. The insert_recordset operator can be used in two different ways; to either copy data from one or more tables to another, or simply to add a chunk of data into a table in one database operation.
    The first example will show how to insert a chunk of data into a table in one database operation. To do this, we simply use two different table variables for the same table and set one of them to act as a temporary table. This means that its content is not stored in the database, but simply held in memory on the tier where the variable was instantiated.
    static void Insert_RecordsetInsert(Args _args)
    {
    CarTable carTable;
    CarTable carTableTmp; 
    /* Set the carTableTmp variable to be a temporary table.
    This means that its contents are only store in memory
    not in the database.
    */
    carTableTmp.setTmp();
    // Insert 3 records into the temporary table.
    carTableTmp.CarId = “200”;
    carTableTmp.CarBrand = “MG”;
    carTableTmp.insert();
    carTableTmp.CarId = “300”;
    carTableTmp.CarBrand = “SAAB”;
    carTableTmp.insert();
    carTableTmp.CarId = “400”;
    carTableTmp.CarBrand = “Ferrari”;
    carTableTmp.insert();
    /* Copy the contents from the fields carId and carBrand
    in the temporary table to the corresponding fields in
    the table variable called carTable and insert the chunk
    in one database operation.
    */
    Insert_Recordset carTable (carId, carBrand)
    select carId, carBrand from carTableTmp;
    }
    The other, and perhaps more common way of using the insert_recordset operator, is to copy values from one or more tables into new records in another table. A very simple example on how to do this can be to create a record in the InventColor table for all records in the InventTable.
    static void Insert_RecordsetCopy(Args _args)
    {
    InventColor inventColor;
    InventTable inventTable;
    This material is copyright and is licensed for the sole use by ALESSANDRO CAROLLO on 18th December
    Chapter 6
    [ 169 ]
    InventColorId defaultColor = “B”;
    Name defaultColorName = “Blue”;
    insert_recordset inventColor (ItemId, InventColorId, Name)
    select itemId, defaultColor, defaultColorName
    from inventTable;
    }
    The field list inside the parentheses points to fields in the InventColor table.
    The fields in the selected or joined tables are used to fill values into the fields in
    the field list. 
  • Update_recordset
    The update_recordset operator can be used to update a chunk of records in a table in one database operation. As with the insert_recordset operator the update_recordset is very efficient because it only needs to call an update in the database once.
    The syntax for the update_recordset operator can be seen in the next example:
    static void Update_RecordsetExmple(Args _args)
    {
    CarTable carTable;
    info(“BEFORE UPDATE”);
    while select carTable
    where carTable.ModelYear == 2007
    {
    info(strfmt(“CarId %1 has run %2 miles”,
    carTable.CarId, carTable.Mileage));
    }
    update_recordset carTable setting Mileage = carTable.Mileage + 1000
    where carTable.ModelYear == 2007;
    info(“AFTER UPDATE”);
    while select carTable
    where carTable.ModelYear == 2007
    {
    info(strfmt(“CarId %1 has now run %2 miles”,
    carTable.CarId, carTable.Mileage));
    }
    } 
    When this Job is executed it will print the following messages to the Infolog: 
    Notice that no error was thrown even though the Job didn’t use selectforupdate, ttsbegin, and ttscommit statements in this example. The selectforupdate is implicit when using the update_recordset, and the ttsbegin and ttscommit are not necessary when all the updates are done in one database operation. However, if you were to write several update_recordset statements in a row, or do other checks that should make the update fail, you could use ttsbegin and ttscommit and force a ttsabort if the checks fail.
  • Delete_from
    As with the insert_recordset and update_recordset operators, there is also an option for deleting a chunk of records. This operator is called delete_from and is used as the next example shows:
    static void Delete_FromExample(Args _args)
    {
    CarTable carTable;
    delete_from carTable
    where carTable.Mileage == 0;
    }