Quantcast
Channel: Microsoft Dynamics AX - Technical
Viewing all 126 articles
Browse latest View live

Create Purchase order or Sales order and invoice through X++

$
0
0

static void CreatePOAndInvoice(Args _args)

{
     PurchTable      purchTable;
     PurchLine       purchLine;
     VendTable       vendTable = VendTable::find("1000");
     AxPurchTable    axPurchTable;
     AxPurchLine     axPurchLine;
     PurchFormLetter purchFormLetter;
     ;

    //Create Purchase order
     purchTable.initFromVendTable(vendTable);

     axPurchTable = axPurchTable::newPurchTable(purchTable);
     axPurchTable.parmPurchaseType(PurchaseType::Purch);
     axPurchTable.parmDocumentStatus(DocumentStatus::PurchaseOrder);
    // axPurchTable.parmAccountingDate(systemDateGet());
     axPurchTable.parmDeliveryDate(01\06\2012);
     axPurchTable.parmPurchStatus(PurchStatus::Backorder);
     axPurchTable.doSave();

    //Create PurchLine for item 1000
     purchLine.initFromPurchTable(purchTable);

    axPurchLine = AxPurchLine::newPurchLine(purchLine);
     axpurchLine.parmItemId("Test29");
     axpurchLine.parmInventDimId('00000063_069');
     axPurchLine.parmPurchQty(10);
     axPurchLine.parmPurchPrice(100);
     axPurchLine.doSave();

    //Posting PO Confirmation,I guess its mandatory
    //You cannot do invoice without doing PO confirm
    purchTable = axPurchTable.purchTable();
     purchFormLetter = PurchFormLetter::construct(DocumentStatus::PurchaseOrder);
     purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

    //Posting PO Invoice
     purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
     purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

}


Save AX 2009 report in to PDF format.

$
0
0

public boolean fetch()
{
boolean ret;
;

// The below code will save the report of ax 2009 in to pdf format and thus help you to send the report to e-mail.

element.printJobSettings().setTarget(Printmedium::File);
element.printJobSettings().format(Printformat::PDF);
element.printJobSettings().fileName(@’C:\temp\myfile.pdf’);

ret = super();
return ret;
}

Change the color of individual field in ax 2009 Report

$
0
0

public void executeSection()
{
int controlcount;
int counter;
int usecolor;
int oldcolor;
object reportobject;
;
controlcount=this.controlCount();
oldcolor=this.foregroundColor();
if(oldcolor==WinApi::RGB2int(255,255,255))
usecolor=WinApi::RGB2int(209,209,209);
else
usecolor=WinApi::RGB2int(255,255,255);
this.foregroundColor(usecolor);
for(counter=1;counter<=controlcount;counter++)
{
reportobject=this.controlNo(counter);
reportobject.backgroundColor(usecolor);
}
super();
}

To set the password when you start your AX.

$
0
0

The very first class called when you log in to the AX is Application(Class) and method startuppost().

Thus you can write the code here in startuppost method.


void startupPost()
{
dialog d;
dialogfield df, df1, df2;
userinfo user;
boolean ret;
;
d = new dialog(“Password”);
df = d.addField(typeid(userid),”UserName”);
df1 = d.addField(typeid(userid),”UserName”);
df2 = d.addField(typeid(string30),”Password”);
df.value(curuserid());
select user
where user.id == curuserid();
if(user)
{
df1.value(user.name);
}
df1.allowEdit(false);
df1.displayLength(25);
while(d.run())
{
if(!(df2.value() || df2.value() == ‘SetYourPasswordHere’)) // line 23
{
infolog.shutDown(true);
throw error(“wrong password”);
df2.doNull();
continue;
}
else
{
ret = true;
break;
}
}
if(ret == false)
{
infolog.shutDown(true);
}
}

In the above code df2 dialog is for password which you can set it at the line num 23 i.e, hardcode your password (or) you can customize the password field in sysuserform and assign to all user. and then you can validate the password whether the entered password and password which is set for the corresponding user in your customized sysuser form is same.

