Monday, August 14, 2017

X++ Code to Switch Sign value

static void SwitchSigns(Args _args)
{
Amount origAmount = -590.39;
Amount newAmount;

newAmount = origAmount * -1;

info (strFmt("%1 - Switched signs: %2", origAmount, newAmount));

origAmount = 243.55;

newAmount = origAmount * -1;

info (strFmt("%1 - Switched signs: %2", origAmount, newAmount));
}

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));

}

Tuesday, February 28, 2017

Simple Dialog In Ax 2012

Creating a Simple Dialog:

The application class Dialog is used to build dialogs. Other application classes, such as
DialogField, DialogGroup, DialogTabPage, and others, are used to create dialog
controls. A common way of using dialogs is within the RunBase framework classes, where
user input is required

Steps:

  1. Expand AOT and create a new Class and name it CustCreate as me..
  2. And Copy the following Code
method 1;

class CustCreate extends RunBase
{
DialogField fieldAccount;
DialogField fieldName;
DialogField fieldGroup;
DialogField fieldCurrency;
DialogField fieldPaymTermId;
DialogField fieldPaymMode;
CustAccount custAccount;
CustName custName;
CustGroupId custGroupId;
CurrencyCode currencyCode;
CustPaymTermId paymTermId;
CustPaymMode paymMode;
}

method 2;

public container pack()
{
return conNull();
}

method 3:

public boolean unpack(container _packedClass)
{
return true;
}

method 4:

protected Object dialog()
{
Dialog dialog;
DialogGroup groupCustomer;
DialogGroup groupPayment;
dialog = super();
dialog.caption("Customer information");
fieldAccount = dialog.addField(extendedTypeStr(CustVendAC),"Customer account");
fieldName =dialog.addField(extendedTypeStr(CustName));dialog.addTabPage("Details");
groupCustomer = dialog.addGroup("Setup");
fieldGroup = dialog.addField(extendedTypeStr(CustGroupId));
fieldCurrency = dialog.addField(extendedTypeStr(CurrencyCode));
groupPayment = dialog.addGroup("Payment");
fieldPaymTermId = dialog.addField(extendedTypeStr(CustPaymTermId));
fieldPaymMode = dialog.addField(extendedTypeStr(CustPaymMode));
return dialog;
}

method 5:

public boolean getFromDialog()
{
custAccount = fieldAccount.value();
custName = fieldName.value();
custGroupId = fieldGroup.value();
currencyCode = fieldCurrency.value();
paymTermId = fieldPaymTermId.value();
paymMode = fieldPaymMode.value();
return super();
}

method 6:

public void run()
{
info("You have entered customer information:");
info(strFmt("Account: %1", custAccount));
info(strFmt("Name: %1", custName));
info(strFmt("Group: %1", custGroupId));
info(strFmt("Currency: %1", currencyCode));
info(strFmt("Terms of payment: %1", paymTermId));
info(strFmt("Method of payment: %1", paymMode));
}

method 7:

public static void main(Args _args)
{
CustCreate custCreate = new CustCreate();
if (custCreate.prompt())
{
custCreate.run();
}
}

3.In order to test the dialog, run the class. The following form should appear with the
General tab page open initially:
4.Enter the cust account and name 

5.And in Detail Tab enter following data
6. click ok

Monday, February 27, 2017

How to Create Foregin Key Relation In AX 2012

Table Relation:

Foreginkey Relation  For Example

  1. First create a new table like Foreginkey table and add a new fields as u want 
  2. And create new ETD as ID and drag into Foreginkey table
  3. Then create  new index for table in the name of ID
  4. In Index property set alternate key "YES" and allow duplicates "NO" 
  5. Then In Foreginkey table property set primary key as Index name "ID" in lookup
  6. And then  ETD "ID" property set  ---> reference table ---> as Foreginkey Table
  7. Then expand the ETD "ID" right click ----> table reference ---> new table reference and related field as "ID"

  8. At last if u  drag an ETD to any other table it will appear like this 
  9. This is foregin key relation.