Dynamics Ax Implementing an InventDim form control

Hi All,

Yesterday I was struggling a bit with an InventDim form control on a custom-made form. The problem was that the product dimension look ups were returning none or too much results like example 1. While the correct result should look like example 2.

Example 1

Example 2

The problem was that I’ve named the item field ServiceItemId instead of ItemId. This is a problem because the class InventDimCtrl_Frm_Lookup looks hard-coded for an ItemId field when you do a look up on an inventory dimension. But there is an exception, the class also looks for a method called itemId. So if you have another field or maybe have 2 item fields on the same table you can implement something like this method to return the correct ItemId.

public ItemId itemId()
{
    ;
 
    return BLOGInventDimDemoTable.ServiceItemId;
}

Dynamics Ax composite queries

Hi all,

Currently I’m working on a new Dynamics Ax 2012 project and for that I’m developing a lot of list pages and forms. For these I had to make multiple menu items that open a list page with different filters, you can do this by setting the menu item query property or calling a class which calls the form with the correct query. So this involves creating a lot of query objects for the same table with only a few extra filters. If only there was a way to inherit queries from each other and there is! :-)

It’s called composite queries and it’s only useful when you just want to extend your query with range or overriding a method. Also you can only derive one time from a query.

An example:

First I’ve created a base query that filters on  Sales Type with value Sales Order. So I have a query that filters all regular sales orders.

 

 

 

 

Next I’m creating a new query without any data sources and I drag my base query to the Composite query node. Then I can add my specific range, such as on Sales Status with value back order.

 

 

 

 

 

That’s it! Now I can create multiple queries such as for delivered or invoiced orders and if I want to apply and extra range for all the queries I only have to change the base query.

source: MSDN

MS SQL Server performance with Dynamics Ax

Hi,

Lately I’m working on some projects who experience a bad performance in Dynamics Ax. This can have multiple causes but one of the most important is maintaining the SQL Server. In my humble opinion every Dynamics Ax developer should have a basic knowledge on how SQL Server works and is maintained because it is the backbone of our beloved ERP software. :-) .

This said if terms like rebuilding and reorganizing indexes, updating statistics or recovery model don’t ring a bell these links will be very interesting for you ;-) .

 

Dynamics Ax RunBase overriding dialog with a Form

Hi,

Some time ago I’ve found out that you can implement a form into a RunBase dialog, this has the advantage that you can easily use a grid control, etc… or use modified field methods without using controlMethodOverload() method. You can do this by overriding the dialog method and adding the following code.

DialogRunbase  dialogRunbase = Dialog::newFormnameRunbase(formstr(BLOGRunBaseDialogExample), this);
;
return super(dialogRunbase);

You can still add fields the normal way by using the addFieldValue() method, these fields will appear next to the embedded form.

This form must have a Tab control and some hardcoded groups, also on the design the property FrameType must be set to None. The groups I’ve created are DialogStartGrp and RightButtonGrp, these are used for positioning fields and query values from code. More groups may be necessary when extending from RunBaseBatch, RunBaseReport, …  The tab control is used for adding a batch tab when extending from RunBaseBatch.

In the dialogPostRun() method you can get the formRun of the dialog and make calls to the form, for example setting query ranges.

public void dialogPostRun(DialogRunbase dialog)
{
    Object  formRun;
    ;
 
    if(FormHasMethod(dialog.formRun(),"setQueryRanges"))
    {
        formRun = dialog.formRun();
        formRun.setQueryRanges();
    }
 
    super(dialog);
}

A way to pass data or do callbacks is to get the calling class in the form init.

public void init()
{
    super();
 
    if( element.args()                                  &&
        element.args().caller()                         &&
        element.args().caller().RunBase()               &&
        ClassIdGet(element.args().caller().RunBase())   == ClassNum(BLOGRunBaseDialogExample))
    {
        // Do something
    }
}

Dynamics Ax printing logo’s from batch

Hi,

*Edit Microsoft has released a fix for this problem contact support for this*

As all of you know the Image class in Dynamics Ax 4.0 and 2009 can only run on client. This poses a problem when you want to print for example invoices with your company logo on it. Having this found out I went to look for an alternative!

I’ve added this code to the top of the PDFViewer class in the writeBitmap(OutputBitmapField _field, OuputSection _section) method

