Sunday, July 30, 2017

X++ Code To Adding Days and Months With From Date

Date Addition Jobs


    info(strFmt("Today is: %1 ",today()));
   
    //Add days
    info(strFmt("Add 5 days to today: %1 ",today()+5));
    info(strFmt("Add 10 days to today: %1 ",systemdateget()+10));

    //Add months
    info(strFmt("Add 12 months to today: %1 ",dateMthFwd(systemdateget(),12)));  //Adds 1 year
    info(strFmt("Add 24 months to today: %1 ",dateMthFwd(systemdateget(),24)));  // add 2 year

Thursday, July 27, 2017

X++ code for Import Fixed Asset

static void FIxedAssetImport(Args _args)
{
    SysExcelApplication    Application;
    SysExcelWorkbooks    workbooks;
    SysExcelWorkbook     workbook;
    SysExcelWorkSheets   worksheets;
    SysExcelWorksheet    worksheet;
    SysExcelCells            cells;
    COMVariantType       type;
    Name                         Descriptions;
    //Filename                 fileName;
    AssetTable                 AssetTable;
    Dialog                        dialog;
    DialogField                dialogField;
    FilenameOpen            filename;
    int row =1 ;
    str AssetCategory,AssetId,AssetSubCategory,SerialNum,Status,AcquisitionYear,AssetLife,DepriciableDays;
    real NetBook,originalAssetCost,Yearly,AccumulatedDepriciation;
    int i=0 ;
    //  COMVariantType type;
    date DateOfIstallations,DateOfPurchase;
    FileIOPermission        permission;
    #File

    str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
    {
    switch (_cv.variantType())
    {
    case (COMVariantType::VT_BSTR):
    return _cv.bStr();
    case (COMVariantType::VT_R4):
    return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);
    case (COMVariantType::VT_R8):
    return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);
    case (COMVariantType::VT_DECIMAL):
    return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);
    case (COMVariantType::VT_DATE):
    return date2str(_cv.date(),123,2,1,2,1,4);
    case (COMVariantType::VT_EMPTY):
    return "";
    default:
    throw error(strfmt("@SYS26908", _cv.variantType()));
    }
    return "";
    }

    //importing from excel
    dialog = new Dialog("FixedAsset Import");
    dialogField = dialog.addField(ExtendedTypeStr("FilenameOpen"),"Source file");

    if (dialog.run())
    {
    filename = dialogField.value();
    permission = new fileIOpermission(filename,"r");
    permission.assert();
    Application = SysExcelApplication::construct();
    workbooks   = Application.workbooks();

    try
    {
        workbooks.open(fileName);
    }
    catch
    {
        throw error("File cannot be opened");
    }

    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    do
    {
        i++;
        row++;
        AcquisitionYear        = COMVariant2str(cells.item(row,2).value());
        AssetId                = cells.item(row,3).value().bStr();
        AssetCategory          = cells.item(row,4).value().bStr();
        AssetSubCategory       = cells.item(row,5).value().bStr();
        Descriptions           = cells.item(row,6).value().bStr();
        SerialNum              = cells.item(row,7).value().bStr();
        DateOfIstallations     = cells.item(row,8).value().date();
        DateOfPurchase         = cells.item(row,9).value().date();
        originalAssetCost      = cells.item(row,10).value().double();
        AssetLife              = COMVariant2str(cells.item(row,11).value());
        Yearly                 = cells.item(row,12).value().double();
        NetBook                = cells.item(row,13).value().double();
        Status                 = cells.item(row,14).value().bStr();
        DepriciableDays        = COMVariant2str(cells.item(row,16).value());
        AccumulatedDepriciation= cells.item(row,17).value().double();


        AssetTable.AcquisitionYear                 = AcquisitionYear  ;
        AssetTable.AssetId                               = AssetId  ;
        AssetTable.AssetCategory                    = AssetCategory  ;
        AssetTable.AssetSubCategory              = AssetSubCategory  ;
        AssetTable.Name                                  = Descriptions  ;
        AssetTable.SerialNum                          = SerialNum  ;
        AssetTable.DateOfInstallations            = DateOfIstallations  ;
        AssetTable.DateOfPurchase                 = DateOfPurchase  ;
        AssetTable.OriginalAssetCost              = originalAssetCost  ;
        AssetTable.AssetLife                            = AssetLife  ;
        AssetTable.YearlyDepriciation             = Yearly  ;
        AssetTable.NetBookValueason             = NetBook  ;
        AssetTable.Status                                  = Status  ;
        AssetTable.DepriciableDays                 = DepriciableDays;
        AssetTable.AccumulatedDepriciations = AccumulatedDepriciation;
        AssetTable.insert();
         //info(strFmt("DATAiMPORTED"));

         type = cells.item(row+1,2).value().variantType();
    }

    while(type != COMVariantType::VT_EMPTY);
    Application.quit();
    //info(strFmt("%1",i));

}
}

