Friday 29 December 2017

Notes

1.if(ComboBox.selection() == ABC::A)

2. Sales Invoice report in ax 2012 R3

Getting the customer address from salesorder i,e salestable ... we should consider
LogisticsPostalAddress table

select salesTable
        join logisticsPostalAddress where salesTable.SalesId == "05SSSSO171800115"
        && logisticsPostalAddress.RecId == salesTable.DeliveryPostalAddress;     
 
    info(strFmt("%1",logisticsPostalAddress.Address));

----

tables and classes involved in Sales Invoice report

url

https://atinkerersnotebook.com/2012/10/05/creating-automatic-email-confirmations-from-dynamics-ax/


Thursday 28 December 2017

send mail withy pdf in ax 2012

SysEmailParameters parameters = SysEmailParameters::find();
    FilePath FilePath;
    SMTPRelayServerName relayServer;
    SMTPPortNumber portNumber;
    SMTPUserName userName;
    SMTPPassword password;
    Str1260 subject,body;
    InteropPermission interopPermission;
    SysMailer mailer;
    SysMailerAttachments    sysMailerAttachments;
    System.Exception e;

    ;
    if (parameters.SMTPRelayServerName)
        relayServer = parameters.SMTPRelayServerName;
    else
        relayServer = parameters.SMTPServerIPAddress;
        portNumber = parameters.SMTPPortNumber;
        userName = parameters.SMTPUserName;
        password = SysEmailParameters::password();
   
        subject = "Subject line for the email";
        body = "<B>Body of the email</B>";
            body += "<br/> <B>testing</B>"; /
        body += "<br/>red</Br/>";
         body += "<br/>blue</Br/>";
         body += "<br/>orange</Br/>";
         body += "<br/>testing</Br/>";

    CodeAccessPermission::revertAssert();

    try
    {
        interopPermission = new InteropPermission(InteropKind::ComInterop);
        interopPermission.assert();
       
        FilePath = '@C//q.pdf';
        FilePath = strfmt('C:\\q.pdf');
        mailer = new SysMailer();
        mailer.SMTPRelayServer(relayServer,portNumber,userName,password, parameters.NTLM);
        //instantiate email
        mailer.fromAddress(userName);

        mailer.tos().appendAddress("email");
        mailer.subject(subject);
        mailer.htmlBody(body);
        mailer.attachments().add(FilePath);
        mailer.sendMail();
        CodeAccessPermission::revertAssert();
        info("Email has been sent!");
    }
    catch (Exception::CLRError)

    {
    e = ClrInterop::getLastException();

    while (e)

    {
        info(e.get_Message());
        e = e.get_InnerException();
    }
    CodeAccessPermission::revertAssert();
    //info(e);
    info ("Failed to Send Email some Error occure");

Friday 15 December 2017

Run base batch to clean undecided number Seq in status List

class NumsSeq extends RunBaseBatch
{
    RefRecId                numSeqId;
    NumberSequenceList      numberSequenceList;

    DialogField dlgNumSeqId;

    #define.CurrentVersion(4)
    #localmacro.CurrentList
    dlgNumSeqId
    #endmacro
}

...................................................................................

protected Object dialog()
{
DialogRunbase dialog;

dialog = super();
dialog = super();
dlgNumSeqId = dialog.addFieldValue(extendedTypeStr(RefRecId),numSeqId);

return dialog;
}

..................................

public boolean getFromDialog()
{
boolean ret;

ret = super();
numSeqId = dlgNumSeqId.value();

return ret;
}

//////////////////////////////

public container pack()
{
    return [numSeqId];
}

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

/// <summary>
///    Contains the code that does the actual job of the class.
/// </summary>
public void run()
{
    while select forUpdate numberSequenceList where numberSequenceList.NumberSequenceId == numSeqId
        &&   numberSequenceList.Status == NumStatus::Active//5637147121
    {
        ttsBegin;
        if(numberSequenceList.cleanAction() == NumberSeqCleanAction::Undecided )
        {
            numberSequenceList.delete();
        }

        ttsCommit;
    }
}


...........................


public boolean unpack(container packedClass)
{
[numSeqId] = packedClass;
    return true;

}

.........................................

public static void main(Args args)
{
    NumsSeq numsSeq = new NumsSeq();

    if(numsSeq.prompt())
    {
        numsSeq.run();
    }
}

Thursday 14 December 2017

update proj dimensions in ax 2012

class ProjDimUpload
{
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
}

.................................................................................

public void importProjDim()
{
    ProjId              projId;

    RecId               recIdDefaultDimension;


    //table
    ProjTable               projTable;

    container   financialDimensionFromExcel;
    container   conDimensionName;
    Dialog                  dialog;
    DialogGroup             dialogGroup;
    DialogField             dialogfilename;
    Filename                filename;
    COMVariantType          type;

    str                     strDate;
    int                     row;

    ;
       startLengthyOperation();
    //variable yang diisi manual
    filename              = "C:\\Proj  excel Dim upload.xlsx";
   


    dialog          = new Dialog("Select File For Proj Master Dim Import");
    dialogGroup     = dialog.addGroup("Excel File");
    dialogfilename  = dialog.addField(extendedTypeStr(FilenameOpen));

    if (dialog.run())
    {
        application = SysExcelApplication::construct();
        workbooks   = application.workbooks();
        filename=dialogfilename.value();
         try
    {
        if (workbooks.open(filename, false /*Update links*/, true /*Read only*/))
        {
            workbook   = workbooks.item(1);
            workSheets = workbook.worksheets();
            workSheet  = workSheets.itemFromNum(1); //worksheet keberapa dari excel di mulai dari angka 1
            cells      = workSheet.cells();
            conDimensionName = this.TIDgetDimensionName();
            row = 2;

            ttsBegin;
            while (cells.item(row,2).value().bStr() != "")
            {
                //financial dimension
                financialDimensionFromExcel = conNull();
                //dimension value 1
                financialDimensionFromExcel += cells.item(row,2).value().bStr();
                //dimension value 2
                financialDimensionFromExcel += cells.item(row,3).value().bStr();
                //dimension value 3
                financialDimensionFromExcel += cells.item(row,4).value().bStr();
                //dimension value 4
                financialDimensionFromExcel += cells.item(row,5).value().bStr();
                //dimension value 5
                financialDimensionFromExcel += cells.item(row,6).value().bStr();
                //dimension value 6
                financialDimensionFromExcel += cells.item(row,7).value().bStr();
                //dimension value 7
                financialDimensionFromExcel += cells.item(row,8).value().bStr();
                //dimension value 8
                financialDimensionFromExcel += cells.item(row,9).value().bStr();
                //dimension value 9
                financialDimensionFromExcel += cells.item(row,10).value().bStr();
                //dimension value 10
                financialDimensionFromExcel += cells.item(row,11).value().bStr();
                //generateDefaultDimension
                recIdDefaultDimension       = this.TIDcreateDefaultDimension(conDimensionName,financialDimensionFromExcel);

                //variable
                //assetId           = this.TIDComVariant2STR(cells.item(row,2).value());
                projId      = this.TIDComVariant2STR(cells.item(row,1).value());

                //table
                projTable      = ProjTable::find(projId);

                //validation
                if(!projTable)
                {
                    throw error(strFmt("Row : %1 ,ProjId not exists, please check again",row));
                }
             

                    projTable.selectForUpdate(true);

                    projTable.DefaultDimension      = recIdDefaultDimension;
                    projTable.update();
                row++;
                }
             
            }
            ttsCommit;
            application.quit();
        }

    catch(Exception::Error)
    {
        info("Proj upload Error");
        application.quit();
    }
    }
    info(strFmt("%1 Dimensions had been updated",row));
}

......................................................................


public  str TIDComVariant2STR(COMVariant _variant)
{
    str valueStr;
    ;

    switch(_variant.variantType())
    {
        case COMVariantType::VT_EMPTY   :
            valueStr = '';
            break;

        case COMVariantType::VT_BSTR    :

            valueStr = _variant.bStr();
            break;

        case COMVariantType::VT_R4      :
        case COMVariantType::VT_R8      :

            if(_variant.double())
            {
                valueStr = strFmt("@SYS311964",
                                    num2Str0(_variant.double(), 0),
                                    num2str(_variant.double(),
                                    0,
                                    numOfDec(_variant.double()),
                                    1,
                                    0));
            }
            break;

        default                         :
            throw error(strfmt("@SYS26908",
                                _variant.variantType()));
    }

    return valueStr;
}


...........................

Public DimensionDefault TIDcreateDefaultDimension(container _attr, container _value, boolean _createIfNotFound = true)
{
    DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();
    DimensionDefault                    result;
    int                                 i;
    DimensionAttribute                  dimensionAttribute;
    DimensionAttributeValue             dimensionAttributeValue;
    //_attr is dimension name in table DimensionAttribute
    container               conAttr =   _attr;
    container               conValue = _value;
    str                     dimValue;

    for (i = 1; i <= conLen(conAttr); i++)
    {
        dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));

        if (dimensionAttribute.RecId == 0)
        {
            continue;
        }

        dimValue = conPeek(conValue,i);

        if (dimValue != "")
        {
            // _createIfNotFound is "true". A dimensionAttributeValue record will be created if not found.
            dimensionAttributeValue = dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,_createIfNotFound);

            // Add the dimensionAttibuteValue to the default dimension
            valueSetStorage.addItem(dimensionAttributeValue);
        }
    }
    result = valueSetStorage.save();
    return result;
}


