Skip to main content

Posts

Showing posts from September, 2011

How to create a query range that searches two different fields

The following code should do the trick: q = new Query(); qbds = q.addDataSource(tablenum(DirPartyTable)); qbr = qbds.addRange(fieldnum(DirPartyTable, recId)); qbr.value(strfmt('("%1" == %2.%3) || ("%1" == %2.%4)', name, qbds.name(), fieldstr(DirPartyTable, firstName), fieldstr(DirPartyTable, lastName))); I just use the DirPartyTable as example. name is the argument that is passed to function.

How can I write the results from a QueryRun object to a CSV file?

you can write to text file using the TextIo class: #File TextIo textIo = new TextIO("xyz123.txt", #IO_Write); ; textIo.outFieldDelimiter(';'); while (queryRun.next()) { //... get data textIo.write(yourTable.AccountNumber, yourTable.AccountName); } If you want to implement a generic solution, you can iterate through datasources/fields like this: setPrefix("List query fields"); for (i = 1; i <= query.dataSourceCount(); i++) { qbds = query.dataSourceNo(i); setPrefix(tableId2name(qbds.table())); for (j = 1; j <= qbds.fields().fieldCount(); j++) { fieldId = qbds.fields().field(j); info(new SysDictField(qbds.table(), fieldId).name()); } } When you have TableId and FieldId, you can write data by the following code: common = queryRun.get(tableId); textIo.write(common.(fieldId)); You can build a container and write it down by writeExp() when it is complete.

Bug in class RunBaseReport