Wednesday, July 19, 2017

X++ Code To Update Customer Details In Ax 2012

X++ Code to Update R3 data for Existing Customers..


static void CustomerUpdate(Args _args)
{


CustTable                                 custTable;
DirParty                                   dirParty;
DirPartyRecId                          partyRecId;
LogisticsPostalAddress            address;
DirPartyPostalAddressView    addressView;
DirPartyTable                          dirPartyTable;
LogisticsPostalAddress           logisticsPostalAddress;
LogisticsElectronicAddress    logisticsElectronicAddress;
DirPartyPostalAddressView   dirPartyPostalAddressView;
DirPartyContactInfoView       dirPartyContactInfo;


Name                     name                  = "Test";
AccountNum         accountNum      = "DE-001";
CustGroupId          custGroupId      = "20";
CurrencyCode       currencyCode    = "INR";
PaymTermId          paymTermId     = "Net45";
DlvModeId            dlvModeId        = "30";
str                          country              = "India";
str                          State                  = "TamilNadu";
str                          city                    = "madurai";
str                          ZipCode            = "625007";
str                         street                  = "K.pudur";
str                         phone                 = "8220308543";
str                         Fax                     = "123";
str                         Email                 = "j.jackrider@gmail.com";
 
ttsBegin;
select forUpdate custTable where custtable.AccountNum == accountNum ;

if(custTable)
{

    if(name)
    {
    partyRecId = DirPartyTable::createNew( DirPartyType::Organization, name).RecId;
    custTable.Party      = partyRecId;
    }

    if(custGroupId)
    {
    custTable.CustGroup = custGroupId;
    }

    if(currencyCode)
    {
    custTable.Currency = currencyCode;
    }

    if(paymTermId)
    {
    custTable.PaymTermId = paymTermId;
    }

    if(dlvModeId)
    {
    custTable.DlvMode = dlvModeId;
    }

    if(country)
    {
        partyRecId = DirPartyTable::createNew( DirPartyType::Organization, name).RecId;
        custTable.Party      = partyRecId;

        DirParty = DirParty::constructFromPartyRecId(partyRecId );
        address.clear();

        address.CountryRegionId = strLRTrim(country);
        dirParty = DirParty::constructFromCommon(custTable);

        if( address.CountryRegionId != "")
        {
        address.State   = State;
        address.City    = City;
        address.ZipCode = ZipCode;
        address.Street  = Street;
        addressView.LocationName = "Address";
        addressView.IsPrimary = NoYes::Yes;
        addressView.Party = partyRecId;
        addressview.initFromPostalAddress(address);

        DirParty = DirParty::constructFromPartyRecId(addressView.Party );
        DirParty.createOrUpdatePostalAddress(addressView);
        }

    }

    if(phone)
    {
    dirPartyContactInfo.LocationName = "Phone Number";
    dirPartyContactInfo.Locator      = strLRTrim(phone);
    dirPartyContactInfo.Type         = LogisticsElectronicAddressMethodType::Phone;
    dirPartyContactInfo.Party        = partyRecId;
    dirPartyContactInfo.IsPrimary    = NoYes::Yes;
    dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
    }

    if(Fax)
    {
    dirPartyContactInfo.LocationName = "Fax Number";
    dirPartyContactInfo.Locator      = strLRTrim(Fax);
    dirPartyContactInfo.Type         = LogisticsElectronicAddressMethodType::Fax;
    dirPartyContactInfo.Party        = partyRecId;
    dirPartyContactInfo.IsPrimary    = NoYes::Yes;
    dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
    }

    if(Email)
    {
    dirPartyContactInfo.LocationName = "Email";
    dirPartyContactInfo.Locator      = strLRTrim(Email);
    dirPartyContactInfo.Type         = LogisticsElectronicAddressMethodType::Email;
    dirPartyContactInfo.Party        = partyRecId;
    dirPartyContactInfo.IsPrimary    = NoYes::Yes;
    dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
    }

    custTable.update();
    info("Customer Updated");
}

ttsCommit;


}

Saturday, June 17, 2017

Object Server 01: Fatal SQL condition during login. Error message: "The internal time zone version number stored in the database is higher than the version supported by the kernel (8/7). Use a newer Microsoft Dynamics AX kernel."

Object Server 01:  Fatal SQL condition during login. Error message: "The internal time zone version number stored in the database is higher than the version supported by the kernel (8/7). Use a newer Microsoft Dynamics AX kernel."



