Friday, February 28, 2014

send Automatic appointment to Mail id by using outlook through X++

// Steps to send Automatic appointment to Mail id by using outlook through X++

static void OutlookAppointment(Args _args)
 {
   COM    sysOutlookCollection;
   COM    receipiants;
   COM    collection;
   COMVariant comStartDate = new COMVariant();
   COMVariant comEndDate  = new
   COMVariant();
   COM    c;
   #SysOutLookCOMDEF
   #define.mapi("MAPI")
   #define.outlook("Outlook.Application")
   COM    sysOutlook;
   COM    sysOutlookNameSpace;
   COM    sysOutlookMAPIFolder;
   sysOutlook         = new COM(#outlook);
   sysOutlookNameSpace     = sysOutlook.getNamespace(#mapi);
   sysOutlookNameSpace.logon();  
   sysOutlookMAPIFolder    = sysOutlookNameSpace.getDefaultFolder(#OlDefaultFolders_olFolderTasks);
   collection         = sysOutlookMAPIFolder.items();
   c = collection.add();
   comStartDate.date(today());
   comStartDate.time(str2Time( "10:40:00"));
   comEndDate.date(today());
   comEndDate.time(str2Time( "10:45:00"));
   c.subject("Meeting regd Microsoft Dynamics AX 2012");
   c.body("Lets discuss on whats new in DAX 2012");
   c.save();
   if (c)
   {
     receipiants = c.Recipients();
     receipiants.add(" Desired mail Id");
     receipiants.ResolveAll();
     c.assign();
     //c.display();
     c.send();
     info("The action is created in Microsoft Outlook");
   }
   else
   throw error("@SYS31969");
   sysOutlookNameSpace.logoff();
 }

To get a User Id in AX client workspace Display..

//To get a User Id in AX client workspace Display..

class->info->method->workspaceWindowcreated
info Class: http://msdn.microsoft.com/en-us/library/xinfo.aspx


static void printCurrentUserId()


{
        //info(curUserId());
        //info(curext());

    SecurityRole        role;
     SecurityUserRole    userRole;
     UserInfo            userInfo,userInfoName;

     ;


    select firstonly  role
    exists join userRole
    where role.RecId     == userRole.SecurityRole
          && userRole.User == curUserId();
    select userInfoName where userInfoName.id == curUserId();

    info(strFmt("System Role :%1 \n UserID :  %2 \n userName: %3 \n UserCompany: %4", role.Name,curUserId(),userInfoName.name,curext()));

}

void workspaceWindowCreated(int _hWnd)
{

     UserInfo userInfoName;
        ;
    super(_hWnd);

    // Put workspace window specific initialization here.

    select userInfoName where userInfoName.id == curUserId();
     WinAPI::setWindowText(_hWnd,strFmt("%1-%2", userInfoName.name, WinAPI::getWindowText(_hWnd)));
}


// To get a Current User id and current working company in X++

info(curuserid());
info(curext());


// In order find out the employee linked to the current user..

In AX 2009:
EmplTable::find(SysCompanyUserInfo::find(curUserId()).EmplId);

In AX 2012:
HcmWorker::find(DirPersonuser::findUserWorkerReference(curUserId())).name();

To get a User Id in AX client workspace Display..

//To get a User Id in AX client workspace Display..

class->info->method->workspaceWindowcreated
info Class: http://msdn.microsoft.com/en-us/library/xinfo.aspx


static void printCurrentUserId()


{
        //info(curUserId());
        //info(curext());

    SecurityRole        role;
     SecurityUserRole    userRole;
     UserInfo            userInfo,userInfoName;

     ;


    select firstonly  role
    exists join userRole
    where role.RecId     == userRole.SecurityRole
          && userRole.User == curUserId();
    select userInfoName where userInfoName.id == curUserId();

    info(strFmt("System Role :%1 \n UserID :  %2 \n userName: %3 \n UserCompany: %4", role.Name,curUserId(),userInfoName.name,curext()));

}

void workspaceWindowCreated(int _hWnd)
{

     UserInfo userInfoName;
        ;
    super(_hWnd);

    // Put workspace window specific initialization here.

    select userInfoName where userInfoName.id == curUserId();
     WinAPI::setWindowText(_hWnd,strFmt("%1-%2", userInfoName.name, WinAPI::getWindowText(_hWnd)));
}


// To get a Current User id and current working company in X++

info(curuserid());
info(curext());


// In order find out the employee linked to the current user..

In AX 2009:
EmplTable::find(SysCompanyUserInfo::find(curUserId()).EmplId);

In AX 2012:
HcmWorker::find(DirPersonuser::findUserWorkerReference(curUserId())).name();

Display data in Title bar of Form and Code to get all object of project node


// Display data in Title bar of Form

http://daynamicsaxaptatutorials.blogspot.in/search/label/title%20bar%20info

//Code to get all object of project node

http://daynamicsaxaptatutorials.blogspot.in/2011/06/code-to-get-all-object-of-project-node.html

Create and Post a BOM journal through X++

// Steps to create and Post a BOM journal through X++

void clicked()
{

        InventJournalTable          journalTable ;
        InventJournalTrans          journalTrans;
        InventJournalTableData      journalTableData;
        InventJournalTransData      journalTransData;
        InventJournalNameId         inventJournalName;
        InventTransId               num;
        InventJournalVoucherId      numV;
        ComboBOMHeader              Header;
        Filename                    filename;
        NumberSeq                   numberSeq,numberSeq1;
        ComboBOMLine                line;
        InventDim                   inventDim;
        Dialog                      dialog;
        DialogField                 dlgfeild;
        str a;
        InventJournalCheckPost      journalCheckPost;// = new InventJournalCheckPost();
         int   L = 10;

        ;
       
        journalTableData = JournalTableData::newTable(journalTable);
        journalTransData = journalTableData.journalStatic().newJournalTransData(journalTrans,journalTableData);
//
        journalTable.clear();
        journalTable.JournalId = journalTableData.nextJournalId();
        journalTable.JournalNameId =  InventParameters::find().BOMJournalNameId;
        journalTable.JournalType = InventJournalType::BOM;
        journalTableData.initFromJournalName(journalTableData.journalStatic().findJournalName(journalTable.JournalNameId));
        journalTable.insert();
   
        journalTrans.clear();
        journalTrans.JournalId      = journalTable.JournalId;
        journalTrans.JournalType    = InventJournalType::BOM;
       
       
       
        numberSeq1 = NumberSeq::newGetNum(InventParameters::numRefInventJournalVoucherId());
        numV = numberSeq1.num();
   
     
        journalTrans.Voucher = numV;
        journalTransData.initFromJournalTable();

        dialog = new Dialog();
        dlgfeild = dialog.addField(extendedTypeStr(BOMId));

        dialog.run();
        filename = dlgfeild.value();

         select line where line.bomid == filename;
            {
                journalTrans.LineNum = L;
                journalTrans.TransDate      = systemdateget();
               
                numberSeq = NumberSeq::newGetNum(Inventparameters::numRefInventTransId());
                num = numberSeq.num();
                journalTrans.InventTransId = num;
                journalTrans.InventTransIdFather = '00162615_068';
                journalTrans.ItemId =line.ItemId;
                journalTrans.CostAmount = line.CostPrice;
                // Dimension details
                inventDim.configId = 'HD';
                inventDim.InventSizeId ='42';
                inventDim.InventColorId ='01';
                inventDim.InventSiteId ='1';
                inventDim.InventLocationId = '11';
                inventDim.inventBatchId = '1001';
                //inventDim.wMSLocationId = '11';
               
                journalTrans.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;

                journalTrans.BOMLine = true;
                //journalTransData.create();
                    journalTrans.insert();
                    //L += 10;

            }
       

        // Call the static method to post the journal
        if(InventJournalCheckPost::newPostJournal(journalTable).validate())
        InventJournalCheckPost::newPostJournal(journalTable).run();
}

// for Multiple lines
error

void clicked()
{

        InventJournalTable          journalTable ;
        InventJournalTrans          journalTrans,inventJournalTransAssembly;
        InventTransOrigin           inventTransOrigin;
        InventJournalTableData      journalTableData;
        InventJournalTransData      journalTransData;
        InventJournalNameId         inventJournalName;
   
        InventTransId               inventtransid;
        InventTransId               num;
        InventJournalVoucherId      numV;
        ComboBOMHeader              Header;
        Filename                    filename;
        NumberSeq                   numberSeq,numberSeq1;
        ComboBOMLine                line;
       
        InventDim                   inventDim;
        Dialog                      dialog;
        DialogField                 dlgfeild;
        str a;
        InventJournalCheckPost      journalCheckPost;// = new InventJournalCheckPost();
        int   L = 10;
        ;
       
        journalTableData = JournalTableData::newTable(journalTable);
        journalTransData = journalTableData.journalStatic().newJournalTransData(journalTrans,journalTableData);
//
        journalTable.clear();
        journalTable.JournalId = journalTableData.nextJournalId();
        journalTable.JournalNameId =  InventParameters::find().BOMJournalNameId;
        journalTable.JournalType = InventJournalType::BOM;
        journalTableData.initFromJournalName(journalTableData.journalStatic().findJournalName(journalTable.JournalNameId));
        journalTable.insert();
   
        journalTrans.clear();
        journalTrans.JournalId      = journalTable.JournalId;
        journalTrans.JournalType    = InventJournalType::BOM;
       
       
       
        numberSeq1 = NumberSeq::newGetNum(InventParameters::numRefInventJournalVoucherId());
        numV = numberSeq1.num();
   
     
        journalTrans.Voucher = numV;
        journalTransData.initFromJournalTable();

        dialog = new Dialog();
        dlgfeild = dialog.addField(extendedTypeStr(BOMId));

        dialog.run();
        filename = dlgfeild.value();

        while select line where line.bomid == filename
            {
                journalTrans.LineNum = L;
                journalTrans.TransDate      = systemdateget();
               
                numberSeq = NumberSeq::newGetNum(Inventparameters::numRefInventTransId());
                num = numberSeq.num();
               
                //journalTrans.InventTransId = num;          
                journalTrans.ItemId =line.ItemId;
               
                    if( L <= 10)
                    {
                   
                        journalTrans.InventTransId = num;
                        journalTrans.BOMLine = false;
                        journalTrans.Qty    = line.qty;
                    }      
                    if(L > 11)
                    {
                        journalTrans.BOMLine = true;
                        inventJournalTransAssembly = InventJournalTrans::findInventTransId(num);
                        //select InventTransId from journalTrans where journalTrans.InventTransId == inventTransOrigin.InventTransId
                                                                     //&& inventTransOrigin.InventTransId == num;
                        //
                        //journalTrans.InventTransIdFather = num;
                        journalTrans.Qty    = -(line.qty);
                        //info(strFmt("%1",journalTrans.Qty));
                    }
                    journalTrans.CostAmount = line.CostPrice;
                    // Dimension details
                    inventDim.configId = '';
                    inventDim.InventSizeId ='02';
                    inventDim.InventColorId ='';
                    inventDim.InventSiteId ='1';
                    inventDim.InventLocationId = '11';
                    inventDim.inventBatchId = '1001';
                    //inventDim.wMSLocationId = '11';
               
                    journalTrans.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;

                    //journalTrans.BOMLine = true;
                    //journalTransData.create();
                    journalTrans.insert();
                    L += 10;

            }
       
        // Call the static method to post the journal
        if(InventJournalCheckPost::newPostJournal(journalTable).validate())
        InventJournalCheckPost::newPostJournal(journalTable).run();
}

       

TO get a current User Id and User Role assignment through X++

// TO get a current User Id and User Role  and WorkerIdassignment through X++ in ax 2012



static void HCMWorkerIDFromUSerID(Args _args)
{
    UserInfo    userInfo;
    SecurityUserRole securityUserRole;
    SecurityRole       Roles;
    HcmWorkerRecId workerRecId ;
    str workerDesgn,workername;
    Label label = new Label();
   
    info(curUserId());              // Current User id
    workerRecId = DirPersonUser::currentWorker();
    info(strFmt("%1",workerRecId)); // HCM.Person   // worker id

    while select userInfo where userInfo.Id == curUserId()
            join securityUserRole where securityUserRole.User == userInfo.Id
                   join Roles where Roles.RecId  == securityUserRole.SecurityRole
    {
        workerDesgn = Roles.Name;      
        info(strFmt("%1",workerDesgn));
        workername = label.extractString(Roles.Name);
        info(strFmt("%1",workername));// Current WOrker Name
    }
}

Open a Development Workspace directly from X++ code.

//Open a Development Workspace directly from X++ code. For example, you can add a customized button in the Application Workspace to open a Development Workspace. The following X++ code can be used to open a Development Workspace.
X++

static void OpenDevWorkspace(Args _args)
{     int hWorkspace;     hWorkspace = infolog.createDevelopmentWorkspaceWindow();
}

Report SSRS DP,COntract,Controller class

//DP class

[
    SRSReportParameterAttribute(classstr(PurchContractClass))
]
public class PurchDPClass extends SRSReportDataProviderBase
{
    PurchTmp    purchTmp;
}


Method :

[SRSReportDataSetAttribute('PurchTmp')]
public purchTmp getpurchTmp()
{
    select * from purchTmp;
    return purchTmp;
}

Method  1:
[SysEntryPointAttribute(false)]
public void processReport()
{
    PurchTable  purchTable;
    PurchLine   purchLine;
    PurchContractClass purchContractClass;
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;

    purchContractClass = this.parmDataContract() as PurchContractClass;
    purchId = purchContractClass.parmPurchId();
    //purchStatus = purchContractClass.parmPurchStatus();
    //inclTax = purchContractClass.parmInclTax();

     while select purchTable where purchTable.PurchId == purchId
    {
        purchTmp.PurchId = purchTable.PurchId;
        purchTmp.InvoiceAccount = purchTable.InvoiceAccount;
        purchTmp.PurchName = purchTable.PurchName;
        purchTmp.InclTax = purchTable.InclTax;
        purchTmp.PaymMode = purchTable.PaymMode;
        purchTmp.PurchStatus = purchTable.PurchStatus;
        purchTmp.CurrencyCode = purchTable.CurrencyCode;
       
        select purchId from purchLine where purchLine.PurchId == purchTable.PurchId;
       
        purchTmp.itemid = purchLine.ItemId;
        purchTmp.VendGroup = purchLine.VendGroup;
        purchTmp.LineNumber = purchLine.LineNumber;
        purchTmp.PurchQty = purchLine.PurchQty;
       
        purchTmp.insert();
    }
}

//Contract Class:

[DataContractAttribute]
public class PurchContractClass
{
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;
}

Method 1:
[DataMemberAttribute("PurchId")]
public PurchId parmPurchId(PurchId _purchId = purchId)
{
    purchId = _purchId;
    return purchId;
}

Method 2:
[DataMemberAttribute("InclTax")]
public InclTax parmInclTax(InclTax _inclTax = inclTax)
{
    inclTax = _inclTax;
    return inclTax;
}

Method 3:

[DataMemberAttribute("PurchStatus")]
public PurchStatus parmPurchStatus(PurchStatus _purchStatus = purchStatus)
{
    purchStatus = _purchStatus;
    return purchStatus;
}


// Controller Class

class PurchControllerClass extends SrsReportRunController
{
     RecordSortedList       journalList;


     PurchView      purchview;
     //CWBProjInvoiceContract CWBProjInvoicecontract;
}

protected void initArgs(Args _args)
{
    args = new Args();

     if (_args.object() &&
        _args.object() is RecordSortedList)
    {
        journalList = _args.object();
    }
    else if (_args.record())
    {
        journalList = new RecordSortedList(tableNum(PurchView));
        journalList.ins(_args.record());
    }

    journalList.first(purchview);

    this.parmReportName("PurchReport.PurchReportDesign");
    this.parmShowDialog(false);

    this.parmArgs(_args);
}

protected void preRunModifyContract()
{
    PurchContractClass contract;
    contract = this.parmReportContract().parmRdpContract() as PurchContractClass;

    contract.parmPurchId(purchview.PurchId);
    contract.parmVendAccount(purchview.InvoiceAccount);
    ////contract.parmPurchStatus(purchview.PurchStatus);
    //contract.parm(purchview.PurchId);
}

public static void main(Args _args)
{
   PurchControllerClass controller = new PurchControllerClass();
    ;


   controller.parmReportName("PurchReport.PurchReportDesign");
   //controller.parmArgs(_args);
    controller.initArgs(_argsssssss);

    controller.startOperation();
}

Saturday, February 15, 2014

Import Customer from XLs fiile through X++ code

// Import Customer from XLs fiile through X++ code


error

public void customer()
{
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;
 FileName                    filename;
    //DialogField                 dialogFileName;
    //int row;
    ImportCSV    Importquality;
    ImportNewCustomer       customer;
    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filename
    #endmacro

    DirPartyTable               dirPartyTable;
    CustTable                   custTable,cust;
    LogisticsPostalAddress      logisticsPostalAddress;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    Name                            name;

    str AccountNo,Address,CurrencyC,custGrp,Location,PaymTerm,Paymode,city,StreetNo,country,zip,LocationName;
    str phone;

        //int row =2;
    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 "";
    }

DialogRunbase       dialog = super();
    DialogField          dialogFileName;
     #Excel


    dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
    dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS100852","*.csv"]);
    dialog.filenameLookupTitle("Upload from EXCEL/CSV");
    dialogFilename.value(filename);
    filename                = dialogFilename.value();


    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    //specify the file path that you want to read

    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 3 is the worksheet Number
    cells = worksheet.cells();
    //row =1;
     ttsBegin;
    custTable.initValue();
    do
    {
        row++;
                AccountNo   =  COMVariant2Str(cells.item(row,1).value());
                custGrp     =  COMVariant2Str(cells.item(row,2).value());
                CurrencyC   =  COMVariant2Str(cells.item(row,3).value());
                PaymTerm    =  COMVariant2Str(cells.item(row,4).value());
                Paymode     =  COMVariant2Str(cells.item(row,5).value());
                Address     =  COMVariant2Str(cells.item(row,6).value());
                city        =  COMVariant2Str(cells.item(row,7).value());
                StreetNo       =  COMVariant2Str(cells.item(row,8).value());
                country     =  COMVariant2Str(cells.item(row,9).value());
                zip         =  COMVariant2Str(cells.item(row,10).value());
                Phone       =  COMVariant2Str(cells.item(row,11).value());
                LocationName=  COMVariant2Str(cells.item(row,12).value());
                Location   = COMVariant2Str(cells.item(row,13).value());
                name        = COMVariant2Str(cells.item(row,14).value());

                custTable.AccountNum    = AccountNo;
                custTable.CustGroup     = custGrp;
                custTable.Currency      = CurrencyC;
                custTable.PaymTermId    = PaymTerm;
                custTable.PaymMode      = Paymode;
                dirPartyTable.Name      = name;


                custTable.insert(DirPartyType::Person,dirPartyTable.Name);

                /* Creates a new instance of the DirParty class from an address book entity
                   that is represented by the custTable parameter. */

                dirParty = DirParty::constructFromCommon(custTable);

                dirPartyPostalAddressView.LocationName     = Location;
                dirPartyPostalAddressView.City              = city;
                dirPartyPostalAddressView.Street            = Address;
                dirPartyPostalAddressView.StreetNumber      = StreetNo;
                dirPartyPostalAddressView.CountryRegionId   = country;

                dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

                dirPartyContactInfo.LocationName    = LocationName;
                dirPartyContactInfo.Locator         = (Phone);
                dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
                dirPartyContactInfo.IsPrimary       = NoYes::Yes;


                dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

                type = cells.item(row+1, 1).value().variantType();
         ttsCommit;
    }
     while (type != COMVariantType::VT_EMPTY);
                application.quit();

}

Import Xls file via Code Class: X++

// Import Xls file via Code Class:


class ImportNewCustomer extends RunBaseBatch
{

    FileName                    filename;

    DialogField                 dialogFileName;
    int row;
     ImportCSV    Importquality;
    ImportNewCustomer       customer;

     #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filename
    #endmacro
}


static void main(Args _args)
{

   ImportNewCustomer     customer = new ImportNewCustomer();
        if (customer.prompt())
    {
        customer.run();
    }
}

public boolean unpack(container _packedClass)
{
    Integer     version     = conpeek(_packedClass,1);
    ;
    switch (version)
    {
    case #CurrentVersion:
    [version,#CurrentList]      = _packedClass;
    break;

    default :

    return false;
    }
    return true;
}


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

public void run()
{
     this.customer();
    super();
}

public void new()
{
    super();
    row =1;
}

public boolean getFromDialog()
{
    filename                = dialogFilename.value();
    return true;
}

public Object dialog()
{
   DialogRunbase       dialog = super();
    //DialogField          dialogFileName;
     #Excel


    dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
    dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS100852","*.csv"]);
    dialog.filenameLookupTitle("Upload from EXCEL/CSV");
    dialogFilename.value(filename);


    return dialog;
}

public void customer()
{
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;

    DirPartyTable               dirPartyTable;
    CustTable                   custTable,cust;
    LogisticsPostalAddress      logisticsPostalAddress;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    Name                            name;

    str AccountNo,Address,CurrencyC,custGrp,Location,PaymTerm,Paymode,city,StreetNo,country,zip,LocationName;
    str phone;


    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 "";
    }




    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    //specify the file path that you want to read

    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 3 is the worksheet Number
    cells = worksheet.cells();
    //row =1;
     ttsBegin;
    custTable.initValue();
    do
    {
        row++;
                AccountNo   =  COMVariant2Str(cells.item(row,1).value());
                custGrp     =  COMVariant2Str(cells.item(row,2).value());
                CurrencyC   =  COMVariant2Str(cells.item(row,3).value());
                PaymTerm    =  COMVariant2Str(cells.item(row,4).value());
                Paymode     =  COMVariant2Str(cells.item(row,5).value());
                Address     =  COMVariant2Str(cells.item(row,6).value());
                city        =  COMVariant2Str(cells.item(row,7).value());
                StreetNo       =  COMVariant2Str(cells.item(row,8).value());
                country     =  COMVariant2Str(cells.item(row,9).value());
                zip         =  COMVariant2Str(cells.item(row,10).value());
                Phone       =  COMVariant2Str(cells.item(row,11).value());
                LocationName=  COMVariant2Str(cells.item(row,12).value());
                Location   = COMVariant2Str(cells.item(row,13).value());
                name        = COMVariant2Str(cells.item(row,14).value());

                custTable.AccountNum    = AccountNo;
                custTable.CustGroup     = custGrp;
                custTable.Currency      = CurrencyC;
                custTable.PaymTermId    = PaymTerm;
                custTable.PaymMode      = Paymode;
             
                custTable.insert(DirPartyType::Organization,name);

                /* Creates a new instance of the DirParty class from an address book entity
                   that is represented by the custTable parameter. */

                dirParty = DirParty::constructFromCommon(custTable);

                dirPartyPostalAddressView.LocationName     = Location;
                dirPartyPostalAddressView.City              = city;
                dirPartyPostalAddressView.Street            = Address;
                dirPartyPostalAddressView.StreetNumber      = StreetNo;
                dirPartyPostalAddressView.CountryRegionId   = country;

                dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

                dirPartyContactInfo.LocationName    = LocationName;
                dirPartyContactInfo.Locator         = (Phone);
                dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
                dirPartyContactInfo.IsPrimary       = NoYes::Yes;


                dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

                type = cells.item(row+1, 1).value().variantType();
         ttsCommit;
    }
     while (type != COMVariantType::VT_EMPTY);
                application.quit();

}

To create Purchase Requisition Through X++

// To create Purchase Requisition Through X++

static void CreatePurchReqJob(Args _args)

{

    PurchReqTable   purchReqTable;
    PurchReqLine    purchReqLine;
    ProjTable       projTable = projTable::find("???10009");
    SalesLine       salesLine = SalesLine::findInventTransId("00000304_068");
    ;

    purchReqTable.clear();
    purchReqTable.initValue();
    purchReqTable.PurchReqId = NumberSeq::newGetNum(PurchReqTable::numRefPurchReqId()).num();
    purchReqTable.PurchReqName = "Testname";
    purchReqTable.ProjId = projTable.ProjId;
    purchReqTable.ProjIdDataArea = projTable.dataAreaId;
    purchReqTable.insert();

    purchReqLine.clear();
    purchReqLine.initValue();
    purchReqLine.InventDimId = salesLine.InventDimId;
    purchReqLine.initFromPurchReqTable(purchReqTable);
    purchReqLine.ItemId = '1001';//salesLine.ItemId;
    purchReqLine.ActivityNumber = 'AO-3456789';//salesLine.ActivityNumber;
    purchReqLine.BuyingLegalEntity = CompanyInfo::find().RecId;
    purchReqLine.InventDimIdDataArea = salesLine.dataAreaId;
    purchReqLine.initFromProjTable(projTable);
    purchReqLine.insert();

    info(purchReqTable.PurchReqId);

}

To create new customer through X++

// To create new customer through X++

static void JobCreateCustomer (Args _args)
{
    CustTable                    custTable;
    NumberSeq                    numberSeq;
    Name                         name ='SouthSide Street LTDA';

    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    ;

    /* Marks the beginning of a transaction.
       Necessary to utilize the method numRefCustAccount() */
    ttsBegin;
    custTable.initValue();

   try
    {
       //CustTable
        numberSeq               = NumberSeq::newGetNum(CustParameters::numRefCustAccount());
        custTable.AccountNum    = numberSeq.num();
        custTable.CustGroup     ='020';
        custTable.Currency      ='BRL';
        custTable.PaymTermId    ='10DD';
        custTable.PaymMode      ='CHEQUE-01';

        custTable.insert(DirPartyType::Organization, name);

        //DirParty

        /* Creates a new instance of the DirParty class from an address book entity
           that is represented by the custTable parameter. */
        dirParty = DirParty::constructFromCommon(custTable);

        dirPartyPostalAddressView.LocationName      ='HeadQuarters ';
        dirPartyPostalAddressView.City              ='São Paulo';
        dirPartyPostalAddressView.Street            ='4th Avenue';
        dirPartyPostalAddressView.StreetNumber      ='18';
        dirPartyPostalAddressView.CountryRegionId   ='BRA';
        dirPartyPostalAddressView.State             ='SP';

        // Fill address
        dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

        dirPartyContactInfo.LocationName    ='SouthStreet Contact Phone';
        dirPartyContactInfo.Locator         ='551291165341';
        dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
        dirPartyContactInfo.IsPrimary       = NoYes::Yes;

        // Fill Contacts
        dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

        // Marks the beginning of a transaction.
        ttsCommit;
    }
    catch(Exception::Error)
    {
       ttsAbort;
       throwException::Error;
    }
}

Its Show Field by Enum value by show or hide

//Its Show Field by Enum value by show or hide


void showHideFields()
{
    switch (callerSalesQuotationTable.QuotationType)
    {
        case QuotationType::Sales             :
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ItemId))         .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesQty))       .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesUnit))      .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesPrice))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineAmount))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineDisc))       .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePercent))    .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjTransType))  .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjectWorker))  .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjCategoryId)) .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePropertyId)) .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjDescription)).visible(false);

            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ItemId))         .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, Qty))            .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesUnit))      .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesPrice))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LineAmount))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscAmount))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscPercent))    .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjTransType))  .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjectWorker))  .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjCategoryId)) .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LinePropertyId)) .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjDescription)).visible(false);


            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ItemId))         .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, Qty))            .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesUnit))      .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesPrice))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LineAmount))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscAmount))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscPercent))    .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjTransType))  .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjectWorker))  .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjCategoryId)) .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LinePropertyId)) .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjDescription)).visible(false);
            break;

        case QuotationType::Project           :
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ItemId))         .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesQty))       .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesUnit))      .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesPrice))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineAmount))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineDisc))       .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePercent))    .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjTransType))  .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjectWorker))  .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjCategoryId)) .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePropertyId)) .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjDescription)).visible(true);

            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, Qty))            .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesUnit))      .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesPrice))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LineAmount))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscAmount))     .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscPercent))    .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjTransType))  .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjCategoryId)) .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LinePropertyId)) .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjDescription)).visible(true);

            if (custQuotationConfirmTrans.ProjTransType == QuotationProjTransType::Item)
            {
                custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ItemId))         .visible(true);
                custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjectWorker))  .visible(false);
            }
            else
            {
                custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ItemId))         .visible(false);
                custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjectWorker))  .visible(true);
            }

            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ItemId))         .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, Qty))            .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesUnit))      .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesPrice))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LineAmount))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscAmount))     .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscPercent))    .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjTransType))  .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjectWorker))  .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjCategoryId)) .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LinePropertyId)) .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjDescription)).visible(true);

            if (custQuotationTrans.ProjTransType == QuotationProjTransType::Item)
            {
                custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ItemId))         .visible(true);
                custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjectWorker))  .visible(false);
            }
            else
            {
                custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ItemId))         .visible(false);
                custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjectWorker))  .visible(true);
            }
            break;

        default                         :
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ItemId))         .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesQty))       .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesUnit))      .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, SalesPrice))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineAmount))     .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LineDisc))       .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePercent))    .visible(true);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjTransType))  .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjectWorker))  .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjCategoryId)) .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, LinePropertyId)) .visible(false);
            salesQuotationLine_ds.object(fieldNum(SalesQuotationLine, ProjDescription)).visible(false);

            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ItemId))         .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, Qty))            .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesUnit))      .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, SalesPrice))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LineAmount))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscAmount))     .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, DiscPercent))    .visible(true);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjTransType))  .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjectWorker))  .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjCategoryId)) .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, LinePropertyId)) .visible(false);
            custQuotationTrans_ds.object(fieldNum(CustQuotationTrans, ProjDescription)).visible(false);

            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ItemId))         .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, Qty))            .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesUnit))      .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, SalesPrice))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LineAmount))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscAmount))     .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, DiscPercent))    .visible(true);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjTransType))  .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjectWorker))  .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjCategoryId)) .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, LinePropertyId)) .visible(false);
            custQuotationConfirmTrans_ds.object(fieldNum(CustQuotationConfirmTrans, ProjDescription)).visible(false);
            break;
    }
}