Args class

$
0
0

The Args system class is one of the most widely used classes in Axapta. Args is an abbreviation for arguments and an Args object is used to pass information from one object (caller) to another newly created object.



Using Args for object creation
Args    args = new Args("CustTable");
 FormRun formRun = ClassFactory.formRunClass(args);
 ; 
 formRun.init();
 formRun.run();
 formRun.wait();

caller:

public Object caller( [Object _value] )

this method gets or sets the calling object. When creating an args object directly through code, the caller will not be automatically set, so you should set it yourself.

Record:

public Common record( [Common _value] )

this method gets or sets a table buffer (record) attached to the Args. A buffer of any table can be attached to an Args object using this method. Be aware when retrieving the buffer that there will be no compile-time check of table id. You should use the dataset method below to check the contents of the buffer.

If the caller and callee are on different tiers, then the applications will automatically copy the buffer to the target tier.

Dataset:

public tableId dataset()

this method gets the table Id of a table buffer (record) attached to the Args.
To safely retrieve an attached record from an Args object, use code similar to that shown below. This checks to ensure that there is an attached record, and that it is in fact a SalesTable record, before trying to assign it to the salesTable variable.

if (args.record() && args.dataset() == tableNum(SalesTable))
  salesTable = args.record();

parm:

public str parm( [str _value] )
parm is used to pass a string variable to the called object

parmEnum:

public anytype parmEnum( [int _value] )
see parmEnumType

parmEnumType:

public int parmEnumType( [int _value] )
parmEnum and parmEnumType are used together to pass a Base Enum value through to the called object. An example is shown below.
args.parmEnumType(EnumNum(AddressType));
args.parmEnum(AddressType::Delivery);

parmObject:

public Object parmObject( [Object _value] )
parmObject is used to pass a reference to any object to the called object. Be aware of client-server issues if the caller and callee are on different tiers.

menuItemName:

public final str menuItemName( [str _value] )

menuItemType:

public final MenuItemType menuItemType( [MenuItemType _value] )

A short tutorial on how to open a form in Dynamics Ax (Axapta) by code.

Just take a line of code:

new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run();

The above code will open the CustTable form. That's all it takes.

Now if you want to supply some arguments to the opening form, this is also possible with the optional args parameter.

static void FormOpen()
{
Args args = new Args();
;
args.record(CustTable::find('CUS-001'));
new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run(Args);
}

This code will open the CustTable form and filter out the customer with accountnumber CUS-001.

MultiSelection of records

$
0
0

void checkSelectedRecords()
{
Student inventLocal;
;
//getFirst method gets all the selected records in the grid
inventLocal = Student_ds.getFirst(true);

while (inventLocal)
{
info(strfmt("You selected Item %1",inventLocal.Studentid));
// get the next selected record
inventLocal = Student_ds.getNext();
}
}

------------------------------------------------------------------------------------------
void clicked()
{
super();
element.checkSelectedRecords();
  

}

check the buttons property multiselect :: yes or not.

RunBase framework:

$
0
0

The RunBaseBatch class extends the RunBase class and allows one to create classes (jobs) that can be added to the batch queue. Once the job has been added to the queue, it will be executed by the batch server. This concept is known as batch processing.

Whenever you write a class that typically asks a user for input and then starts a process based on that input you use the RunBase framework as most of the typical methods needed for such a Job is already implemented in the RunBase class. This means that using the RunBase framework is done by extending RunBase either by directly extending RunBase or by extending a class that extends RunBase.

For more: RunBase

Some of the features implemented in the RunBaseframework are the following:

• Run: The main flow of the operation
• Dialog: Prompting the user for input and storing that input
• Batch execution: Schedule the Job for later execution
• Query: Used to select data
• Progress bar: Shows the progress of a task
• Pack/unpack with versioning: Remember variable values until the next time
the task is executed
               
Pack and Unpack method:

This method is a standard method inherited from RunBase. It is used to save
the values that the user selects and store them until the next time the user executes
the class.

public container pack()
{
    ;
    return [#CurrentVersion,#CurrentList];// + [super()];
}

And under unpack:

public boolean unpack(container packedClass)
{
    container       _base;
    boolean         _ret;
    Integer         _version    = conpeek(packedClass,1);

    switch (_version)
    {
        case #CurrentVersion:
            [_version, #CurrentList, _base] = packedClass;
            //_ret = super(_base);
            break;

        default:
            _ret = false;
    }
    return _ret;
}

And your class declaration looks like:

class ItemCreationApprove extends runbase
{
    Dialogfield fieldapprover;
    approvedby  approver;
    #define.CurrentVersion(2)
    #localmacro.CurrentList
        approver
    #endmacro
}


Other framework in Microsoft dynamics AX:

Ø  Runbase Framework
Ø  Batch Framework
Ø  Dialog Framework
Ø  Operation Progress Framework 
Ø  NumberSequence Framework
Ø  SysLastValue Framework
Ø  AIF-Application Integration Framework
Ø  Wizard Framework
Ø  Infolog Framework
Ø  Unit Test Framework

Report structure in AX 2009 / Create report in simple steps

$
0
0

public class ReportRun extends ObjectRun
{
 dialogField Fromdatefield,todatefield;
    FromDate fromdatevalue;
    ToDate   todatevalue;
    date1980 date1;
    date1980 date2;
    ConfirmId  ConfirmIdfield;

}

------------------------------------------------------------------------

display date1980 date2()
{
return date2;
}


------------------------------------------------------------------------

display date1980 date1()
{
return date1;
}



------------------------------------------------------------------------

public boolean getFromDialog()
{
    Boolean         ret;
   // LedgerPeriod    ledgerPeriod;
 //  CustConfirmTrans CustConfirmTrans;
    ;

    fromDateValue       = fromDateField.value();
    toDateValue         = toDateField.value();

    if (fromDateValue == dateNull())
    {
        select firstonly CustConfirmTrans;
        fromDateValue = CustConfirmTrans.ConfirmDate;//.PeriodStart;
    }
    if (toDateValue == dateNull())
    {
        todateValue = systemDateGet();
    }
    if (fromDateValue > toDateValue)
    {
        ret = checkFailed('From date should not be greater than To date.');
    }
    else
    {
        ret = true;
    }

    return ret;
}
--------------------------------------------------------------------------

public Object dialog(Object d)
{

    DialogRunbase dialog = d ;
    ;

    fromDateField           = dialog.addField(typeid(FromDate),"From date");
    toDateField             = dialog.addField(typeid(ToDate),"To date");

    return dialog;
}


------------------------------------------------------------------------

public boolean fetch()
{
    boolean ret;
   
    ;
    date1 = fromdatevalue;
    date2 = todatevalue; 



while select CustConfirmTrans where     CustConfirmTrans.ConfirmDate >= fromdatevalue
&& CustConfirmTrans.ConfirmDate <= todatevalue
{
      this.send(CustConfirmTrans);
}   


 ret = true; //super();
 return ret;
}

Renumber your RecId's

$
0
0

Every record in Axapta will have one unique identifier: the RecId.

The RecId will be unique per company and the system gets the next RecId number from the table SYSTEMSEQUENCES, field "NEXTVAL".
Sometimes Axapta also does not only take one number but will take more (I remember to have read that it can be up to 24 numbers)

The field is a signed integer in the database, so it can happen that you will swap from positive RecId's to negative RecId's. The range in which recid's are allocated is between 2.147.nnn.nnn and -2.147.nnn.nnn.
If you have "holes" in your RecId, it may then be interesting to renumber all RecId's, starting with the number 1 again. You can do this by running the script "Check Record Ids" in the menu Administration/Periodic/SQL Administration.



Q: What will the script do?
Ans: It will create some new tables on the SQL database, collect all RecId numbers, assign new RecID number starting from one.
It will then check all Axapta tables if there are fields that are a reference to a RecId. If yes, the old RecId Reference will be replaced by the new one.
And here is also a very important trap: you must be sure that all your database fields that are a referenced RecID are extended from any type of RecId datatype.

Tax calculation through X++

$
0
0

Method 1:

void clicked()
{
real tax1;
;
    super();
 tax1 = Tax::calcTaxAmount(Salesline.TaxGroup, Salesline.TaxItemGroup, Systemdateget(), Salesline.CurrencyCode, Salesline.LineAmount, TaxModuleType::Sales);

info(strfmt("%1", tax1));
}

------------------------------------------------------------------------------------------------------------

Method 2:

void clicked()
{
TaxOnItem                       TaxOnItem;
TaxGroupData                    TaxGroupData, TaxGroupData_1;
real                            TaxAmount = 0, TaxAmount_1 = 0;
TaxValue                        TaxValue = 0, TaxValue_1 = 0;
;
   
    super();

    if(Salesline.TaxItemGroup && Salesline.TaxGroup && Salesline.LineAmount != 0)
    {
        while select TaxOnItem
             where TaxOnItem.TaxItemGroup == salesline.TaxItemGroup
             {
              if(TaxOnItem)
              {
             while select TaxGroupData
                  where TaxGroupData.TaxGroup == Salesline.TaxGroup
&& TaxGroupData.TaxCode  == TaxOnItem.TaxCode
                   {
                   if(TaxGroupData)
                   {
                    TaxValue  =  TaxData::find(TaxOnItem.TaxCode, Systemdateget(), 0).TaxValue;
                    TaxValue_1  += TaxValue;
                    TaxAmount = (Salesline.LineAmount * TaxValue)/100;
                    TaxAmount_1 += TaxAmount;
                   }
                   }
              }
              }
               info(strfmt("%1", TaxAmount_1));
        }
}

Formula 1 Team Races With Microsoft Dynamics

Import the record from MS Excel to AX2009 / AX2012

$
0
0


The below code will help you to import the Excel file in to your MS Dynamics AX 2009 / AX 2012.



staticvoidImportFromExcelTOAX(Args _args)
{

    #AviFiles
    SysOperationProgress        progress = newSysOperationProgress();
    SysExcelApplication         application;
    SysExcelWorkbooks           workbooks;
    SysExcelWorkbook            workbook;
    SysExcelWorksheets          worksheets;
    SysExcelWorksheet           worksheet;
    SysExcelWorkSheet           workSheetInventTableModule;
    SysExcelCells               cellsInventTableModule;
    SysExcelCells               cells;
    COMVariantType              type;
    COMVariantType              typeModule;
    int                         row;
    FileName                    fileName;
    InventTable                 inventTable;
    InventTableModule           tabmodule;
    LedgerJournalTrans_Project  proj;
    ItemId                      itemId;
    FileIoPermission            perm;
    int64                       rec;
  

    Dialog                          dialog = new dialog();
    dialogField                     dialogFilename;
   
    #define.FileMode('R')
    ;

    fileName        = "C:\\Users\\vishal\\Desktop\\Refrec1.xlsx";
    perm = new FileIOPermission(FileName, #FileMode);
    perm.assert();
    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    try
    {
        workbooks.open(Filename);
    }
    catch (Exception::Error)
    {
        throw error("File cannot be opened.");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromName('refer');
    if (worksheet)
    {
        cells = worksheet.cells();
    }
    else
    {
        throw warning('File cannot be opened.');
    }

    progress.setCaption("Migrating ...");
    progress.setAnimation(#AviTransfer);

    try
    {
        ttsbegin;

        do
        {
            row++;
            if (row > 1)
            {
                rec              = any2int64(cells.item(row, 1).value().double());

                selectfirstonlyforUpdateproj
                    where proj.RefRecId                == rec;
                if (proj)
                {
                    proj.CostPrice = any2real(cells.item(row, 2).value().double());
                    proj.update();

                    progress.setText('Processing item ' + proj.ProjId);
                }
                else
                {
                    throw warning('Rec id' + rec+ ' does not exist in the project transaction.' );
                }

                /*
                Suppose you want to insert the record from excel to inventory table in AX.
                then just declare the buffer in class declaration as : itemtable itemtab;
                And then you can write the below code from line 69 to 83.
               
                Code:
               
                select firstonly itemtab
                                    where itemtab.ItemId == any2str(cells.item(row, 1).value().bStr());
                                if (!itemtab)
                                {
                                    itemtab.itemid = any2str(cells.item(row, 1).value().bStr());
                                    itemtab.name = any2str(cells.item(row, 2).value().bStr());
                                    itemtab.insert();

                */
            }
            type = cells.item(row+1, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);
        ttscommit;

    }


    catch (Exception::Error)
    {
        workbooks.close();
        CodeAccessPermission::revertAssert();
        application.quit();
        ttsabort;
    }


    workbooks.close();
    CodeAccessPermission::revertAssert();
    application.quit();

    //element.close();

}







Some Important date functions in AX

$
0
0

Dayname: Retrieves the name of the day of the week specified by a number.
wkofyr : Calculates the week of the year in which a date falls

mthofyr: Retrieves the number of the month in the year for the specified date.

mthname : Retrieves the name of the specified month

mkdate : Creates a date based on three integers, which indicate the day, month, and year, respectively.

dayofmth: Retrieves the day of the specified date.

dayofyr: Retrieves the day of the specified date.

year: Get year from date

dayofwk: Calculates the day of the week for a date.

prevmth:  Retrieves the date in the previous month that corresponds most closely to the specified date.

prevyr: Retrieves the date in the previous year that corresponds most closely to the specified date.

prevqtr: Retrieves the date in the previous quarter that corresponds most closely to the specified date.

Today: Retrieves the current date on the system.


To find stock On-Hand in AX through X++

$
0
0

static void findOnHand(Args _args)
{
 
InventDim inventDim;
InventDimParm inventDimParm;
Itemid itemid;
InventOnHand inventOnHand = new InventOnHand();
;

// take a sample item for testing
itemid = "Item1";

// take a combination of dimension , against which you want to find the stock
inventDim.InventLocationId = "HYD";

//Set the flag for the selected dimensions as active.
inventDimParm.initFromInventDim(inventDim);

//initialize the inventonhand with item,dimension and dim paramter

inventOnHand.parmItemId(itemid);
inventOnHand.parmInventDim(inventDim);
inventOnHand.parmInventDimParm(inventDimParm);

// Retrieve the onhand info
info(strfmt("Available Physical: %1",
inventOnhand.availPhysical()));
info(strfmt("On order: %1",inventOnhand.onOrder()));

}



To find out stock in inventsum using code X++:

static void ItemOnhandSum(Args _args)
{
    InventSum           inventsum;
    Qty                 availableQty = 0;
    ;

    select sum(PostedQty),
        sum(Received),
        sum(Deducted),
        sum(Registered),
        sum(Picked),
        sum(ReservPhysical),
        sum(Ordered),
        sum(Arrived),
        sum(ReservOrdered),
        sum(OnOrder) from inventsum
        where inventsum.ItemId      == "KCYIWU001";
    if (inventsum)
    {
        availableQty = inventsum.PostedQty
            + inventsum.Received
            - inventsum.Deducted
            + inventsum.Registered
            - inventSum.Picked
            - inventSum.ReservPhysical
            + inventsum.Ordered
            + inventsum.Arrived
            - inventsum.ReservOrdered
            - inventsum.OnOrder;
    }
    info(strfmt('%1', availableQty));
}



To find on- hand Stock by date :

static void findOnHand_ByDate(Args _args)
{
InventDim inventDim;
InventDimParm inventDimParm;
Itemid itemid;
InventOnHand inventOnHand = new InventOnHand();
InventSumDateDim inventSumDateDim;
TransDate transDate;
;

// take a sample item for testing
itemid = "20 MM RMC";
transDate = 13\01\2010;

// take a combination of dimension , against which you want to find the stock
inventDim.InventLocationId = "GW";

//Set the flag for the selected dimensions as active.
inventDimParm.initFromInventDim(inventDim);

//initialize the inventSumDateDim with Date,item,dimension and dim paramter

inventSumDateDim = InventSumDateDim::newParameters(transDate,
itemid,
inventDim,
inventDimParm);


// Retrieve the onhand info
info(strfmt("PostedQty: %1",inventSumDateDim.postedQty()));
info(strfmt("DeductedQty: %1",inventSumDateDim.deductedQty()));
info(strfmt("ReceivedQty: %1",inventSumDateDim.receivedQty()));

}


Use of container in display method in AX

$
0
0
Hi friends, Today am going to discuss about the use of container in display method in MS dynamics AX.
There may be requirement when we need to display certain things from multiple lines in to a single field with comma separated, and it is just for viewing purpose(Sometime informative).

Let us take a quick example wherein I can show you this functionality working and code behind it!! J

Ex:
In sales header you want to capture all the lines warehouses in a single field which should be separated in comma.
Am going to add display method, Just add the below code in Table > SalesTable

Display Name Warehouse()
{
    salesline salesline;
    Container warehouse;
    int i=0;
    str strwarehouse;
    ;
    strwarehouse='';
    while select salesline where salesline.SalesId==this.SalesId
    {
        if(confind(warehouse,InventDim::find(salesline.InventDimId).InventLocationId)==0)
            warehouse +=InventDim::find(salesline.InventDimId).InventLocationId;
    }
     for (i = 1 ; i <= conLen(warehouse) ; i++)
     {
        if(strwarehouse=='')
        strwarehouse=conPeek(warehouse,i);
        else
        strwarehouse=strwarehouse+', '+conPeek(warehouse,i);

     }
    return strwarehouse;
}

And then drag this particular method in SalesTable form.


And once this display method is added in to the grid, we will be able to view our scenario.
Here it is:


So, the field ‘warehouse’ in header part of sales order represents the cumulative warehouse of lines.

Keep reading J








Lookup (or) Drop-down for field in Dynamic AX using query

$
0
0

void lookupField(FormControl  control)
{
    Query                   query = new Query();
    QueryBuildDataSource    queryBuildDataSource;
    QueryBuildRange         queryBuildRange;
    SysTableLookup          sysTableLookup;
    ;

    //Create an instance of SysTableLookup with the form control passed in
    sysTableLookup = SysTableLookup::newParameters(tablenum(<table name>), control);

    //Add the fields to be shown in the lookup form
    sysTableLookup.addLookupfield(fieldnum(<table name>, <field name>), true);
    sysTableLookup.addLookupfield(fieldnum(<table name>, <field name>), false);

    //create the query datasource
    queryBuildDataSource = query.addDataSource(tablenum(<table name>));
    queryBuildRange = queryBuildDataSource.addRange(fieldnum(<table name>, <field name>));
    queryBuildRange.value(enum2str(NoYes::Yes)); //Example of Enum value or you can specify any range

    //add the query to the lookup form
    sysTableLookup.parmQuery(query);

    // Perform lookup
    sysTableLookup.performFormLookup();
}

Lookup using temporary table:

Writing the lookup under form > datasource > field  > method:
public void lookup(FormControl _formControl, str _filterStr)
{
    Query                       query          = new Query();
    QueryBuildDataSource        qds1;
    QueryBuildDataSource        qds2;
    QueryBuildRange             qr1;
    QueryBuildRange             qr2;
    QueryBuildRange             qr3;
    SysTableLookup              sysTableLookup;
    VendInvoiceJour             VendInvoiceJour;
    WHT_WithholdingTaxTrans     WHT_WithholdingTaxTrans;
    WHT_KRALookuptable          WHT_KRALookuptable; // Temporary table
    QueryRun                    qr;
    ;

    delete_from WHT_KRALookuptable;
    qds1 = query.addDataSource(tableNum(VendInvoiceJour));
    qds2 = qds1.addDataSource(tableNum(WHT_WithholdingTaxTrans));
    qds2.joinMode(JoinMode::InnerJoin);
    qds2.addLink(fieldNum(WHT_WithholdingTaxTrans,Invoice), fieldNum(VendInvoiceJour,InvoiceId));
    qds2.addLink(fieldNum(WHT_WithholdingTaxTrans,InvoiceAccount), fieldNum(VendInvoiceJour,InvoiceAccount));
    qr1 = qds1.addRange(fieldNum(VendInvoiceJour, InvoiceAccount));
    qr1.value(WHT_KRAreceiptUpdate.AccountNum);
    qr2 = qds2.addRange(fieldNum(WHT_WithholdingTaxTrans, WHT_KRAStatus));
    qr2.value(int2str(WHT_KRAStatus::Paid));
    qr3 = qds2.addRange(fieldNum(WHT_WithholdingTaxTrans,WHT_DTA));
    qr3.value(int2str(NoYes::No));
    qr = new QueryRun(query);
    while (qr.next())
    {
        VendInvoiceJour = qr.get(tablenum(VendInvoiceJour));
        select WHT_KRALookuptable
            where WHT_KRALookuptable.InvoiceId == VendInvoiceJour.InvoiceId
            && WHT_KRALookuptable.InvoiceAmount == VendInvoiceJour.InvoiceAmount;
        if (!WHT_KRALookuptable)
        {
            select sum(WithholdingTaxAmount) from  WHT_WithholdingTaxTrans
                group by InvoiceAccount,Invoice
                where WHT_WithholdingTaxTrans.InvoiceAccount == VendInvoiceJour.InvoiceAccount
                && WHT_WithholdingTaxTrans.Invoice == VendInvoiceJour.InvoiceId;
            if (WHT_WithholdingTaxTrans)
            {
                WHT_KRALookuptable.WithholdingTaxAmount = WHT_WithholdingTaxTrans.WithholdingTaxAmount;
            }
            WHT_KRALookuptable.InvoiceId = VendInvoiceJour.InvoiceId;
            WHT_KRALookuptable.InvoiceAmount = VendInvoiceJour.InvoiceAmount;
            WHT_KRALookuptable.AccountNum = VendInvoiceJour.InvoiceAccount;
            WHT_KRALookuptable.insert();
        }
    }
    sysTableLookup = SysTableLookup::newParameters(tableNum(WHT_KRALookuptable),_formControl);
    sysTableLookup.addLookupField(fieldNum(WHT_KRALookuptable, InvoiceId));
    sysTableLookup.addLookupField(fieldNum(WHT_KRALookuptable, InvoiceAmount));
    sysTableLookup.addLookupField(fieldNum(WHT_KRALookuptable, WithholdingTaxAmount));

    //sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();
}

X++ Code to Export AOT Object / automatic backup of XPO's.

$
0
0

Hi friends, hope all is well!! J

Today am here to convey the most vital subject for MS dynamics AX.

Development or customization's are the most important topic which should be saved or backup need to be taken on daily or weekly basis.

We need to take daily backup of our development (in terms of XPO), but we all always forget because of our hectic work schedules.

So use the following job and build batch application to take backup of development in terms of XPO.
We can take AOD file also but the size will be more and needs to stop AOS every time.

Following job illustrates how to export/backup all AOT Classes object.

void ExportTreeNodeExample()
{
    TreeNode            treeNode;
    FileIoPermission    perm;

    #define.ExportFile(@"D:\AOTclasses.xpo")
    #define.ExportMode("w")
    ;

    perm = new FileIoPermission(#ExportFile, #ExportMode);
    if (perm == null)
    {
    return;
    }
    perm.assert();

    treeNode = TreeNode::findNode(@"\Classes");
    if (treeNode != null)
    {

    // BP deviation documented.
    treeNode.treeNodeExport(#ExportFile);
    }

    CodeAccessPermission::revertAssert();

}

Keep reading!! J

Get exchange rate from web in to MS AX

$
0
0

static void GetExchangeRates(Args _args)
{
    com com = new com('microsoft.xmlhttp');
    com com1;
    XMLDocument xmlDoc;
    Dialog exchDialog = new Dialog("Exchange Rates");
    DialogField   fromField;
    DialogField   ToField;
    str                 url;
    ;

    fromField = exchDialog.addField(typeid(currencycode), 'Base Currency');

    fromField.value(CompanyInfo::find().CurrencyCode);

    ToField =  exchDialog.addField(typeid(currencycode), 'To Currency');

    if(exchDialog.run())
    {
        url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?";
        url += "FromCurrency=" +strupr(fromField.value())+"&ToCurrency="+strupr(ToField.value());
        com.open("get",url, false);
        com.send();
        com1 = com.responsexml();
        xmlDoc = XmlDocument::newXml(com1.xml());

        info("1"+fromField.value() + " = " +xmlDoc.getNamedElement('double').text() + " " +ToField.value());
    }
 }

Force Synchronisation of AOT tables through X++ in AX:

$
0
0

static void forceDbSynchronize1(Args _args)
{
Dictionary dict;
int idx, lastIdx, totalTables;
TableId tableId;
Application application;
SysOperationProgress progress;
StackBase errorStack;
ErrorTxt errorTxt;
;
application = new Application();
dict = new Dictionary();
totalTables = dict.tableCnt();
progress = new SysOperationProgress();
progress.setTotal(totalTables);
progress.setCaption(“@SYS90206″);
errorStack = new StackBase(Types::String);
lastIdx = 0;
try
{
for (idx = lastIdx+1; idx <= totalTables; idx++)
{
tableId = dict.tableCnt2Id(idx);
progress.setText(dict.tableName(tableId));
lastIdx = idx;
application.dbSynchronize(tableId, false, true, false);
progress.incCount();
}
}
catch (Exception::Error)
{
errorTxt = strFmt("Error in table '%1' (%2)", tableId, dict.tableName(tableId));
errorStack.push(errorTxt);
retry;
}
setPrefix("@SYS86407");
errorTxt = errorStack.pop();
while (errorTxt)
{
error(errorTxt);
errorTxt = errorStack.pop();
}
}

Ledger postings in MS Dynamics AX 2009

$
0
0

PS stands for packing slip
PSO stands for packing slip offset

Ledger postings for sales order:

1.packing slip:                                                                                      Credit             Debit                       
 Inventory clearing … shipped, Un invoiced (PS)…………. Cr
Account Receivable clearing (PSO)………………………………………….……….Dr
2.Sales Invoice:
Inventory clearing … shipped, Un invoiced (PS)……………………………….Dr
Account Receivable clearing (PSO)………………………………..Cr
Sales order (inventory) Issue………………………………….……..Cr
Sales order (Inventory) consumption……….........................................Dr
Customer balance………………………………………………..............................Dr
Revenue………………………………………………………………........Cr              
3.payment:        
Bank or cash…………………………………………………………………….................Dr
Customer Balance…………………………………………………….....Cr

Ledger postings for purchase order:

1. Packing slip:
Inventory clearing…Received (PS)……………………………………………………Dr    
Accounts Payable clearing (PSO)……………………………………Cr
2.Purchase Invoice:
Inventory clearing…Received (PS)…………………………………Cr
Accounts Payable clearing…………………………………………………………….Dr
Purchase Receipt…………………………………………………………………………….Dr
Vendor Balance…………………………………………………………….Cr
3.payment:        
Vendor Balance……………………………………………………………………………….Dr
Bank or cash………………………………………………………………….Cr

Viewing all 126 articles
Browse latest View live