Monday, February 17, 2014

Dependent lookup in dialog class

class dialogDepLookup extends runbase
{
    DialogRunbase       dlg;
    DialogField     fieldCustAccount;
    DialogField     fieldCustTransDate;

    CustAccount     custAccount;
    TransDate       transDate;

    #define.CurrentVersion(1)

    #localmacro.CurrentList
        custAccount,transDate

    #endmacro
}
protected Object dialog()
{
    dlg = new DialogRunbase("test",this);


    //dlg                 = super();
    fieldCustAccount = dlg.addFieldValue(typeId(CustAccount),'', "Customer Account");
    fieldCustTransDate = dlg.addFieldValue(typeId(TransDate), datenull(), "Transaction Date");

    return dlg;
}
public void dialogPostRun(DialogRunbase _dialog)
{
    super(_dialog);

    _dialog.dialogForm().formRun().controlMethodOverload(true);
    _dialog.dialogForm().formRun().controlMethodOverloadObject(this);
}
void Fld2_1_lookup()
{
    Object control = dlg.formRun().controlCallingMethod();
    ;

    this.transDate_Lookup(control, fieldCustAccount.value());
}
public boolean getFromDialog()
{
    boolean ret;
    ;

    ret             = super();
    custAccount  = fieldCustAccount.value();
    transDate         = fieldCustTransDate.value();

    return ret;
}
public container pack()
{
    return [#CurrentVersion, #CurrentList];
}
void run()
{
    //#OCCRetryCount
    //setprefix("@SYS3761");

    try
    {
        info(custAccount);
        info(date2strxpp(transDate));
    }
    catch (Exception::Deadlock)
    {
        retry;
    }   
}
public void transDate_Lookup(FormStringControl _ctrl,CustAccount _custAccount)
{
    SysTableLookup          sysTableLookup = SysTableLookup::newParameters(tablenum(CustTrans),_ctrl);
    Query                   query = new Query();
    QueryBuildDataSource    queryBuildDataSource = query.addDataSource(tablenum(CustTrans));
    ;

    sysTableLookup.addLookupfield(fieldnum(CustTrans,TransDate));
    queryBuildDataSource.addRange(fieldnum(CustTrans,AccountNum)).value(_custAccount);
    queryBuildDataSource.orderMode(orderMode::GroupBy);
    queryBuildDataSource.addSortField(fieldnum(CustTrans,TransDate));

    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();
}
public boolean unpack(container _packedClass)
{
    Integer version = RunBase::getVersion(_packedClass);
    ;

    switch (version)
    {
        case #CurrentVersion:
            [version, #CurrentList] = _packedClass;
            break;

        default:
            return false;
    }

    return true;
}
public static void main(Args    _args)
{
    dialogDepLookup dialogDepLookup = new dialogDepLookup();
    ;
    if (dialogDepLookup.prompt())
    {
        dialogDepLookup.run();
    }
}

Create new project through X++

static void createProject(Args _args)
{
    sysprojectfilterrunbase upgradeproject;
    utilelements            theelements;
    ;

    upgradeproject = new sysprojectfilterrunbase();
    upgradeproject.parmProjectNode(systreenode::createProject('test'));
    upgradeproject.grouping(sysprojectgrouping::AOT);

    while select name, utilLevel, RecordType, ParentId from theelements
    where theelements.utilLevel == UtilEntryLevel::usr
    {
        try
        {
            theelements.reread();
            upgradeproject.doUtilElements(theelements);
        }
        catch (exception::Error)
        {
            throw error('error');
        }
    }

    upgradeproject.write();
    info('finish');
}

Creating context (Right-click) menu for display field

Creating right click filter options for display field disCustName (Customer Name)

Add the override method 'Context' for the name field

public void context()
{
    int             selectedMenu;
    formrun         fr;
    Args            ag;
    Name            strtext;
    querybuilddataSource qb1;
    queryrun    qr;
    query       q;
    PopupMenu menu = new PopupMenu(element.hWnd());
    int a = menu.insertItem('Filter By Field'); //2
    int b = menu.insertItem('Filter By Selection'); //3
    int c = menu.insertItem('Remove Filter'); //4
    ;

    selectedMenu = menu.draw();
    print selectedMenu;pause;
    switch (selectedMenu)
    {
    case -1: //Filter by field
            break;
    case 2:
            ag = new args('SysformSearch');
            fr = new formrun(ag);
            fr.run();
            fr.wait();
//Reading User entered value for filter process
            strtext = '';
            strtext = fr.design().controlName('FindEdit').valueStr();

            if(strtext)
            {
//Creating a query for filter
                q   = smmBusRelTable_ds.query();
                qb1 = q.dataSourceTable(tablenum(smmBusRelTable));
                qb1 = qb1.addDataSource(TableNum(CustTable));
                qb1.addLink(FieldNum(smmBusRelTable,CustAccount),FieldNum(CustTable,AccountNum));
                //strtext = strreplace(disCustName.text(),',','*');
                info(strtext);
                qb1.addRange(FieldNum(CustTable,Name)).value(strtext);
                smmBusRelTable_ds.query(Q);
                info(qb1.toString());
                smmBusRelTable_ds.executeQuery();
            }
            break;

    case 3:   // Filter By Selection
         
            q   = smmBusRelTable_ds.query();
            qb1 = q.dataSourceTable(tablenum(smmBusRelTable));
            //qb1.clearRanges();
            qb1 = qb1.addDataSource(TableNum(CustTable));
            qb1.addLink(FieldNum(smmBusRelTable,CustAccount),FieldNum(CustTable,AccountNum));
            //info(disCustName.text());
            strtext = strreplace(disCustName.text(),',','*');
            qb1.addRange(FieldNum(CustTable,Name)).value(strtext);
            smmBusRelTable_ds.query(Q);
            info(qb1.toString());
            //qr = new queryrun(smmBusRelTable_ds.query());
            smmBusRelTable_ds.executeQuery();
            break;
    case 4 :   // Remove Filter
            q   = new Query();
            qb1 = q.addDataSource(tablenum(smmBusRelTable));
            qb1.clearLinks();
            qb1.clearRanges();
            smmBusRelTable_ds.query(Q);
            smmBusRelTable_ds.removeFilter();
            break;

    Default:
            break;
    }

}

Using DictTable

Truncate table using DictTable object

class SqlPermissionJobCls
{
}
static void main(args _args = null)
{
    DictTable dictTable = new DictTable(tablenum(TestTable));
    str sqlTableName;
    SqlDataDictionary sqlTable;

    if (dictTable && dictTable.enabled())
    {
        sqlTableName = dictTable.name(DbBackend::Sql);
        sqlTable = new SqlDataDictionary();
        // Try to truncate only if the table does exist
        // in the SQL database.
        if (sqlTable.tableExist(sqlTableName))
        {
            new SqlDataDictionaryPermission(
                methodstr(SqlDataDictionary, tableTruncate)).assert();
            sqlTable.tableTruncate(tablenum(TestTable));
            CodeAccessPermission::revertAssert();
        }
    }
}

Using sub-query through X++

static void SelectAsExpression3Job(Args _args)
{
    int64 nRecId,
        nCount;
    str sAccountNum,
        sName;
    ;
    // Test_1.a
    sAccountNum = (select firstonly AccountNum from CustTable
        order by AccountNum desc
        where 0 == 0 // 'where' must occur after 'order by'.
        ).AccountNum;
    info(strFmt("Test_1.a: %1", sAccountNum));

    // Test_1.b
    sAccountNum = (select maxof(AccountNum) from CustTable).AccountNum;
    Global::info(strFmt("Test_1.b: %1", sAccountNum));

    // Test_2.c
    nRecId = (select maxof(RecId) from CustTable
        where CustTable.Blocked == CustVendorBlocked::No).RecId;
    info(strFmt("Test_2.c: %1", nRecId));

    // Test_2.d
    nRecId = (select count(RecId) from CustTable
        where CustTable.Blocked == CustVendorBlocked::No).RecId;
    info(strFmt("Test_2.d: %1", nRecId));

    // Test_3
    sName = (select Name from AssetTable
        where AssetTable.AssetId ==
            (select AssetId from AssetTrans
                where AssetTrans.AssetId == 'VEHC-005' //"CNC-01"
            ).AssetId).Name;
    info(strFmt("Test_3: %1", sName));
}

Populating Data source Using Temp Table

Form init method

public void init()
{
    custtable        nut; // regular table in AOT
    custtable        tmp; // instead of creating in AOT a temporary table
                                   // we can create a temporary instance of the preivous regular table
    ;
     super();

    // here we make it temporary;
    // it will disappear from memory when loses the scope
    // in other words, when we close the form
    tmp.setTmp();

    // simply selecting some of records from the regular table
    while select nut
        where nut.City=='Toronto'
    {
        // and putting them in the temporary one
        tmp.data(nut);
        tmp.doInsert();

    }
    // finally to show them on the form
    // we set the form data source to the temporary table
    custtable.setTmp();
    custtable.setTmpData(tmp);
}

Using external websevice

class CampaignClients
{
}
public static server void getClient()
{
    COM     myXmlHttp;
    url     webServiceUrl;
    str     method;
    str     userName;
    str     password;
    str     strXML;
    str     strTxt;
    str     result;
    str     fileName;
    str     listValue;
    int     listLength;
    int     i;


    System.Exception netExcepn;
    InteropPermission permission;
    FileIOPermission    fileIOPerm;
    COM             receiveCom;
    XMLDocument     xmlDocu;
    XMLDocument     doc = XMLDOcument::newBlank();
    XMLElement      node;
    XMLNodeList     elemlist;
    str s_Json;
    ;

    try {

    permission = new InteropPermission(InteropKind::ComInterop);
    permission.assert();

    myXmlHttp = new COM('Microsoft.XMLHTTP'); // used ms xml http com object to communicate with the web service
    webServiceUrl   = strfmt("https://api.createsend.com/api/v3/clients.json");
    method          = "GET";
    fileName = "c:\\temp\\getRateFile.xml";
    xmlDocu = XmlDocument::newBlank('utf-8');

    CodeAccessPermission::revertAssert();
    fileIOPerm = new FileIOPermission(fileName, 'r');
    fileIOPerm.assert();

    xmlDocu.load(fileName);

    s_Json ='{"CompanyName": "Karya","Country": "India","TimeZone": "(GMT+10:00) Canberra, Melbourne, Sydney"}';

    CodeAccessPermission::revertAssert();
    permission = new InteropPermission(InteropKind::ComInterop);
    permission.assert();

    myXmlHttp.open(method,webServiceUrl,false,"2b4c0d6d781cbb43983e88674154cd39",password);
    myXmlHttp.setRequestHeader("content-type","text/xml"); //application/x-www-form-urlencoded
    myXmlHttp.send(s_Json);

    strTxt =strrtrim(myXMLHttp.responseText());
    info(strTxt);

    receiveCom  = myXMLHttp.responseXML();

    doc.loadXml(receiveCom.xml());
    elemList = doc.GetElementsByTagName("v3:Amount");
    listLength = elemList.length();

    for (i=0; i < elemList.length(); i++)
    {

        info(elemList.item(i).innerXml());
    }

    }
    catch (exception::CLRError)
    {
     netExcepn = CLRInterop::getLastException();
     info(netExcepn.ToString());
    }
    catch(exception::Error)
    {

     netExcepn = CLRInterop::getLastException();
     info(netExcepn.ToString());
    }
}