How To Read Csv file in Ax 2012

//To Read Csv  file in Ax 2012

How to read CSV file in AX
    #file
    CommaTextIo       commaTextIo;      
    fileiopermission     permission;
    container              c;
    int                        x;
    int                        cols;

    permission = new fileiopermission('c:\\test.csv',#io_read);
    permission.assert();

    // specify the source file name ie. "test.csv"
    commaTextIo = new CommaTextIo('c:\\test.csv','r');
    c = commaTextIo.read();

    while(c)
    {
        cols = conlen(c);
        for(x = 1; x <= cols; x++)
        {
              info (any2str(conpeek(c,x)));
        }
        c = commaTextIo.read();
   }

   commaTextIo = null;

TO cancel the PO

// TO cancel the PO

cancel the PO. go to lines>functions>deliver remainder>cancel qty


void cancelPurchLine(recId PurchLineRecId)
{
    PurchLine       localPurchLine = PurchLine::findRecId(PurchLineRecId,true);
    ;
    ttsbegin;

    localPurchLine.RemainPurchPhysical = 0;
    localPurchLine.RemainInventPhysical = 0;

    localPurchLine.update();

    ttscommit;
}

Days between two dates not counting Saturday and Sunday:

// Days between two dates not counting Saturday and Sunday:

static void WorkDayDiff(Args _args)
{
    int i;
    Days workDayDiff(date d1, date d2)
    {
        Days y1 = dayofwk(d1);          // Day of week 1
        Days y2 = dayofwk(d2);          // Day of week 2
        date t1 = d1 - y1;              // Sunday before d1
        date t2 = d2 - y2;              // Sunday before d2
        Days y3 = (t2 - t1) div 7 * 5;  // Work days between Sundays
        Days y4 = min(y1-1,5);          // Work days before d1
        Days y5 = min(y2,5);            // Work days after t2
        return y3 - y4 + y5 - 1;        // Work days between d1 and d2
    }
    ;
    setprefix(strFmt("Today %1 %2", today(), dayname(dayofwk(today()))));
    for (i = -10; i <= 10; i++)
        info(strFmt("Diff %1 %2 = %3", today()+i, dayname(dayofwk(today()+i)), int2str(workDayDiff(today(), today() + i))));
}

How to access tables of different companies


//how to access tables of different companies
(crosscompany)?


static void crossCompanysupport(Args _args)
{
    container conCompanies = [ 'cee', 'ceu' ];
custTable custTable;
while select crossCompany : conCompanies custTable
    where custTable.accountNum >= "2000" && custTable.AccountNum <="5000"
{
print custTable.accountNum;
}
pause;

}

SSRS report using DP ,Contract, Controller

// SSRS report using DP ,Contract, Controller
//DP class

[
    SRSReportParameterAttribute(classstr

(PurchContractClass))
]
public class PurchDPClass extends

SRSReportDataProviderBase
{
    PurchTmp    purchTmp;
}


Method :

[SRSReportDataSetAttribute('PurchTmp')]
public purchTmp getpurchTmp()
{
    select * from purchTmp;
    return purchTmp;
}

Method  1:
[SysEntryPointAttribute(false)]
public void processReport()
{
    PurchTable  purchTable;
    PurchLine   purchLine;
    PurchContractClass purchContractClass;
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;

    purchContractClass = this.parmDataContract() as

PurchContractClass;
    purchId = purchContractClass.parmPurchId();
    //purchStatus = purchContractClass.parmPurchStatus();
    //inclTax = purchContractClass.parmInclTax();

     while select purchTable where purchTable.PurchId ==

purchId
    {
        purchTmp.PurchId = purchTable.PurchId;
        purchTmp.InvoiceAccount =

purchTable.InvoiceAccount;
        purchTmp.PurchName = purchTable.PurchName;
        purchTmp.InclTax = purchTable.InclTax;
        purchTmp.PaymMode = purchTable.PaymMode;
        purchTmp.PurchStatus = purchTable.PurchStatus;
        purchTmp.CurrencyCode =

purchTable.CurrencyCode;
     
        select purchId from purchLine where

purchLine.PurchId == purchTable.PurchId;
     
        purchTmp.itemid = purchLine.ItemId;
        purchTmp.VendGroup = purchLine.VendGroup;
        purchTmp.LineNumber = purchLine.LineNumber;
        purchTmp.PurchQty = purchLine.PurchQty;
     
        purchTmp.insert();
    }
}

//Contract Class:

[DataContractAttribute]
public class PurchContractClass
{
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;
}

Method 1:
[DataMemberAttribute("PurchId")]
public PurchId parmPurchId(PurchId _purchId = purchId)
{
    purchId = _purchId;
    return purchId;
}

Method 2:
[DataMemberAttribute("InclTax")]
public InclTax parmInclTax(InclTax _inclTax = inclTax)
{
    inclTax = _inclTax;
    return inclTax;
}

Method 3:

[DataMemberAttribute("PurchStatus")]
public PurchStatus parmPurchStatus(PurchStatus

_purchStatus = purchStatus)
{
    purchStatus = _purchStatus;
    return purchStatus;
}


// Controller Class

class PurchControllerClass extends

SrsReportRunController
{
     RecordSortedList       journalList;


     PurchView      purchview;
     //CWBProjInvoiceContract CWBProjInvoicecontract;
}

protected void initArgs(Args _args)
{
    args = new Args();

     if (_args.object() &&
        _args.object() is RecordSortedList)
    {
        journalList = _args.object();
    }
    else if (_args.record())
    {
        journalList = new RecordSortedList(tableNum

(PurchView));
        journalList.ins(_args.record());
    }

    journalList.first(purchview);

    this.parmReportName

("PurchReport.PurchReportDesign");
    this.parmShowDialog(false);

    this.parmArgs(_args);
}

protected void preRunModifyContract()
{
    PurchContractClass contract;
    contract = this.parmReportContract

().parmRdpContract() as PurchContractClass;

    contract.parmPurchId(purchview.PurchId);
    contract.parmVendAccount(purchview.InvoiceAccount);
    ////contract.parmPurchStatus(purchview.PurchStatus);
    //contract.parm(purchview.PurchId);
}

public static void main(Args _args)
{
   PurchControllerClass controller = new

PurchControllerClass();
    ;


   controller.parmReportName

("PurchReport.PurchReportDesign");
   //controller.parmArgs(_args);
    controller.initArgs(_argsssssss);

    controller.startOperation();
}

Calculation of Explosive Qty

// Calculation of Explosive Qty

private void CalculationOfExplosiveQty()
{
    ExplosiveQty    netExplosiveQty;
    InventTable     _InventTable;
    InventSum       _InventSum;
    InventLocation  _InventLocation;
    PurchParmLine   _PurchParmLine,_PurchParmLine1;
    InventDim       _InventDim,_InventDim1;
    real            totalQty,PhysicalQty;
    PurchId         _PurchId;
    ;

    while select _InventDim1 group by InventLocationId join _PurchParmLine1 where _PurchParmLine1.ParmId == PurchParmTable.ParmId
                                                                                && _InventDim1.inventDimId == _PurchParmLine1.InventDimId
    {
        totalQty =0;
        info(strFmt("%1",_InventDim1.InventLocationId));

        while select _PurchParmLine join _InventDim group by InventLocationId where _PurchParmLine.ParmId == PurchParmTable.ParmId
                                                                            && _InventDim.inventDimId == _PurchParmLine.InventDimid
                                                                            && _InventDim.inventlocationid == _InventDim1.inventlocationid

        {
            _PurchId = PurchParmLine.OrigPurchId;
            select _InventTable where _InventTable.ItemId == _PurchParmLine.ItemId;
            netExplosiveQty = _InventTable.ExplosiveQty;
            select _InventLocation where _InventLocation.InventLocationId == _InventDim.InventLocationId;
            totalQty += PurchParmLine.ReceiveNow * netExplosiveQty;
        }
            PhysicalQty = 0;
            while select _InventSum join _InventDim join _InventTable where _InventSum.InventDimId == _InventDim.inventDimId
                                                                        && _InventDim.InventLocationId == _InventDim1.InventLocationId
                                                                        && _InventTable.ItemId == _InventSum.ItemId
            {
                PhysicalQty += _InventSum.PhysicalInvent * ((_InventTable.ExplosiveQty == 0)? 1 : _InventTable.ExplosiveQty) ;
                // info(strFmt("%1 :  %2",_InventSum.PhysicalInvent,_InventDim.InventLocationId));
            }
                // info(strFmt("%1 : %2",PhysicalQty,totalQty));
                if(_InventLocation.ExplosiveLimit < totalQty + PhysicalQty)
                {
                    info(strFmt("Limit Exceed in  wearhouse %1",_InventDim1.InventLocationId));
                }
                else
                {
                    info("Purchase Order Posted");
                }
    }
}

To open Form by X++


// To open Form by X++

static void OpenForm()
{ FormRun formRun;
Args args = new Args();
;
args.name(formstr(VendTable));
args.record(CustTable::find("XYZ"));

formRun = ClassFactory.formRunClass(args);
formRun.init();
formRun.run();
formRun.wait();
}

Query Examples

// Query Examples


static void Query (Args _args)
{
Query query;
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange qbr;
SalesTable SalesTable;
query = new Query();

qbds = query.addDataSource(TableNum (SalesTable));

qbr = qbds.addRange(FieldNum (SalesTable,CustAccount));


qbr.value ('3003');

qbds.addSortField (FieldNum(SalesTable,SalesId));

queryRun = new QueryRun(query);


while (queryRun.next())
{

SalesTable = queryRun.get(tableNum(SalesTable));
print SalesTable.SalesId;

}
pause;
}



this.query().dataSourceTable(tablenum(SupplProduct)).addRange(fieldnum(SupplProduct, ShowOnReport)).value(QueryValue(NoYesCombo::Yes));

this.query().dataSourceTable(tablenum(AppointmentTable)).addRange(fieldnum(AppointmentTable, AppointmentId)).value(queryValue(activeAppoint.AppointmentId));
//
InventoryMangementOnhandView is ViewDatasource

 qbr = InventoryMangementOnhandView_ds.query().dataSourceNo(1).addRange(fieldNum(InventoryMangementOnhandView, DatePhysical));
    _qbr = InventoryMangementOnhandView_ds.query().dataSourceNo(1).addRange(fieldNum(InventoryMangementOnhandView, StatusReceipt));

//TO filter a date value to view data source

    qbr.value(strFmt("<%1", AsonDate.dateValue()));
// To filter a two enum value to view filtered date value to view datasource

    _qbr.value("1..2");

// Example range Value

 query = new Query();
        queryBuildDataSource = query.addDataSource(
            TableNum(CustTable));

        //----------- Range: AccountNum
        queryBuildRange = queryBuildDataSource.addRange(
            FieldNum(CustTable,AccountNum));
        queryBuildRange.value("4000..5000");


// Example with Explanation :
http://nathalie.gimenez.free.fr/DynamicsAX/DynamicsProg_queryrange.html

Upload data from Excel in D365FO X++

 Action Menu Item: SAN_UploadExcelData Object type: Class Object: <Controller class name> Label: <> Class: Controller class clas...