if( isRunningOnServer() &&
    _field.name()       == #FieldLogo)
{
    this.BLOGWriteBitmapOnServer(_field,_section);
    super(_field, _section);
    return;
}

For the method BLOGWriteBitmapOnServer(OutputBitmapField _field, OuputSection _section) I have copied everything from the writeBitmap and started by replacing the Image object with a System.Drawing.Image object, you can make a company parameter for this file path.

img = System.Drawing.Image::FromFile(imgStr);

After compiling there are a few errors witch I’ve corrected and ended up with this code.

public void BLOGWriteBitmapOnServer(OutputBitmapField _field, OuputSection _section)
{
    #File
    BinData bin = new BinData();
    //Image img;
    container data, imgInfoData;
    str s;
    real x1,x2, y1,y2;
    Struct br;
    int imageObjectNo = 0;
    int newwidth, newheight;
    real pdfPreviewScale = 0.8;
    boolean generateXImage = false;
    container c;
    str fn;
    FileIOPermission writePermission;
    FileIOPermission readPermission;
    boolean grayScale = false;
 
    System.Drawing.Image    img;
    str                     imgStr;
    int                     widthTemp, heightTemp;
    CompanyInfo             companyInfo = companyInfo::find();
    ;
 
    new InteropPermission(InteropKind::ClrInterop).assert();
 
    imgStr  = companyInfo.BLOGCompanyLogoFile;
 
    br = this.boundingRectTwips(currentPage, _section, _field);
 
    x1 = br.value('x1'); y1 = br.value('y1');
    x2 = br.value('x2'); y2 = br.value('y2');
 
    if (_field.type() == 10) // resourceId, DB_RESId
    {
        //img = new Image(_field.resourceId());
        img = System.Drawing.Image::FromFile(imgStr);
 
        if (resourceIdImageMap.exists(_field.resourceId()))
            imageObjectNo = resourceIdImageMap.lookup(_field.resourceId());
        else
        {
            imageObjectNo = this.nextObjectNo();
            resourceIdImageMap.insert(_field.resourceId(), imageObjectNo);
            generateXImage = true;
        }
 
        if (debugLevel >= 1)
            info ('Image in resource ' + int2str(_field.resourceId()));
    }
    else if (_field.type() == 7) // queue
    {
        c = _field.value();
        if (c)
        {
            //img = new Image(c);
            img = System.Drawing.Image::FromFile(imgStr);
 
            imageObjectNo = this.nextObjectNo();
        }
        generateXImage = true;
 
        if (debugLevel >= 1)
        {
            if (img)
                info ('Image in container');
            else
                info ('No image in container');
        }
    }
    else // string containing filename
    {
        //img = new Image(_field.imageFileName());
        img = System.Drawing.Image::FromFile(imgStr);
 
        if (stringImageMap.exists(_field.imageFileName()))
            imageObjectNo = stringImageMap.lookup(_field.imageFileName());
        else
        {
            imageObjectNo = this.nextObjectNo();
            stringImageMap.insert(_field.imageFileName(), imageObjectNo);
            generateXImage = true;
        }
 
        if (debugLevel >= 1)
            info ('File is ' + _field.imageFileName());
    }
 
    if (img)
    {
        if (generateXImage)
        {
            fn  = System.IO.Path::GetTempFileName();
 
            widthTemp   = img.get_Width();
            heightTemp  = img.get_Height();
 
            img.Save(fn);
 
            // revert previous assertion
            CodeAccessPermission::revertAssert();
 
            // assert read permissions
            readPermission = new FileIOPermission(fn, #io_read);
            readPermission.assert();
 
            // BP deviation documented (note that the file io assert IS included above)
            bin.loadFile(fn);
            data = bin.getData();
 
            // Get rid of the temporary file.
            //WinAPIServer::deleteFile(fn);
 
            CodeAccessPermission::revertAssert();
            new InteropPermission(InteropKind::ClrInterop).assert();
            System.IO.File::Delete(fn);
 
            if (bitmapEncode85)
                s = bin.ascii85Encode();
            else
                s = BinData::dataToString(data);
 
            objectOffsetMap.insert(imageObjectNo, binBuffer.size());
 
            this.appendTextToBuffer(int2str(imageObjectNo) + ' 0 obj <

This could probably been done much cleaner, but it does the job. :-)

Dynamics Ax Reports with Calibri font

Hi,

A customer of mine asked me to change the font of some reports to Calibri. It all went well until we saved a report as PDF, there was way too much spacing between characters.

After some days of investigating and contact with Microsoft I’ve found out that it worked on a Windows Server 2008 R2 and the Calibri font files were almost double in size. So I replaced the font files with the ones from Windows Server 2008 R2 and the reports are working like a charm. :-)

Dynamics ax take screenshots from FormControls

Hi all,

Here is a little code snippet for you to take screen shots within a Dynamics Ax client.

public void run(FormControl _control)
{
    str                         SaveToFileName;
    System.Drawing.Bitmap           bitmap;
    System.Drawing.Graphics        graphics;
    System.Windows.Forms.Screen primaryScreen;
    System.Drawing.Rectangle       bounds;
 
    int                                       x, y, k, l;
    System.Int32                         width;
    System.Int32                         height;
 
    #define.FileName('DynamicsAx_Screenshot.png')
    ;
 
    try
    {
        // 5 for the My Documents folder
        SaveToFileName  = strfmt(@"%1%2",WinApi::getFolderPath(5),#FileName);
 
        primaryScreen   = System.Windows.Forms.Screen::get_PrimaryScreen();
        bounds          = primaryScreen.get_Bounds();
 
        [x, y, k, l]    = WinApi::getWindowRect(_control.hWnd());
 
        width           = _control.widthValue();
        height          = _control.heightValue();
 
        // TwC: used API CLRObject
        // BP Deviation Documented
        bitmap          = new System.Drawing.Bitmap(width,height);
 
        graphics        = System.Drawing.Graphics::FromImage(bitmap);
        graphics.CopyFromScreen(x,y,0,0,bitmap.get_Size());
 
 
        bitmap.Save(SaveToFileName, System.Drawing.Imaging.ImageFormat::get_Png());
    }
    catch
    {
        error("The file could not be saved"); // TODO make label
    }
}

This snippets uses the size of your control and the position on your screen to create the screenshot :-)

Dynamics Ax printing from the AOS

Hello,

This post will be all about printing from printers that are connected on the AOS instead of the client.

First up is installing a printer on the server thats hosts the AOS services. Next is configuring the client and server as shown in the next screenshots:

In the printer setup you should now be able to choose from printers with the prefix “AOS:”

*edit* : If the printer does not show up, try restarting the windows ‘Print Spooler’ service.

Many application object servers today are installed on 64bit operating systems this can cause problems when trying to connect a network printer that is hosted on a 32bit printer server. You might choose to upgrade the operating system of the printer server and face more drivers problems with other 32bit clients or install a secondary 64bit printer server, witch seems overkill.  A better is when the printer is connected directly to the LAN install it on the server thats hosts the AOS services. You can do this by installing the printer local with a TCP/IP port and using the 64bit driver.

Dynamics ax unknown software exception

Hi,

Ever had this error “The exception unknown software exception (0xc0000417) occured in the application at 0x00a13c18″.

Solving it is easy, just erase the .AUC files in the folder:

C:Documents and Settings*Current user*Local SettingsApplication Data

Or for Windows 7 / Windows server 2008 users:

C:Users*Current user*AppDataLocal

Dynamics Ax SQL Trace

Hi there,

here is a simple job to enable SQL tracing for all your users, this quite handy for optimizing queries. (The macro’s for modifying other fields on the UserInfo table can be found on the ClassDeclaration of the SysUserSetup form.)

boolean     enable      = true;
UserInfo    userInfo;
 
#LOCALMACRO.FLAG_SQLTrace                       ( 1 << 8 ) #ENDMACRO
#LOCALMACRO.FLAG_TraceInfoQueryTable            ( 1 << 11 ) #ENDMACRO
;
 
ttsbegin;
while select forupdate userInfo
{
    if(enable)
    {
        userInfo.DebugInfo      = userInfo.DebugInfo | #FLAG_SQLTrace;
        userInfo.TraceInfo      = userInfo.TraceInfo | #FLAG_TraceInfoQueryTable;
        userInfo.querytimeLimit = 100;
    }
    else
    {
        userInfo.DebugInfo      = userInfo.DebugInfo ^ #FLAG_SQLTrace;
        userInfo.TraceInfo      = userInfo.TraceInfo ^ #FLAG_TraceInfoQueryTable;
    }
    userInfo.update();
}
ttscommit;

Make sure that client tracing is enabled in the server configuration. (Only use this in development and testing environments, tracing may affect the AOS performance.)

The results can be found in the Administration module.

Dynamics Ax RunBaseBatch multithreading

Hi,

Next post will be a little tutorial on how the RunBaseBatch framework can work multithreaded. For example in the SalesFormLetter class on the method run, the following code will be found before the query iteration:

if (this.canMultiThread())
{
    batchHeader = BatchHeader::construct(this.parmCurrentBatch().BatchJobId);
    salesFormLetterEndMultiThread = SalesFormLetterEndMultiThread::newFormLetter(this,
                                                                                 salesParmUpdate.ParmId,
                                                                                 salesParmUpdate.Proforma);
    batchHeader.addRuntimeTask(salesFormLetterEndMultiThread,this.parmCurrentBatch().RecId);
}

The SalesFormLetterEndMultiThread that is being created will be called when all threads connected to that bacth are processed, this will call methods like printJournal and endUpdate. Notice that all the variables that are passed in the construct method are also  defined in the CurrentList macro for packing and unpacking, this is important to keep in mind when writing custom code.

In the iteration itself, another multithread batch task is created for each line.

if (batchHeader)
{
    formLetterMultiThread = FormLetterMultiThread::newFormLetter(this);
    batchHeader.addRuntimeTask(formLetterMultiThread,this.parmCurrentBatch().RecId);
    batchHeader.addDependency(salesFormLetterEndMultiThread,formLetterMultiThread,BatchDependencyStatus::FinishedOrError);
}

So foreach SalesParmTable found an instance of the runtime task FormLetterMultiThread is created, and is a dependency for the SalesFormLetterEndMultiThread to run.

Now let’s create our own simple example.

Start by creating a RunBaseBatch class like you would otherwise do, but make sure that the code witch uses the most load is written in a separate method and called from the run. This method will be called from the threads. (method: updateSalesOrder)

The canMultiThread method is the same as in the FormLetter class.

protected boolean canMultiThread()
{;
    return this.isInBatch();
}

And the run method could be written like this, analog to the run of the SalesFormLetter class, but without an ending thread.

void run()
{
    int batchCounter    = 0;
    ;
    try
    {
        ttsbegin;
 
        if(this.canMultiThread())
        {
            batchHeader     = BatchHeader::construct(this.parmCurrentBatch().BatchJobId);
        }
 
        while(this.queryRun().next())
        {
            salesTable  = this.queryRun().get(TableNum(SalesTable));
 
            if(batchHeader)
            {
                tSTSalesOrderUpdateMultiThread  = TSTSalesOrderUpdateMultiThread::newFromTSTSalesOrderUpdate(this);
                batchHeader.addRuntimeTask(tSTSalesOrderUpdateMultiThread,this.parmCurrentBatch().RecId);
 
                batchCounter++;
            }
            else
            {
                this.updateSalesOrder();
            }
        }
 
        if(batchHeader)
        {
            batchHeader.save();
 
            info(strfmt("%1 batches created",batchCounter));
        }
 
        ttscommit;
    }
    catch(Exception::Error)
    {
        ttsabort;
    }
    catch(Exception::Deadlock)
    {
        retry;
    }
}

The second class you need to create is kind of a wrapper class that also extends from RunBaseBatch and will be used to create the subtasks for your batch process. Make sure that the runsImpersonated method returns true.

Remember that you need to keep an instance of the caller class (TSTSalesOrderUpdate) and you need to pack and unpack it.

class TSTSalesOrderUpdateMultiThread extends RunBaseBatch
{
    BatchHeader         batchHeader;
 
    TSTSalesOrderUpdate salesOrderUpdate;
    container           packedSalesOrderUpdate;
 
    #define.CurrentVersion(2)
    #LOCALMACRO.CurrentList
        packedSalesOrderUpdate
    #ENDMACRO
}
 
public static TSTSalesOrderUpdateMultiThread newFromTSTSalesOrderUpdate(TSTSalesOrderUpdate  _caller)
{
    TSTSalesOrderUpdateMultiThread   instance;
    ;
 
    instance    = TSTSalesOrderUpdateMultiThread::construct();
    instance.parmSalesOrderUpdate(_caller);
 
    return instance;
}
 
public container pack()
{;
    packedSalesOrderUpdate  = salesOrderUpdate.pack();
    return [#CurrentVersion,#CurrentList];
}
 
public boolean unpack(container _packedClass)
{
    int version     = RunBase::getVersion(_packedClass);
 
    switch (version)
    {
        case #CurrentVersion:
            [version,#CurrentList] = _packedClass;
 
            salesOrderUpdate    = TSTSalesOrderUpdate::construct();
            salesOrderUpdate.unpack(packedSalesOrderUpdate);
            return true;
        default :
            return false;
    }
 
    return false;
}

The run method should call the updateSalesOrder on your TSTSalesOrderUpdate class. This means that all the logic is placed in one place, because it should also work when not running in batch. ;-)

void run()
{
    ;
    try
    {
        ttsbegin;
        salesOrderUpdate.updateSalesOrder();
        ttscommit;
    }
    catch(Exception::Error)
    {
        ttsabort;
        throw error("error");
    }
    catch(Exception::Deadlock)
    {
        retry;
    }
}

In addition you can add an ending multithread class if necessary, like the FormLetterEndMultiThread class.  The maximum number of simultaneous batch thread can be defined on the SysServerConfig form.

The example given is only for educational purposes. (It is somewhat sloppy :-) )

Dynamics Ax creating a batch job from code

Hi,

Here is a simple code snippet to create Batch jobs from code. This convenient when starting a heavy load job from a user interface and still keep the client responsive.

TSTSalesOrderUpdate tSTSalesOrderUpdate;
 
BatchInfo           batchInfo;
BatchHeader         batchHeader;
;
 
tSTSalesOrderUpdate = TSTSalesOrderUpdate::construct();
 
batchInfo   = tSTSalesOrderUpdate.batchInfo();
batchInfo.parmCaption("Test from code");
batchInfo.parmGroupId("");
 
batchHeader = BatchHeader::construct();
batchHeader.addTask(tSTSalesOrderUpdate);
batchHeader.save();

Creating sales orders with the SalesAutoCreate class

Many projects use an interface to import their sales orders, because of this a SalesAutoCreate class was created. This class is easily extendable and customizable.The first thing to do is designing a buffer table, like this one for example:

After this we can start extending a new class from the SalesAutoCreate class and modifying the construct on the SalesAutoCreateClass .

class TSTSalesAutoCreate extends SalesAutoCreate
{
    TSTSalesImport  TSTSalesImport;
}
static  SalesAutoCreate    construct(Common       buffer = null,
                                     Object       object = null,
                                     Common       buffer2 = null)
{
    switch (buffer.TableId)
    {
        case tablenum(SalesCreateReleaseOrderLineTmp)     : return new SalesAutoCreate_ReleaseOrder(buffer,object,buffer2);
        case tablenum(PurchLine)                          : return new SalesAutoCreate_ProjPurchLine(buffer,object);
        case tablenum(SalesBasketLine)                    : return new SalesAutoCreate_Basket(buffer,object);
        //-> TST
        case tablenum(TSTSalesImport)                     : return new TSTSalesAutoCreate(buffer,object);
        //<- TST
    }
    throw error(strfmt("@SYS23419",tableid2name(buffer.TableId)));
}

After the construct your buffer record should be passed in the new or a parm method could also be an option.

void new(Common _initFromBuffer, Object _callBackClass)
{;
    super(_initFromBuffer,_callBackClass);
 
    TSTSalesImport  = _initFromBuffer;
}

When extending from the SalesAutoCreate class some methods must be implemented:

  • setCust
  • salesType
  • recordExist
  • nextRecord
  • invoiceAccount

In my example I’ve implemented them like this:

protected void setCust()
{;
    custTable   = CustTable::find(TSTSalesImport.CustAccount);
 
    if(!custTable)
    {
        throw error("Custtable not found!");
    }
}
 
protected SalesType salesType()
{;
    return SalesType::Sales;
}
 
protected boolean recordExist()
{;
    return TSTSalesImport.RecId != 0;
}
 
protected void nextRecord()
{;
    next TSTSalesImport;
}
 
protected CustInvoiceAccount invoiceAccount()
{
    CustInvoiceAccount  ret = custTable.InvoiceAccount;
    ;
 
    if(!ret)
    {
        ret = custTable.AccountNum;
    }
 
    return ret;
}

The next step is setting our table and line fields by overriding the setSalesTable and setSalesLine methods and make sure that you always call the super first. Notice that you need to call the createSalesTable and createSalesLine to do the insert.

protected void setSalesTable()
{;
    super();
 
    this.createSalesTable();
}
 
protected void setSalesLine()
{;
    super();
 
    salesLine.ItemId    = TSTSalesImport.ItemId;
    salesLine.itemIdChanged();
    salesLine.SalesQty  = TSTSalesImport.SalesOrderedQty;
 
    this.createSalesLine();
}

you should have a class looking like this.

the final step is to call the logic from a job or a RunBaseBatch class, make sure that you select records on the same tier as the nextRecord will run or else it will fail. Preferably on the server tier. :)

select forupdate TSTSalesImport;
 
SalesAutoCreate = SalesAutoCreate::construct(TSTSalesImport);
SalesAutoCreate.create();

This example lacks some validation whether the record has already been processed or not, so it will created the same records every time it is called. You could implement your own method on the SalesAutoCreate class, call it from the create method and override it on your custom class, like this.

void  create()
{
    #OCCRetryCount
 
    try
    {
        setprefix("@SYS55110");
 
        ttsbegin;
 
        while (this.recordExist())
        {
 
            this.setCust();
 
            setprefix(#PreFixField(CustTable,AccountNum));
 
            this.setSalesTable();
 
            this.setSalesLine();
 
            setprefix(#PreFixField(SalesLine,ItemId));
 
            //-> TST
            this.deleteProcessed();
            //<- TST
 
            this.nextRecord();
        }
 
        this.endUpdate();
 
        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;
        }
    }
 
}
 
//SalesAutoCreate
protected void deleteProcessed()
{
}
 
//TSTSalesImport
protected void deleteProcessed()
{;
    super();
 
    TSTSalesImport.selectForUpdate(true);
    TSTSalesImport.delete();
}

Cleaning up the AIF document log

While doing a small AIF project I wrote a small batch class to cleanup the AIF document log because the button on the AifDocumentHistory form can take up a huge amount of time. The first thing I did to write this class is checking out the standard Ax code in the following method ClassesAifMessageManagerclearAllProcessedAndError. This method uses a progress bar and deletes records in batches of 3000 records, this is something we don’t need when running in batch.

The first thing our method needs to do is check if we have access rights to delete.

if (    !hasTableAccess(tablenum(AifMessageLog),    AccessType::Delete)
    ||  !hasTableAccess(tablenum(AifDocumentLog), AccessType::Delete)
    ||  !hasTableAccess(tablenum(AifCorrelation),    AccessType::Delete))
{
    throw error("@SYS113226");
}

The second step is requesting the permission to skip AOS validation.

skipAOS = new SkipAOSValidationPermission();
skipAOS.assert();

The next step is calling all the skip methods, Microsoft does this to make sure that a delete_from doesn’t fall back to row by row deletes.

  • skipAosValidation : Skips all validation methods (validateWrite, validateDelete, validateField)
  • skipDatabaseLog : Prevents SQL from making transactions logs.
  • skipDataMethods : Forces doInsert, doUpdate instead of insert, update.
  • skipDeleteActions : Skips all actions defined under DeleteActions ( For example: Deleting a SalesTable also deletes all referencing MarkupTrans records. )
  • skipDeleteMethod : Forces doDelete instead of delete.
  • skipEvents : Disables a lot of kernel events to increase performance.
aifMessageLog.skipAosValidation(true);
aifMessageLog.skipDatabaseLog(true);
aifMessageLog.skipDataMethods(true);
aifMessageLog.skipDeleteActions(true);
aifMessageLog.skipDeleteMethod(true);
aifMessageLog.skipEvents(true);
 
aifDocumentLog.skipDatabaseLog(true);
aifDocumentLog.skipDataMethods(true);
aifDocumentLog.skipDeleteActions(true);
aifDocumentLog.skipDeleteMethod(true);
//BP Deviation Documented
aifDocumentLog.skipAosValidation(true);
aifDocumentLog.skipEvents(true);
 
aifCorrelation.skipDatabaseLog(true);
aifCorrelation.skipDataMethods(true);
aifCorrelation.skipDeleteActions(true);
aifCorrelation.skipDeleteMethod(true);
//BP Deviation Documented
aifCorrelation.skipAosValidation(true);
aifCorrelation.skipEvents(true);

After these methods we can start deleting the records, I’ve used a utcDateTimeRemove variable to cleanup records after a certain number of days.

delete_from     aifDocumentLog
    exists join aifMessageLog
        where   aifDocumentLog.MessageId        == aifMessageLog.MessageId
        &&      aifMessageLog.createdDateTime   <= utcDateTimeRemove
        &&     (aifMessageLog.Status            == AifMessageStatus::Processed
                                                ||
                aifMessageLog.Status            == AifMessageStatus::Error);
 
delete_from     aifCorrelation
    exists join aifMessageLog
        where   aifCorrelation.MessageId        == aifMessageLog.MessageId
        &&      aifMessageLog.createdDateTime   <= utcDateTimeRemove
        &&     (aifMessageLog.Status            == AifMessageStatus::Processed
                                                ||
                aifMessageLog.Status            == AifMessageStatus::Error);
 
delete_from aifMessageLog
    where   aifMessageLog.createdDateTime       <= utcDateTimeRemove
    &&     (aifMessageLog.Status                == AifMessageStatus::Processed
                                                ||
            aifMessageLog.Status                == AifMessageStatus::Error);

The final step is to revert the code access permission.

CodeAccessPermission::revertAssert();

Source : msdn xRecord class

(this job should never run on a production environment, build an archiving alternative instead)

Dynamics Ax 2009 using the DateTimeUtil

Since i’m getting a lot of google hits on my Dynamics Ax – workdays to days post, i’ve decided to blog some more about it. The DateTimeUtil class is actually a wrapper of the .NET DateTime class.

A first thing to remember when using UtcDateTime EDT’s is that it is stored like the name says as Coordinated Universal Time.

The controls on the form will translate the DateTime to the timezone of the client. Now keeping this in mind is very important when mixing date, time and datetime controls. The following example will make it more clear.

The first field is a UtcDateTimeEdit control with a data method that returns DateTimeUtil::UtcNow().

As you can see the time is 08:58, but the first control on the form shows 10:58. This is correct because my client timezone is (GMT+01:00) Brussel, Kopenhagen, Madrid, Parijs and it’s summer time.

The second field is a TimeEdit control with a data method that returns DateTimeUtil::time(DateTimeUtil::utcNow()), this isn’t correct because it will always return the time in the UTC timezone and the control will not translate it to the correct timezone.

The third field is another TimeEdit control with a data method that returns TimeNow(), this is correct because the TimeNow method will also apply the client/server (depending on the tier) timezone.

this also applies to field in a table.

Another way to use Time controls and the DateTimeUtil is using the applyTimeZoneOffset method.

UtcDateTime ret;
;
 
ret = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::utcNow(),TimeZone::GMTPLUS0100BRUSSELS_COPENHAGEN_MADRID);
 
return  DateTimeUtil::time(ret);

but this is a lot of code for a rather more simple thing :-)

A second thing to remember, when querying with a date on UtcDateTime fields make sure you select the whole day from 00:00:00 to 23:59:59.

For this I like to implement a method on the Global class, it’s keeps you’re queries cleaner ;-) It works the same way as all .NET developers use, Add a with time 0 and subtract a second.

static UtcDateTime dateCompare(date      _date,
                                  boolean   _toDate = false)
{
    UtcDateTime ret;
    ;
 
    if(_toDate)
    {
        ret = DateTimeUtil::addSeconds(DateTimeUtil::newDateTime(_date + 1,0),-1);
    }
    else
    {
        ret = DateTimeUtil::newDateTime(_date,0);
    }
 
    return ret;
}

So you’re query looks like this.

Date        currectDate = SystemDateGet();
SalesLine   salesLine;
;
 
while select    salesLine
where           salesLine.createdDateTime >= dateCompare(currectDate)
&&              salesLine.createdDateTime  <= dateCompare(currectDate,true)
{
    //Do something
}