When you create a class that extends from RunBaseReport and you try to modify the printer preferences it won’t have any effect. This small bug can be fixed very easy. Edit the class RunBaseReportDialog, method main and check lines 14 and 15: static void main(Args args) { RunBaseReportDialog reportDialog = new RunBaseReportDialog(args.caller()); RunBaseReport runBaseReport = args.caller().runbase(); ReportRun reportRun = runBaseReport.reportRun(); Report report = reportRun.report(); boolean oldInteractive; boolean res; Dialog dialog; ; // We must invoke the SysPrintForm via the report object so that we honor an prompt overrides. oldInteractive = report.interactive(); report.interactive(true); //res = reportRun.prompt(); // COMMENTED res = reportDialog.prompt(); // CHANGE OF CODE report.interactive(oldInteractive); if (!res) return; dialog = Dialog::getDialogFromCaller(args.caller()); if (dialog) { dialog.updateServer(); } runBaseReport.dialog...

Call a method on caller form

Sometimes you need to call a function on the calling form. You can use the following code to accomplish this. element.args().caller(). (); For example element.args().caller().GS_Refresh(); The problem with the code above is that you don't get any compilation errors if the method doesn't exist. To handle this problem, you can use the following code. if (formHasMethod(element.args().caller(), identifierStr(GS_Refresh))) { element.args().caller().GS_Refresh(); }

How to run Client Batches on AX 2009

In AX 2009 the batch engine has been changed to run as a service. The batch services do only process server batches they don't process client batches aynmore. There might still be some situations where you would like to run client batches. The following description explains how to do this. - Create a new batch group Client which is used for client batches later. ( Administration | Setup | Batch groups ) - Add this batch group to an AOS acting as batch server. ( Administration | Setup | Server configuration ) This is needed to change the status from Waiting to Ready on the batch tasks and to Execute on the batch jobs. The batch server will not process any client batches. - Start the legacy batch client ( Basic | Periodic | Batch | Processing ) - Select the new created batch group Client and press OK The client batch server will now process all client batches of the Client batch group. This is from the blog EMEA Dynamics AX Support (http://blogs.msdn....

Disable autocomplete

Below is an example of how to disable the autocomplete for a specific field in AX. public boolean modified() { boolean ret; ; ret = super(); element.delAutoCompleteString(this); return ret; }

Update all records shown in a form

If you want to update, or do something else, with all records shown on a form (i e only the records shown by the filter), you can use the following code. In the example below, CustTable is used as example. void updateRecords() { CustTable custTableLocal; QueryRun queryRun; ; queryRun = new QueryRun(CustTable_DS.queryRun().query()); while (queryRun.next()) { if (queryRun.changed(tableNum(CustTable))) { custTableLocal = queryRun.get(tableNum(CustTable)); // DO STUFF } } }

changecompany insert

static void FO_changecompany(Args _args)   {       FO_TestTable    table, table2;       ;       while select table       {           changecompany("FO1")           {               table2 = null;               ttsbegin;               buf2buf(table, table2);               table2.insert();               ttscommit;           }       }   }

I just leapt on top of it with both hands

British man has captured what is thought to be one of the largest snakes in the world. Niall McCann, a 29-year-old biologist from Cardiff, snared the 18ft anaconda in the tropical rainforests of Guyana, South America, three weeks after he initially spotted the creature during his exploration with fellow traveler Dr Robert Pickles. The find occurred in 2009 but photos have only recently emerged.

send e-mail

I have created a new class with a static method that I can easily call from any .update() method to alert me when a record changes, and what changed in the record. static void CompareAndEmail(str emailTemplateName, str nameField, str recipient, Common original, Common modified) {     UserInfo    userInfo;     Map         emailParameterMap = new Map(Types::String, Types::String);     str         changes;     int         i, fieldId;        DictTable   dictTable = new DictTable(original.TableId);     DictField   dictField; ;     for (i=1; i<=dictTable.fieldCnt(); i++)     {         fieldId = dictTable.fieldCnt2Id(i);         dictFie...

Axapta change company

You writing two metot . First method code static void LedgerDataAreaUpdateWhile(Ledgertable  _Ledgertable) {     dataarea           qdataarea;     DataAreaId    eskiDataArea;     Ledgertable TLedgertable ;     LedgerTableInterval  sLedgerTableInterval, tLedgerTableInterval;     recid             hedefrecid;     ;     eskiDataArea = companyinfo::find().dataAreaId;     while select qdataarea where qdataarea.Id != companyinfo::find().KonsilideSirket &&                                  qdataarea.Id != curext() &&          ...

Open Dynamics AX on a sync mode

Maybe sometimes, we need to run our Microsoft Dynamics AX with a synchronization mode, because we have some differences between Dynamics AX tables and SQL tables produced for a problem that we could have in the AOS while we were creating a table or a field in AOT... The sentence (in Windows CMD Command) to run Dynamics AX in sync mode is that:   Ax32.exe -startupCmd=synchronize (we need to browse in the Dynamics AX client folder or have the AX32.exe in the local variables of Windows)

Update field properties from axapta x++

This job helps you to update field properties of AOT tables from axapta x++. In this case, we'll update 'ModifiedDate', 'ModifiedTime', 'ModifiedBy' and 'CreatedDate', 'CreatedTime', 'CreatedBy' field properties of all Dynamics AX tables, excluding system tables, tmp tables, views and maps. static void Test_DictTaules(Args _args) { SqlDataDictionary sqlDD; Dictionary dict; TableId tabId; SysdictTable dTable; SqlDictionary sqlDictionary; TreeNode Tnode; ;     dict = new Dictionary(); sqlDD = new SQLDataDictionary();     ttsbegin;     tabId = dict.tableNext(0);     While (tabId) { dTable = new SysDictTable(tabId);         if(!dTable.isSystemTable() && !dTable.isView() && !dTable.isMap() && !dTable.isTmp())...

Passing values between form and class

Class name is EmplDuplication and Form is EmplTable . void clicked() {    MenuFunction mf;    args args = new Args();    ;     args.record(EmplTable);     mf = new menufunction(identifierstr(EmplDuplication), MenuItemType::Action); mf.run(args); } Meanwhile, in the main() method of the EmplDuplication class, we need to put this Axapta x++ code to get the datasource: static void main(Args args) {     EmplDuplication EmplDuplication; EmplTable localEmplTable; ;     if(args.record().TableId == tablenum(EmplTable)) localEmplTable = args.record();     ... }

Filtering Excel and CSV files in a dialog

This is useful if you want to show only this type of files in a selection. public Object dialog() {    DialogRunbase dialog = super();    #AviFiles    #Excel     dialogFilename = dialog.addField(typeId(FilenameOpen));     dialog.filenameLookupFilter   (["@SYS28576",#XLSX,"@SYS100852","*.csv"]); dialog.filenameLookupTitle("Upload from EXCEL/CSV"); dialogFilename.value(filename);     return dialog; }

Checking phone number axapta

boolean CheckPhoneNumber(str phoneNumber) {    System.Text.RegularExpressions.Regex regEx;    ;    if(phoneNumber)   {     regEx = new System.Text.RegularExpressions.Regex(@'^((\+[1-9]{1,3}(-| )?\(?\d\)?(-| )?\d{1,3}))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$');        return regEx.IsMatch(phoneNumber);     }     return true; }

Make axapta x++ report at runtime

With that, we can to create and modify our reports dynamically, and adjust its properties at runtime. static void MakeReportAtRuntime(Args _args) { #AOT str reportName = 'MakeReport'; tableid custTableId = tablenum(CustTable); TreeNode reportNode = TreeNode::findNode(#ReportsPath); Report areport; ReportDesign design; ReportAutoDesignSpecs specs; ReportSection section; ReportRun run; ; //Delete the report if it already exists areport = reportNode.AOTfindChild(reportName); if (areport) areport.AOTdelete(); //Build the report areport = reportNode.AOTadd(reportName); areport.query().addDataSource(custTableId); design = areport.addDesign('Design'); specs = design.autoDesignSpecs(); section = specs.addSection(ReportBlockType::Body, custTableId); section.addControl(custTableId, fieldnum(CustTable, AccountNum)); section.addControl(custTableId, f...

Count total number of records in axapta x++

Sometimes, we need to know the number of records in a axapta x++ query... so it's possible! Just we use the SysQuery::countTotal(queryRun) function to count the number of query records. However, this function count only the number of records of the first datasource... if we need to count the number of records of a query with more than one datasources... we need to use the SysQuery::countLoops(queryRun) instead of SysQuery::countTotal(queryRun) .

Calling external dll files from Dynamics AX

In this example, we will use the Beep function of kernel32.dll. This function needs two parameters: BOOL Beep(DWORD dwFreq,DWORD dwDuration); The AX Code is static void ExtDLL(Args _args) {     DLL winApiDLL = new DLL('kernel32');     DLLFunction Function = new DLLFunction(winApiDLL,'Beep');   Function.arg(extTypes::DWord,extTypes::DWord);   Function.call(400,1000); } Run this and you will hear a beep.

Shut down axapta from x++ code

void ShutDownAxapta() {    SysGlobalCache cache = appl.globalCache();    info info;    ;    cache.set(classstr(info), identifierstr(Autologoff), true);    info = new info();    info.shutDown(true); }

Passing values between form and class

Class name is EmplDuplication and Form is EmplTable . void clicked() { MenuFunction mf; args args = new Args(); ;   args.record(EmplTable); mf = new menufunction(identifierstr(DASEmplDuplication), MenuItemType::Action); mf.run(args); } Meanwhile, in the main() method of the EmplDuplication class, we need to put this Axapta x++ code to get the datasource: static void main(Args args) { DASEmplDuplication DASEmplDuplication; EmplTable localEmplTable; ;     if(args.record().TableId == tablenum(EmplTable)) localEmplTable = args.record();     ... }

Exporting data to Excel from axapta x++

static void CreateExcelDocument(Args _args) { SysExcelApplication xlsApplication; SysExcelWorkBooks xlsWorkBookCollection; SysExcelWorkBook xlsWorkBook; SysExcelWorkSheets xlsWorkSheetCollection; SysExcelWorkSheet xlsWorkSheet; SysExcelRange xlsRange; CustTable custTable; int row = 1; str fileName; ; //Filename fileName = "C:\\Test.xlsx"; //Initialize Excel instance xlsApplication = SysExcelApplication::construct(); //Open Excel document //xlsApplication.visible(true); //Create Excel WorkBook and WorkSheet xlsWorkBookCollection = xlsApplication.workbooks(); xlsWorkBook = xlsWorkBookCollection.add(); xlsWorkSheetCollection = xlsWorkBook.worksheets(); xlsWorkSheet = xlsWorkSheetCollection.itemFromNum(1); //Excel columns captions xlsWorkSheet.cells().item(row,1).value("Account Num"); x...

Open table from axapta x++

today, I want to share you a simple way to open a table from x++. static void DASTableBrowser(Args _args) SysTableBrowser sysTableBrowser = new SysTableBrowser(); ; //Browse the CustTable table sysTableBrowser.run(tablenum(CustTable)); ;

how to create new account to vendtable

void ismailCreateVend() {     VendTable                   vendTable;     EmplTable                   emplTable;     NumberSeq                   numberSeq;     str                         accnum;     ;     ttsbegin;     numberSeq = NumberSeq::newGetNumFromCode(VendParameters::numRefVendAccount().NumberSequence);     vendTable.AccountNum   = numberseq.num();     accnum               ...