Using a query in a SysOperation data contract class in Dynamics AX 2012

The information in this post is based on Dynamics AX 2012 R3. It may or may not be valid for other versions.

I always seem to forget the details on how to specify and initialize a query in the SysOperation framework. I guess that most of the batch jobs I’ve been making aren’t based on user-configurable queries, but every now and then I do need to make such a batch job, so this post is also for my own reference, or memory-aid if you will 😉

First, in the data contract class, the query will be stored packed in a string. Its parm method must be decorated with the AifQueryTypeAttribute attribute, like so (in this example I’ve used the SalesUpdate query, but you can replace this with any AOT query):

[   
    DataMemberAttribute,
    AifQueryTypeAttribute('_packedQuery', queryStr(SalesUpdate))
]
public str parmPackedQuery(str _packedQuery = packedQuery)
{
    ;

    packedQuery = _packedQuery;
    return packedQuery;
}

If you want the query to be decided by the controller class instead, you can also use an empty string. In that case, you also need to implement a couple of helper methods (which you probably should implement anyway for your own convenience when you need to access the query):

public Query getQuery()
{
    ;

    return new Query(SysOperationHelper::base64Decode(packedQuery)); 
}
public void setQuery(Query _query)
{
    ;

    packedQuery = SysOperationHelper::base64Encode(_query.pack());
}

If you need to initialize the query (for example, add ranges), you should implement an initQuery method

public void initQuery()
{
    Query queryLocal = this.getQuery();
    ;

    // add ranges, etc...

    this.setQuery(queryLocal);
}

You need to make sure to call this method from the controller class.