..............................

public  container TIDgetDimensionName()
{
    DimensionAttribute              dimAttr;
    DimensionAttributeSetItem       dimAttrSetItem;
    DimensionEnumeration            dimensionSetId;
    DimensionAttributeValue         dimAttributeValue;
    container                       DimensionName;

    dimensionSetId      = DimensionCache::getDimensionAttributeSetForLedger();

    while select dimAttr order by Name
                where dimAttr.Type != DimensionAttributeType::MainAccount
            join RecId from dimAttrSetItem
                where dimAttrSetItem.DimensionAttribute     == dimAttr.RecId &&
                      dimAttrSetItem.DimensionAttributeSet  == dimensionSetId
            {
                dimensionName += dimAttr.Name;

            }

    return DimensionName;
}

.......................................................................

public static void main(Args args)
{
   ProjDimUpload projDimUpload = new ProjDimUpload();
    projDimUpload.importProjDim();
}

Import fixed assets dim ax 2012

class FixedAssetDimUpload
{
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;


}


//////////////////////////////////////////////////////////////////////

public void importFixedAssetDim()
{
    AssetId             assetId;
    AssetGroupId        assetGroupId;
    AssetName           assetName;
    AssetLocationId     assetLocationId;
    AssetServiceLife    assetServiceLife;
    AssetLifeTimeRest   assetLifeTimeRest;
    AssetPostingProfile assetPostingProfile;
    AssetBookId         assetBookId;
    TransDate           depreciationStartDate,LastDepreciationDate,AcquisitionDate;
    RecId               recIdDefaultDimension;

    AxAssetTable        axAssetTable;



    //table
    AssetTable          assetTable;
    AssetGroup          assetGroup;
    AssetLocation       assetLocation;
    AssetBook           assetBook,assetBookLoc;
    AssetLedger         assetLedger;
    AssetBookTable      assetBookTable;

    container   financialDimensionFromExcel;
    container   conDimensionName;
    Dialog                  dialog;
    DialogGroup             dialogGroup;
    DialogField             dialogfilename;
    Filename                filename;
    COMVariantType          type;

    str                     strDate;
    int                                         row;

    ;
       startLengthyOperation();
    //variable yang diisi manual
    filename              = "C:\\Fixed Asset  excel Dim upload.xlsx";
    assetPostingProfile   = "FA POSTING";
    depreciationStartDate = today();
    LastDepreciationDate  = today();
    AcquisitionDate       = today();

    dialog          = new Dialog("Select File For customer Bank Master Import");
    dialogGroup     = dialog.addGroup("Excel File");
    dialogfilename  = dialog.addField(extendedTypeStr(FilenameOpen));

    if (dialog.run())
    {
        application = SysExcelApplication::construct();
        workbooks   = application.workbooks();
        filename=dialogfilename.value();
         try
    {
        if (workbooks.open(filename, false /*Update links*/, true /*Read only*/))
        {
            workbook   = workbooks.item(1);
            workSheets = workbook.worksheets();
            workSheet  = workSheets.itemFromNum(1); //worksheet keberapa dari excel di mulai dari angka 1
            cells      = workSheet.cells();
            conDimensionName = this.TIDgetDimensionName();
            row = 2;

            ttsBegin;
            while (cells.item(row,2).value().bStr() != "")
            {
                //financial dimension
                financialDimensionFromExcel = conNull();
                //dimension value 1
                financialDimensionFromExcel += cells.item(row,7).value().bStr();
                //dimension value 2
                financialDimensionFromExcel += cells.item(row,8).value().bStr();
                //dimension value 3
                financialDimensionFromExcel += cells.item(row,9).value().bStr();
                //dimension value 4
                financialDimensionFromExcel += cells.item(row,10).value().bStr();
                //dimension value 5
                financialDimensionFromExcel += cells.item(row,11).value().bStr();
                //dimension value 6
                financialDimensionFromExcel += cells.item(row,12).value().bStr();
                //generateDefaultDimension
                recIdDefaultDimension       = this.TIDcreateDefaultDimension(conDimensionName,financialDimensionFromExcel);

                //variable
                assetId           = this.TIDComVariant2STR(cells.item(row,2).value());
                assetGroupId      = this.TIDComVariant2STR(cells.item(row,1).value());
                assetLocationId   = this.TIDComVariant2STR(cells.item(row,6).value());
                assetName         = this.TIDComVariant2STR(cells.item(row,3).value());
                strDate = this.TIDComVariant2STR(cells.item(row,4).value());
                depreciationStartDate = str2Date(strDate,123);
                //assetServiceLife  = str2num(this.TIDComVariant2STR(cells.item(row,4).value()));
                assetLifeTimeRest = str2num(this.TIDComVariant2STR(cells.item(row,5).value()));
                assetBookId       = this.TIDComVariant2STR(cells.item(row,13).value());
                //table
                assetTable      = assetTable::find(assetId);
                assetGroup      = AssetGroup::find(assetGroupId);
                assetLocation   = AssetLocation::find(assetLocationId);

                //validation
                if(!assetGroup)// || !assetLocation)
                {
                    throw error(strFmt("Row : %1 ,Asset group or asset location not existed, please check again",row));
                }
                //create asset Table


                //create assetBook
                assetBookLoc = assetBook::find(assetId,assetBookId);
                select assetBook
                    join assetBookTable
                        where assetBook.BookId == assetBookTable.BookId
                        && assetBook.AssetId == assetBookLoc.AssetId
                        && assetBook.BookId == assetBookLoc.BookId
                        && assetBookTable.CurrentOperationsTax == CurrentOperationsTax::Current;
                if(!assetBook)
                {
                    assetBook.clear();
                    //assetBook.initValue();
                    //assetBook.AssetId               = assetId;
                    //assetBook.BookId                = assetBookId;
                    //assetBook.PostingProfile        = assetPostingProfile;
                    //assetBook.ServiceLife           = assetServiceLife;
                    //assetBook.LifeTime              = assetServiceLife*12;
                    //assetBook.LifeTimeRest          = assetLifeTimeRest;
                    //assetBook.DepreciationStartDate = depreciationStartDate;
                    //assetBook.LastDepreciationDate  = LastDepreciationDate;
                    //assetBook.AcquisitionDate       = AcquisitionDate;
                    //assetBook.DefaultDimension      = recIdDefaultDimension;
                    //assetBook.insert();
                }
                else
                {
                    assetBook.selectForUpdate(true);

                    assetBook.DepreciationStartDate = depreciationStartDate;

                    assetBook.DefaultDimension      = recIdDefaultDimension;
                    assetBook.update();
                }


                row++;
            }
            ttsCommit;
            application.quit();
        }
    }
    catch(Exception::Error)
    {
        info("Fixed Asset upload Error");
        application.quit();
    }
    }
    info("Dimensions had been updated");
}