Solution:

Open SSMS (SQL)
Run enter SSMS and Enter.



Run the below script:   on SQL 


select * from SQLSystemVariables
WHERE PARM = 'SYSTIMEZONESVERSION'

UPDATE SQLSystemVariables
SET VALUE = 7
WHERE PARM = 'SYSTIMEZONESVERSION'



Monday, May 29, 2017

X++ code to Import General Journal by CSV file in Ax 2012

static void GeneralJournalinsert(Args _args)
{
Dialog                      dialog;
DialogField                 dfFileName;
boolean first = true;
Io io;

#file
LedgerJournalType                        JournalType;
str                                     voucher,journalnum,journaldate,offsetaccounttype,offsetaccount,paymentreference,department,costcenter,offsetcostcenter,offsetdepartment,journalname,methodofpayment,currency,name,companyaccount,accounttype,account,Description ;
int                                       debit,credit;
TransDate                                  transdate;
DimensionDynamicAccount                      ledger;
str                                         filenameopen;
int64                   ledgerOffset;
FilenameOpen        filename = "j:\\sample.csv";//To assign file name
Container           readcon;

AxLedgerJournalTable    journalTable;
AxLedgerJournalTrans    journalTrans;
container               acctPattern;
container               offSetAcctPattern;
LedgerJournalTable      ledgerJournalTable;
ledgerJournalCheckPost  ledgerJournalCheckPost;

journalTable = new AxLedgerJournalTable();//  header table class

    iO = new CommaTextIo(filename,#IO_Read);
    if (! iO || iO.status() != IO_Status::Ok)
    {
    throw error("@SYS19358");
    }
    while (iO.status() == IO_Status::Ok)
    {
    readCon = iO.read();// To read file
    if (readCon)
    {
    if (first)  //To skip header
    {
    first = false;
    }
    else
    {
              
                journalname              = conPeek(readCon,1);
                journaldate                = conPeek(readCon,2);
                transdate                   = str2Date(journaldate,123);
                voucher                     =  conPeek(readCon,3);
                accounttype              = conPeek(readCon,4);
                account                     = conPeek(readCon,5);
                Description                = conPeek(readCon,6);
                Debit                         = conPeek(readCon,7);
                credit                         = conPeek(readCon,8);
                offsetaccounttype     = conPeek(readCon,9);
                offsetaccount            = conPeek(readCon,10);
                department               = conPeek(readCon,11);
                costcenter                 = conPeek(readCon,12);
                offsetcostcenter        = conPeek(readCon,13);
                offsetdepartment       = conPeek(readCon,14);


journalTable.parmJournalName(journalname);
journalTable.save();

journalTrans = new AxLedgerJournalTrans();        //// line table class
journalTrans.parmJournalNum(journalTable.ledgerJournalTable().JournalNum);


journalTrans.parmTransDate(transdate);
journalTrans.parmAmountCurDebit(Debit);
journalTrans.parmAmountCurCredit(credit);
journalTrans.parmAccountType(LedgerJournalACType::Ledger);
acctPattern   =  [account,account, 2, "department",department,"costcenter", costcenter];
journalTrans.parmLedgerDimension(AxdDimensionUtil::getLedgerAccountId(acctPattern));

offSetAcctPattern = [offsetaccount,offsetaccount, 2, "Department",offsetdepartment, "CostCenter",offsetcostcenter];
journalTrans.parmOffsetLedgerDimension(AxdDimensionUtil::getLedgerAccountId( offSetAcctPattern));
journalTrans.parmOffsetAccountType(LedgerJournalACType:: Ledger );

journalTrans.save();

//ledgerJournalCheckPost = //ledgerJournalCheckPost::newLedgerJournalTable(journalTable.ledgerJournalTable(),NoYes::Yes);
//ledgerJournalCheckPost.run();

info(strFmt("Journal No. %1.", journalTable.ledgerJournalTable().JournalNum));
}
    }

}
}

Wednesday, March 8, 2017

Shrinking log file on sql database in Ax

Shrinking log file on sql database


1.First open SQL Database------>right click MicrosoftDynamicsAx----click properties to check file size

2.Then for safety purpose ----->right click MicrosoftDynamicsAx------>Task----->Backup,

3.And remove the existing path and add your desired path location.


4.Then click MicrosoftDynamicsAx----->Right click ----> Newquery


5.Then the page display like this

6.In this Page add your db shrinking code 

USE MicrosoftDynamicsAX;
ALTER DATABASE MicrosoftDynamicsAX
SET RECOVERY SIMPLE;
DBCC SHRINKFILE (MicrosoftDynamicsAX_Log, 0);
ALTER DATABASE MicrosoftDynamicsAX
SET RECOVERY FULL


7.Click Execute on top of the page

8.The Database will be shrinked and reduced into small. 
  

Sunday, March 5, 2017

How to reset "unbalanced ttsbegin ttscomit " error in ax 2012

To reset "Unbalanced ttsbegin ttscommit pair has been detected" error in AX 2012

//Write this code in Job and Run.

static void TheAxaptaResetTTS(Args _args)
{
    while (appl.ttsLevel() > 0)
    {
        info(strfmt("Level %1 aborted",appl.ttsLevel()));
        ttsAbort;
    }
}

Saturday, March 4, 2017

Form Methods in Ax 2012

Sequence of form Methods:

This gives the information of method calls in the form level while
1. Opening the Form.
2. Creating/Updating/Deleting the record in the Form.
3. Closing the Form.


Sequence of Methods calls while opening the Form

Form — init ()
Form — Datasource — init ()
Form — run ()
Form — Datasource — execute Query ()
Form — Datasource — active ()


Sequence of Methods calls while closing the Form


Form — canClose ()
Form — close ()

Sequence of Methods calls while creating the record in the Form


Form — Datasource — create ()
Form — Datasource — initValue ()
Table — initValue ()
Form — Datasource — active ()

Sequence of Method calls while saving the record in the Form


Form — Datasource — ValidateWrite ()
Table — ValidateWrite ()
Form — Datasource — write ()
Table — insert ()

Sequence of Method calls while deleting the record in the Form


Form — Datasource — validatedelete ()
Table — validatedelete ()
Table — delete ()
Form — Datasource — active ()

Sequence of Methods calls while modifying the fields in the Form

Table — validateField ()
Table — modifiedField ()

Thursday, March 2, 2017

Sequence Of Table Methods in Ax 2012

   Sequence Of Table Methods



    When you press CTR+N

    inItValue()

    When you change data in a Field

    validateField()  -> validateFieldValue() ->  ModifiedField() ->  ModifiedFieldValue()

    When you close the table after entering some data

    validateWrite() - > Insert()  -> aosValidateInsert()

    When you open the table which will contain some data
    If table will contain 10 records this method is called 10 times

    aosValidateRead()

    When you Save the Record for the first time

    validateWrite() ->Insert() - > aosValidateInsert()

    When you modify the record and saving

    validateWrite() -> update() - > aosValidateUpdate()

    When you delete the record

    validateDelete() -> delete() -> aosValidateDelete()

Wednesday, March 1, 2017

Import From Excel File Using X++ in AX 2012



In this example i have my customized table ImportTable with the following fields
(itemid,qty,price,purchunit,lineamount)



static void ImportFromExcel(Args _args)
{
Dialog _dialog;
DialogField _file;
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
ImportTable importTable; //Declaring Table Name
int  row = 1;
str   _itemid;
real  _qty;
real  _price;
str   _purchunit;
real  _lineamount;

_dialog = new Dialog("Please select the file to load");
_dialog.addText("Select file:");
_file   = _dialog.addField(ExtendedTypeStr("FilenameOpen"));
_dialog.run();

if (_dialog.closedOK())
{
info(_file.value() );

application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename =_file.value(); //ExcelSheet File Name
try
{
     workbooks.open(filename);
}
catch (Exception::Error)
{
     throw error('File cannot be opened');
}

workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(1); //Here 1 is the worksheet Number
cells = worksheet.cells();
do
{
        row++;
        _itemid     = cells.item(row, 1).value().bStr();
        _qty         = cells.item(row, 2).value().double();
        _price       = cells.item(row, 3).value().double();
        _purchunit   = cells.item(row, 4).value().bStr();
        _lineamount  = cells.item(row, 5).value().double();

        importTable.ItemId       = _itemid;
        importTable.Qty          = _qty;
        importTable.Price        = _price;
        importTable.PurchUnit    = _purchunit;
        importTable.LineAmount   = _lineamount;
        importTable.insert();
        type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
application.quit();
info("Data is Imported");
}
}

Find Onhand Qty by ItemId In X++ code

On Hand Qty by ItemId:



static void onhandcode(Args _args)
{
InventOnhand  inventOnhand;
InventDim     inventDim;
InventDimParm inventDimParm;
ItemId        itemId;
InventQty     availqty;

itemId = "1102";

inventDimParm.initFromInventDim(inventDim);

inventOnhand = inventOnhand::newParameters(itemId,inventDim,inventDimParm);
availqty = inventOnhand.availPhysical();
info(strFmt("%1",availqty));

}