jeudi 29 décembre 2011

How to display system date and time in a report

display String30 clearanceDate()
{
    return date2str(systemdateget(),123,2,DateSeparator::Slash,2, DateSeparator::Slash,4)
             + "   " + time2str(timenow(),1,1) ;
}

How to use pack/unpack in a form

We can also use pack/unpack mechanism in a form like the ones used in Runbase Classes

Refer to this link  
http://daxguy.blogspot.com/2006/12/use-packunpack-on-form.html

When to use "ParentVersion" and when should I use "CurrentVersion" in pack/unpack method

If you're making your own, you should use CurrentVersion.  ParentVersion is likely a way to support older versions of packed information, or it's doing something fancy.  Here's an example of multiple version support in an unpack():

boolean unpack(container _packedClass)
{
int version = RunBase::getVersion(_packedClass); // this is a better way of conpeek(_packedClass, 1)
boolean ret = true;
;
switch (version)
{
case #CurrentVersion:
[version, #CurrentList] = _packedClass;
break;
case 2:
[version, startDate, endDate] = _packedClass;
break;
default:
ret = false;
break;
}
return ret;
}

It's just a switch on the version number so old data can be handled at least partially.

Why, When and How to use pack and unpack methods

An object has a particular state. You want to work with the same object at a later time or another place (such as on another tier). 
Make it possible to save the state of the object in a form that can be persistently saved or transported to another tier. Moreover, make it possible to reinstantiate the object.  

Basically, the pack method serializes the object, and unpack deserializes it.
What this gives you is the ability to automatically have all the variables set to specific values next time the job (class) is run.

For example, you have a class that prompts the user for an ItemId and does something with this item.
Each time the job is run, the user would have to select the item again, if it were not for the pack/unpack methods.

All you have to do to use them is declare the needed variables in the classDeclaration, add a macro defining the CurrentVersion of the parameterList and implement the pack and unpack methods. (the code is in the RunBase class - just copy it (removing #if.never, of course)

the information that is saved / restored is per user & per company basis.
The important thing to remember is - version id.  If you change the contents of container, you should remember to increment the version id. 

refer to this link to find an example.
https://community.dynamics.com/product/ax/f/33/p/67248/122709.aspx

and here is a link from MSDN tutorials
 http://msdn.microsoft.com/en-us/library/aa879675.aspx

How to override fetch method in a report

here is an example of an overrided fetch method in a report  
----------------------------------------------classDeclaration-----------------------------------------
public class ReportRun extends RunbaseReport
{
     InventQty                  sumQty1, sumQty2, sumQty3, sumQty4, sumQty5, sumQty6,
                                sumQty7, sumQty8, sumQty9, sumQty10, sumQty11, sumQty12, sumQty13, sumQty14;

     InventTrans                inventTrans;
     Thy_IntrastatItemCode      thy_IntrastatItemCode;
     IntrastatItemCode          intrastatItemCode;
     DialogField                fieldFromDate_Period;
     DialogField                fieldToDate_Period;
     FromDate                   fromDate;
     ToDate                     toDate;

     #define.CurrentVersion(1)

     #localmacro.CurrentList
        fromDate,
        toDate
     #endmacro
}

----------------------------------------------dialog----------------------------------------------------
public Object dialog(Object _dialog)
{
    DialogRunbase dialog = _dialog;
    ;

    dialog.addGroup("@SYS94817");
    fieldFromDate_Period  = dialog.addField(typeid(FromDate));
    fieldToDate_Period    = dialog.addField(typeid(ToDate));
    fieldFromDate_Period.value(fromDate);
    fieldToDate_Period.value(toDate);
    return dialog;
}

---------------------------------------------getDialog------------------------------------------------
boolean getFromDialog()
{;
    fromDate = fieldFromDate_Period.value();
    toDate   = fieldToDate_Period.value();
    return true;

----------------------------------------------fetch-----------------------------------------------------
public boolean fetch()
{
    boolean                 ret = false;
    QueryRun                _queryRun;
    queryBuildDataSource    queryBuildDataSource;
    ;

    _queryRun = new QueryRun(element);
            _queryRun.query().datasourcetable(tablenum(Thy_InventCustomsTrans)).addrange(fieldnum(Thy_InventCustomsTrans,DeliveryDate)).
    value(queryrange(fromDate,toDate));


     if (! _queryRun.prompt())
     {
        return ret;
     }

     while (_queryRun.next())
     {
        Thy_InventCustomsTrans  = _queryRun.get(tablenum(Thy_InventCustomsTrans));

        While select Qty, ItemId, InventTransId, inventDimId, RecId from inventTrans
        {
              sumQty1    = sumQty1 + inventTrans.Qty;            
        }
        element.send(Thy_InventCustomsTrans);
     }
    ret = true;

    return ret;
}
------------------------------------------------pack----------------------------------------------------
public container pack()
{
    return [#CurrentVersion, #CurrentList];
}
---------------------------------------------unpack-----------------------------------------------------
public boolean unpack(container packedClass)
{
    boolean         _ret;
    Integer         _version    = conpeek(packedClass,1);

    switch (_version)
    {
        case #CurrentVersion:
            [_version, #CurrentList] = packedClass;
            _ret = true;
            break;
        default:
            _ret = false;
    }
    return _ret;
}


Here is another example

public boolean fetch()
{
querybuildrange  qbr;
QueryRun qr = new queryrun(this.query());// picks the current datasource available in the report
;

qr.query().datasourcetable(tablenum(RBOTransactionTable)).addrange(fieldnum(RBOTransactionTable,TransDate)).value(queryrange(fromDate,toDate));

while(qr.next())
{

element.send(RBOStoreTable);
element.send(RBOTransactionTable);
element.send(RBOTransactionSalesTrans);

}

return true;
}

Here is another example from MSDN tutorials
http://msdn.microsoft.com/en-us/library/bb395110%28v=ax.10%29.aspx  

Check the RunBase Framework here  
http://msdn.microsoft.com/en-us/library/aa863262.aspx 

mercredi 28 décembre 2011

How to shut down axapta through code

This is an example to shut down the Dynamics AX client from x++ code using info class.

void DASShutDownAxapta()
{
    SysGlobalCache  cache = appl.globalCache();
    info            info;
    ;

    cache.set(classstr(info), identifierstr(Autologoff), true);
    info = new info();
    info.shutDown(true);
}


mardi 27 décembre 2011

How to get the value of the range before printing a report

You can get the range value using the following code:
this.queryRun().query().dataSourceTable(tableNum(<YourTableName>)).findRange(fieldNum(<YourTableName>, <Your_Division_FieldName>)).value();

mercredi 21 décembre 2011

How to import vendors from a csv file

Here is an example of a job that can be used to import vendors

static void import_fournisseurs_DIST(Args _args)
{
    Dirpartytable                               dirpartytable, _dirpartytable;
    container                                   c;
    TextIo                                      io;
    str 130                                     fileName;
    TextBuffer                                  b;
    str                                         s,stramount;
    integer                                     inc;
    DirPartyid                                  partyid;
    Vendtable                                   vendTable;
    SmmBusRelSectorTable                        smmBusRelSectorTable;
    TaxVATNumTable                              taxVATNumTable;
    Address                                     addressTab;
    Integer                                     counter;
    ;

    delete_from vendTable;
    delete_from dirpartytable
        where Dirpartytable.Type == Dirpartytype::Organization;
    delete_from smmBusRelSectorTable;

    fileName = @"C:\\FRS_DIST\FRS_LOC_DIST.csv";
    io = SysLicenseCodeReadFile::openFile(fileName,'r');
    if (!io)
        throw error(strfmt("@SYS18678",fileName));
    io.inFieldDelimiter(";");
    c = io.read();
    while (io.status() == IO_Status::Ok)
    {
        c = io.read();
        inc++;
        if (io.status() != IO_Status::Ok)
        break;

        partyid                 = conpeek(c,1);
        Dirpartytable.PartyId   = partyid;
        Dirpartytable.Type      = DirPartyType::Organization;
        Dirpartytable.NameAlias = conpeek(c,4);
        DirpartyTable.Name      = conpeek(c,3);

        if (DirpartyTable.Name != "" )
        {
            Dirpartytable.insert();
        }

        vendTable.AccountNum = conpeek(c,1);
        vendTable.name       = conpeek(c,2);
        vendtable.PartyId    = partyid;
        vendTable.NameAlias  = conpeek(c,3);

        vendTable.Currency              = conpeek(c,8);
        vendTable.InvoiceAccount        = conpeek(c,5);

        vendTable.VendGroup  = conpeek(c,6);
        vendTable.LanguageId = "fr";
        vendTable.PartyType  = DirPartyType::Organization;
        vendTable.Phone      = conpeek(c,11);
        vendTable.TeleFax    = conpeek(c,12);
        vendTable.Email      = conpeek(c,13);
        vendTable.VATNum     = conpeek(c,9);
        if (vendTable.name   != "0")
        {
            VendTable.insert();
        }
        print dirpartytable.PartyId;
        select recId from _dirpartytable
            where _dirpartytable.RecId   == dirpartytable.RecId
                && dirpartytable.PartyId == partyid;
                print _dirpartytable.RecId;
        addressTab.AddrRecId        = _dirpartytable.RecId;
        addressTab.AddrTableId      = 2303;
        addressTab.Street           = conpeek(c,10);

        addressTab.insert();
       
        if (conpeek(c,7) != '')
        {
            smmBusRelSectorTable.PartyId                = partyId;
            smmBusRelSectorTable.BusinessSectorId       = conpeek(c,7);
            smmBusRelSectorTable.KeyId                  = partyId;

            smmBusRelSectorTable.insert();
        }
        if ( partyid == '')
        break;
    }
    info("inserted");
}

How to import customers using a csv file in dynamics ax

Here is an example of a job that can be used to import customers

static void insert_Clients_Stunas(Args _args)
{
        CustTable                                   custTable;
        container                                   c;
        Integer                                     Start, PartyStart;
        TextIo                                      io;
        string50                                    fileName, FRS;
        TextBuffer                                  b;
        DirPartyType                                DirPartyType;
        ExtendedTypeId                              id;
        NumberSeq                                   num;
        DirPartyId                                  localDirPartyId;
        DirpartyTable                               dirpartyTable, _dirpartyTable;
        AccountNum                                  AccountNum;
        Addressing                                  address;
        Address                                     addressTab;
        CustPaymModeTable                           custPaymModeTable;
        Name                                        PaymName;

        ;
        delete_from custTable;

        fileName = @"C:\\Update_Clients_Stunas\Clients.csv";
        b=new Textbuffer();
         io = SysLicenseCodeReadFile::openFile(fileName,'r');

         c = io.read();
         if (!io)
            throw error(strfmt("@SYS18678",fileName));
         io.inFieldDelimiter(";");

         while (io.status() == IO_Status::Ok)
         {
             c = io.read();
             AccountNum                         = conpeek(c,1);
             custTable.AccountNum               = AccountNum;
             custTable.PartyId                  = AccountNum;

             custTable.Name                     = conpeek(c,2);
             custTable.NameAlias                = conpeek(c,2);
             custTable.CustGroup                = conpeek(c,16);
             custTable.Currency                 = "TND";
             custTable.PartyType                = DirPartyType::Organization;
             custTable.LanguageId               = "FR";
             custTable.TaxGroup                 = conpeek(c,6);
             custTable.VATNum                   = conpeek(c,7);

             custTable.Phone                    = conpeek(c,8);
             custTable.CellularPhone            = conpeek(c,9);
             custTable.TeleFax                  = conpeek(c,10);
             custTable.InvoiceAccount           = conpeek(c,11);
             custTable.SegmentId                = conpeek(c,12);
             custTable.PriceGroup               = conpeek(c,13);
             PaymName                           = conpeek(c,15);
             custTable.CustGroup                = conpeek(c,16);
             custTable.editContactPersonName(true, conpeek(c,17));
             if(conpeek(c,18) != '*')
             custTable.SubsegmentId             = conpeek(c,18);

             select PaymMode from custPaymModeTable
                where custPaymModeTable.Name    == PaymName;
             custTable.PaymMode                 = custPaymModeTable.PaymMode;

             custTable.insert();

             delete_from DirpartyTable
                where DirpartyTable.PartyId == accountNum;


             DirpartyTable.Type                 = DirPartyType::Organization;
             DirpartyTable.Name                 = conpeek(c,2);
             DirpartyTable.NameAlias            = conpeek(c,2);
             DirpartyTable.LanguageId           = "FR";
             DirpartyTable.PartyId              = AccountNum;

             print custTable.AccountNum;
             print custTable.Name;
             print dirpartytable.PartyId;

             DirpartyTable.insert();



             select recId from _dirpartytable
                where _dirpartytable.RecId   == dirpartytable.RecId
                    && dirpartytable.PartyId == AccountNum;
                    print _dirpartytable.RecId;
             addressTab.AddrRecId        = _dirpartytable.RecId;
             addressTab.AddrTableId      = 2303;
             addressTab.State            = conpeek(c,4);
             addressTab.Street           = conpeek(c,3);
             addressTab.ZipCode          = conpeek(c,5);

             addressTab.insert();
    }

    info("finish");
}