///////

public  str TIDComVariant2STR(COMVariant _variant)
{
    str valueStr;
    ;

    switch(_variant.variantType())
    {
        case COMVariantType::VT_EMPTY   :
            valueStr = '';
            break;

        case COMVariantType::VT_BSTR    :

            valueStr = _variant.bStr();
            break;

        case COMVariantType::VT_R4      :
        case COMVariantType::VT_R8      :

            if(_variant.double())
            {
                valueStr = strFmt("@SYS311964",
                                    num2Str0(_variant.double(), 0),
                                    num2str(_variant.double(),
                                    0,
                                    numOfDec(_variant.double()),
                                    1,
                                    0));
            }
            break;

        default                         :
            throw error(strfmt("@SYS26908",
                                _variant.variantType()));
    }

    return valueStr;
}

/////

Public DimensionDefault TIDcreateDefaultDimension(container _attr, container _value, boolean _createIfNotFound = true)
{
    DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();
    DimensionDefault                    result;
    int                                 i;
    DimensionAttribute                  dimensionAttribute;
    DimensionAttributeValue             dimensionAttributeValue;
    //_attr is dimension name in table DimensionAttribute
    container               conAttr =   _attr;
    container               conValue = _value;
    str                     dimValue;

    for (i = 1; i <= conLen(conAttr); i++)
    {
        dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));

        if (dimensionAttribute.RecId == 0)
        {
            continue;
        }

        dimValue = conPeek(conValue,i);

        if (dimValue != "")
        {
            // _createIfNotFound is "true". A dimensionAttributeValue record will be created if not found.
            dimensionAttributeValue = dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,_createIfNotFound);

            // Add the dimensionAttibuteValue to the default dimension
            valueSetStorage.addItem(dimensionAttributeValue);
        }
    }
    result = valueSetStorage.save();
    return result;
}

