首页 > 代码库 > 常用的X++

常用的X++

Simple select statement example
static void selectExample(Args _args)
{
CustTable custTable;
int counter;
;
select * from custTable;
while(custTable.AccountNum)
{
print custTable.Name + " "+ custTable.AccountNum;
next custTable;
counter++;
}
print "The no. of customer records are : " + int2str(counter);
pause;
}

Difference between the while and while select
Small eg:
While select custTable
{
print custtable.AccountName;
} //Automatically loops through records until the last record.

select custTable;
while(custTable)
{
print custTable.AccountName;
next custTable;//Without this statement(next) the looping becomes infinite
}


How to pop up a new form through code...Args args;
FormRun formRun;
;

args = new Args();
args.name(formstr(Your_Form_Name));
args.caller();

formRun = classFactory.formRunClass(args);
formRun.init();
formRun.run();
formRun.wait();


Execute query code with filter
1) this.query().dataSourceTable(tablenum(CustTable)).addRange(fieldnum(CustTable, AccountNum)).value(LedgerJournalTrans.AccountNum);

or else u can use 
2) The select statement with the where clause. Make sure to override the super();

Create a dialog radiobutton...
First create a new base enum with the property selected as radiobutton.

Dialog dialog = new Dialog();
DialogField df;
FormRadioControl frc;
;
df = dialog.addField(typeid(BaseEnum1));
frc = df.control();
frc.caption("Whatever the label should be");
frc.helpText("Whatever the help message should be");
dialog.run();


Look up on the form datasource...
public void lookup(FormControl _formControl, str filterStr)
{
Table1 Table1;
SysTableLookup Lookup = SysTableLookup::newParameters(tableNum(Table1),_formControl); 
Query query = new Query();
QueryBuildDataSource queryBuildDataSource;
QueryBuildRange queryBuildRange;
;
Lookup.addLookupField(fieldNum(Table1,FieldName));
queryBuildDataSource = query.addDataSource(tableNum(Table1));
queryBuildDataSource.addRange(fieldNum(Table1,FieldName).value(Table2.FieldName1);
Lookup.parmQuery(query); // Query to be executed
Lookup.performFormLookup();
}


This job aid concentrates on string manipulations.
1) Retrieve a substr...
static void Job13(Args _args)
{
str a,b,c,d;
str s = ‘AAAAAA,BBBBB,CCCCCCCCCC,DD‘;
;
[a,b,c,d] = global::str2con(s,‘,‘);
print a;
print b;
print c;
print d;
pause;
}

2) To replace a filename with theAxapta standard filename use the following...
strReplace(filepath,‘\\‘,‘/‘);

3)
TextBuffer textBuffer = new TextBuffer();
str text "xxxx,xxxxxx,xxxx,xxxx";
int lines, i;
;

text = strReplace(text,",", "\r\n");
textBuffer.setText(text);
lines = textBuffer.numLines();

for(i=0; i<=lines; i++)
{
box::info(StrLine(text, i));
}

Some light on arrays and calling a AOT item...
static void arrayInfo(Args _args)
{
str l;
array i = new array(types::Integer);;
startLengthyOperation(); // For that hour glass symbol to start
// i.value(0,0); //There‘s no pointer to 0
i.value(1,12);
i.value(2,13);

info(i.toString()); // I am displaying the contents of the array
l = infolog.text(); // Having a string and getting the value in the infolog, currently the array value is present
sleep(2000); //simply making the system idle for 2 seconds
info(l);
endLengthyOperation(true); //Hour glass symbol ends and becomes a mouse pointer again

}


// Calling a Job or any AOT Item from another method in a class in Ax
static void CallJob(Args _args)
{

Treenode treenode;
;
treenode = treenode::findNode("jobs\\arrayInfo");
treenode.AOTrun();

treenode = treenode::findNode("forms\\TestControls");
treenode.AOTrun();
}