////

public  container TIDgetDimensionName()
{
    DimensionAttribute              dimAttr;
    DimensionAttributeSetItem       dimAttrSetItem;
    DimensionEnumeration            dimensionSetId;
    DimensionAttributeValue         dimAttributeValue;
    container                       DimensionName;

    dimensionSetId      = DimensionCache::getDimensionAttributeSetForLedger();

    while select dimAttr order by Name
                where dimAttr.Type != DimensionAttributeType::MainAccount
            join RecId from dimAttrSetItem
                where dimAttrSetItem.DimensionAttribute     == dimAttr.RecId &&
                      dimAttrSetItem.DimensionAttributeSet  == dimensionSetId
            {
                dimensionName += dimAttr.Name;

            }

    return DimensionName;
}
///

public static void main(Args args)
{
    FixedAssetDimUpload fixedAssetDimUpload = newFixedAssetDimUpload();
    fixedAssetDimUpload.importFixedAssetDim();
}

Tuesday 12 December 2017

company address in ax 2009

Display str CompanyAddress()
{
    InventSiteId  inventSiteId;
    TextBuffer  txt = new TextBuffer();
    Addressing  address;
    CompanyInfo companyInfoLoc;
    ;

    companyInfoLoc = CompanyInfo::find();
    inventSiteId =PurchTable::find(VendPurchOrderJour.PurchId).InventSiteId;
    address = Address::findByInventSiteIdandTableRecId(inventSiteId,companyInfoLoc.TableId,companyInfoLoc.RecId
            ,AddressType::Invoice).Address;

    txt.setText(address);
    txt.replace('\n',' ');
    address = txt.getText();

    return(address);
}

Tuesday 5 December 2017

convert currency

static void CurrencyConvertor(Args _args)
{
CurrencyExchangeHelper currencyExchangeHelper;
CurrencyCode transCurrency = "INR";
AmountCur amountCur = 500.00;
AmountMst amountMST;

currencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::current(), systemDateGet());
amountMST = currencyExchangeHelper.calculateTransactionToAccounting(transCurrency, amountCur ,true);
info(strFmt("%1",amountMST));
}