Upload an image in a form window control...
public void clicked() // on the click event of a button we need to upload an image on the form in a window control.
{
str filename;
FileNameFilter filter = [‘JPG files‘,‘*.jpg‘];
Bindata binData;
Image signatureImage = new Image();

super();

filename = Winapi::getOpenFileName(element.hWnd(), filter, ‘‘, "Upload your image", ‘‘, ‘‘);

binData = http://www.mamicode.com/new BinData();

if (binData.loadFile(filename))
{
signatureImage = binData.getData();
FormWindowCOntrol.image(signatureImage);
FormWindowCOntrol.widthValue(signatureImage.width());
FormWindowCOntrol.heightValue(signatureImage.height());
element.resetSize();
element.unLock();
}

generates the index for the base enums
static void baseenumid(Args _args)
{
dictenum dictenum;
int i;
;
dictenum = new dictenum(enumname2id(‘NumberSeqModule‘));

for(i=0;i{
print int2str(i)+‘,‘+dictenum.index2Name(i);
pause;
}
}

exporting the data to doc format
static void exportToFile(Args _args)
{
Container con;
sqlDictionary sqlDictionary;
TableName tabName;
CommaIo myfile;
CustTrans custTrans;

;

TabName = "CustTrans";

select * from sqlDictionary where Tablename2id(TabName) == sqlDictionary.tabId;

if(sqlDictionary.RecId > 0)
{
myfile= new CommaIo("c:\\exportedfile.doc","w");
myfile.outFieldDelimiter("\t");//leaves space between each column
// myfile.outRecordDelimiter("\r\n");
while select custTrans
{
con= [custTrans.AccountNum,custTrans.Txt];
myfile.writeExp(con);

}

}
}




Post a journal
// posting a ledgerjournal automatically
LedgerJournalCheckPost ljcp;
LedgerJournalTable ljt;
;

// have to find a ledgerJournalTable, and assign it to ljt

lcjp = LedgerJournalCheckPost::newLedgerJournalTable(ljt, noYes::Yes);
ljcp.run();

Letz See some treenode functionality
//This job uses the treenode functionality to the fullest to find a child in a report with a given name... Check it out 
//copy the lines to Ax and tab them so that the code looks better to understand...

static void AOTGetReportFinal(Args _args)
{
#define.Menu(‘Menus‘)
#define.Reports(‘Reports‘)

Treenode treenode, child, itTree;
TreeNodeIterator iterator;

str ReportName = ‘Your_Report_Label_Name‘; // report label name as it appears in the Menus > (Module) > Reports in the AOT

void checkReport(treenode _subNode)
{
Str path;

path = _subNode.treeNodePath();
_subNode = _subNode.AOTfindChild(ReportName);
if(_subNode)
{
info(‘Found - ‘ + _subNode.treeNodePath());
return ;
}
else if(infolog.findNode(path).AOTfirstChild())
{
checkReport(infolog.findNode(path).AOTfirstChild());
}
return;

}

boolean traverse(treenode _child)
{
Treenode tmpNode;
treeNodeIterator it;


tmpNode = _child.AOTfindChild(#Reports);
if(tmpNode)
it = tmpNode.AOTiterator();
while(tmpNode)
{
checkReport(tmpNode);
tmpNode = it.next();
}
return 0;
}

;
treenode = infolog.rootNode();
child = treenode.AOTfindChild(#Menu);
// iterator = child.AOTiterator();
child = child.AOTfirstChild();
while(child)
{
if(traverse(child))
break;
child = child.AOTnextSibling();
}

}


Query, QueryBuildDatasource, QueryBuildLink...
//This job is for seeing the relations that are there in the query datasource
//Please tab the lines in X++ editor to have a better undersatnding...

static void QueryLinks(Args _args)
{
Query query = new Query(queryStr(custtable));//Give your query name as in AOT...

void getLinks(QueryBuildDatasource _qbds)
{
QueryBuildDataSource childDataSource;
QueryBuildLink queryBuildLink;
Counter links;
int i;
;
if (_qbds.enabled())
{
setPrefix (tableId2Name(_qbds.table()));
if(_qbds.level() > 1)
{
while (links < _qbds.linkCount())
{
links++;
queryBuildLink = _qbds.link(links);
info(strFmt("%1.%2 --> %3.%4",
tableId2Name(queryBuildLink.relatedTable()),
fieldId2Name(queryBuildLink.relatedTable(), queryBuildLink.relatedField()),
tableId2Name(queryBuildLink.table()),
fieldId2Name(queryBuildLink.table(),queryBuildLink.field())));

}
}
for (i = 1; i <= _qbds.childDataSourceCount(); i++)
{
childDataSource = _qbds.childDataSourceNo(i);
getLinks(childDataSource);
}
}
}
;


setPrefix(strFmt("Query: ‘%1‘", query.name()));
getLinks(query.dataSourceNo(1));

}

Number sequence in Projects...
//Create your own number sequence in the projects module
//All modules have methods to create number sequences... Use those methods for creating the records from X++

static void ProjNumberSeq(Args _args)
{
NumberSeq projNumberSeq;
;

projNumberSeq = NumberSeq::newGetNum(ProjParameters::numRefProjId(), true);
print projNumberSeq.num();
pause;
}

Get u r database details from SQLSystem Class
//Check out the other methods of the SQLSystem class

static void SqlSystem(Args _args)
{
SqlSystem SqlSystem = new SqlSystem();
;
info(SqlSystem.loginServer() + ‘ ‘ + SqlSystem.loginName());

}

Get data from table in XML format...
static void Job5(Args _args)
{
custtable custTable;
;
while select custtable
info(custTable.xml());
}

Get the default language...
static void defaultLangId(Args _args)
{
Session session = new Session(sessionId());
;
info(session.interfaceLanguage());
}

Using wildcard "Like"
//The "*" symbolises the like in the statement
static void useWildCards(Args _args)
{
Query custQuery = new Query();
QueryRun queryRun;
CustTable CustTable;
;
custQuery.addDataSource(tablenum(CustTable)).addRange(fieldnum(CustTable, Name)).value(‘L*‘);
queryRun = new QueryRun(custQuery);
while (queryRun.next()) 
{
custTable = queryRun.get(tablenum(CustTable)); 
info(custTable.Name); 
}
}

Mandatory fields in Table through code
Hi ...This is a simple job specially for the fresh learners of AX..
This job will give us the mandatory fields in a table...check out

static void Mandatoryfields_inTable(Args _args)
{

DictTable dictTable;
DictField dictField;
tableId tableId;
fieldId fieldId;
str result;
#DictField
;
dicttable = new DictTable(tablenum(salestable));
for (fieldId = dictTable.fieldNext(0);fieldId;fieldId = dictTable.fieldNext(fieldId))
{
dictField = dictTable.fieldObject(fieldId);

if (!dictField.isSystem() && bitTest(dictField.flags(), #dbf_visible)
&& bitTest(dictField.flags(), #dbf_mandatory))
{
result += dictField.name();
result +=‘\n‘;
}
}
info(result);
}

All the fields in a table through code
The idea behind writing this job is to make clear the concepts of sqlDictionay and how to get the fields from a table. Also a little introduction to file generation class(TextBuffer).This job create a CSV file by name fieldlist in C: drive

static void fieldsInTable(Args _args)
{

str fieldList = ‘‘;
SqlDictionary sqlDictionary;
TextBuffer buffer = new TextBuffer();
;
while select * from sqlDictionary where sqlDictionary.tabId==tablenum(salestable)
{
fieldList += sqlDictionary.sqlName;
fieldlist += ‘\r‘;
}
if (fieldList)
fieldList = subStr(fieldList,1,strLen(fieldList)-1);
buffer.setText(fieldlist);
buffer.toFile("c:\\fieldslist.csv");
}

Get specified layer object
This Job gets u the list of objects(Forms) which are developed in usr layer. This can be achieved in many possible ways...This job will be time consuming as it uses treenode to find the objects. Also, if u click the object in the info displayed, the corresponding form gets opened..I used sysinfoaction_formrun to achieve this.check out..

static void getLayers(Args _args)
{
treeNode treeNode;
xInfo xInfo = new xInfo();
#AOT
;
treeNode = xInfo.findNode(#FormsPath);
treeNode = treeNode.AOTfirstChild();
while (treeNode)
{
if(treeNode.applObjectLayer() == utilEntryLevel::usr)
{
info(treeNode.TreeNodeName(),‘‘, sysinfoaction_formrun::newFormname(treeNode.TreeNodeName(),‘‘,‘‘));
}
treeNode = treeNode.AOTnextSibling();
}


}

No of users Online and sessions
This job gives u the number of current online users. Also it throws some light of session classes in Axapta 3.0 and its limit.
static void noofusersOnline(Args _args)
{
int maxSessions = Info::licensedUsersTotal();
userinfo userinfo;
int counter;
int num;
xSession session;

if (!maxSessions) //Demo mode
maxSessions = 3;

num = 0;
for(counter = maxSessions;counter;counter--)
{
session = new xSession(counter, true);
if(session && session.userId())
{
select userinfo where userinfo.id == session.userId();
print userinfo.name;
}
}
print "Maximum session id‘s in Axapta 3.0 - ", xsession::maxSessionId();
pause;

}

常用的X++