Showing posts with label POST. Show all posts
Showing posts with label POST. Show all posts

Monday, April 18, 2016

HOW TO CREATE A DIALOG IN DYNAMICS AX : X++ CODE

CREATE A DIALOG IN AX : X++ CODE 


class CustDialog extends RunBase
{
DialogField fieldAccount;
DialogField fieldName;
DialogField fieldGroup;
DialogField fieldCurrency;
}

pack() and unpack(0 are used to retain the last used values.
public container pack()
{
return conNull();
}
public boolean unpack(container _packedClass)
{
return true;
}
protected Object dialog()
{

Dialog dialog;
DialogGroup groupCustomer;
DialogGroup groupPayment;
dialog = super();
dialog.caption("Customer information"); dialog.allowUpdateOnSelectCtrl(true);
fieldAccount = dialog.addField(
extendedTypeStr(CustAccount), "Customer account");
fieldName = dialog.addField(extendedTypeStr(CustName));
fieldName.enabled(false);
dialog.addTabPage("Details");
groupCustomer = dialog.addGroup("Setup");
fieldGroup = dialog.addField(
extendedTypeStr(CustGroupId)); fieldCurrency = dialog.addField(
extendedTypeStr(CurrencyCode)); fieldGroup.enabled(false);
fieldCurrency.enabled(false);
groupPayment = dialog.addGroup("Payment");
return dialog;
}

Below method is used to dynamically assign the different values of the cust table
public void dialogSelectCtrl()
{
CustTable custTable;
custTable = CustTable::find(fieldAccount.value()); fieldName.value(custTable.name()); fieldGroup.value(custTable.CustGroup); fieldCurrency.value(custTable.Currency);
}
public static void main(Args _args)
CustSelect custSelect = new CustSelect();
if (CustSelect.prompt()) {
CustSelect.run();
}
}

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++
PUBLIC VOID READCOMMAFILE()
{
CommaTextIo         file;
container           line;
#define.filename(@'C:\\accounts.csv') #File
file = new CommaTextIo(#filename, #io_read);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
line = file.read();
while (file.status() == IO_Status::Ok)
{
info(con2Str(line, ' - '));
line = file.read();
                }


}

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE
public void createcommafiles()
{
CommaTextIo         file;
container            line;
MainAccount           mainAccount;
#define.filename(@'C:\accounts.csv') #File
file = new CommaTextIo(#filename, #io_write);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
while select MainAccountId, Name from mainAccount
{
line = [
mainAccount.MainAccountId,
mainAccount.Name];
file.writeExp(line);
}
info(strFmt("File %1 created.", #filename));

}

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE FOR A TABLE

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE 
FOR A TABLE

static void TabledocuAdd(Args _args) {
DocuRef      docuRef;
VendTable vendTable;
vendTable = VendTable::find('123');
docuRef.RefCompanyId = vendTable.dataAreaId;
docuRef.RefTableId    = vendTable.TableId;
docuRef.RefRecId        = vendTable.RecId;
docuRef.TypeId        = 'Note';
docuRef.Name            = 'Imported';
docuRef.Notes         = 'This vendor was imported.';
docuRef.insert();

}

Saturday, April 16, 2016

LIST OF AX TABLES /TABLES FIELDS IN DYNAMICS AX THROUGH JOB

LIST OF AX TABLES /TABLES FIELDS IN DYNAMICS AX THROUGH JOB
static void findTablesinAX(Args _args)
{
    Dictionary      dictionary;
    TableId         tableId;
    tableName       tableName;
    ;
    dictionary = new Dictionary();
    tableId = dictionary.tableNext(0);
    tableName = dictionary.tableName(tableId);
    while (tableId)
    {
        info(strfmt("%1 - %2",int2str(tableId), tableName));
        tableId = dictionary.tableNext(tableId);
        tableName = dictionary.tableName(tableId);
    }
}

static void FindTableFields(Args _args)
 {
TreeNode node = TreeNode::findNode(@'\Data dictionary\Tables\CustTable\Fields');
TreeNode childNode;
TreeNodeIterator nodeIT;
                                                       tab
nodeIt = node.AOTiterator();
childNode = nodeIt.next();
while(childNode)
{
    info(strfmt("PBATable %1", childNode.treeNodeName()));
    childNode = nodeIt.next();
}
}

CURRENT COMPANY IN AX /GET ACTIVE COMPANY'S NAME IN AX

Get the active company in AX 2009 - curExt()

Use the curExt() function to get the active company in AX;

static void curExtExample(Args _arg)
{
str CompanyId;
;

CompanyId = curExt();
Info(CompanyId);
}

Or else you can also use the following code.

static void curExtExample(Args _arg)
{
str CompanyId;
;

CompanyId = CompanyInfo::Find().DataAreaId;
Info(CompanyId);
}

COLOR FORMS IN AX ENVIRONMENTS : AX 2012 CODE X++ DYNAMICS

Color forms in ax Environments


There is a way to change the color of the Dynamics forms to help indicate what environment is in use. It involved overriding the SysSetupFormRun.run() method, which will be called every time a form is opened. On the class SysSetupFormRun, 
create a new method with this code:

public void run()
{
SysSQLSystemInfo systemInfo = SysSQLSystemInfo::construct();
; 

super();
// Set the color scheme of this instance of the SysFormRun to RGB
this.design().colorScheme(FormColorScheme::RGB);
// If the database name is not the live version, change the color of the form
if (systemInfo.getloginDatabase() != 'MyDBName')
this.design().backgroundColor(0x112255);
}

Change Color of your Dynamics AX Environments/Forms

 Change Color of your Dynamics AX  Environments/Forms


To change the color of the Dynamics forms to help indicate what environment is in use. It involved overriding the SysSetupFormRun.run() method, which will be called every time a form is opened. On the class SysSetupFormRun, create a new method with this code:
public void run()
{
SysSQLSystemInfo systemInfo = SysSQLSystemInfo::construct();
; 

super();
// Set the color scheme of this instance of the SysFormRun to RGB
this.design().colorScheme(FormColorScheme::RGB);
// If the database name is not the live version, change the color of the form
if (systemInfo.getloginDatabase() != 'DynamicsAX_test')
this.design().backgroundColor(0x112255);
}



 If your live and test systems use the same database name, but the AOS is running on different servers you can modify this code to to match on systemInfo.getLoginServer() != 'MyServerName'. You can change the color by setting the hex value. It uses the RGB values in reverse order: 0xBBGGRR. 

thanks,
Vikas Mehta

SQL STATEMENT IN AX X++ CODE

SQL statement in Ax code x++ generated 

So here is another small tip based on me reading Inside Microsoft Dynamics AX 2012 R3.

If you want to know what SQL statement the SQL Server query processor generates based on a regular X++ select statement, you can add to the keyword generateOnly to the statement and afterwards call the getSQLStatement method on the record buffer.

Example:
   AccountingEvent         accountingEvent;
   SourceDocumentHeader    sourceDocumentHeader;
   
   select generateonly accountingEvent
   join sourceDocumentHeader 
       where sourceDocumentHeader.RecId == accountingEvent.SourceDocumentHeader;

   info (accountingEvent.getSQLStatement());

AX 2012 SSRS REPORT ERRORS AND TROUBLESHOOT

AX 2012 SSRS - Misc Problems and Solutions

Problem
You get a http 503 service unavailable during installation of Report Extensions.

Solution
Check the remote registry settings.Remove Report Server settings in AX.

Problem
The title of the window of a SSRS report doesn't change as expected when editing it on the menu item or from Visual Studio.

Solution
Delete usage data in AX.

Problem
Error while setting server report parameters. Error message: The DefaultValue expression for the report parameter ‘AX_CompanyName’ contains an error: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. (rsRuntimeErrorInExpression)

Solution
Open the file C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\rssrvpolicy.config
Set PermissionSetName to “FullTrust” at Name=Report_Expressions_Default_Permissions

See:
http://community.dynamics.com/product/ax/axtechnical/b/axsupport/archive/2012/02/02/microsoft-dynamics-ax-2012-reporting-extensions-error-system-security-permissions-environmentpermission-while-running-report.aspx

Problem
The reports are deployed to the wrong report folder.

Solution
AX was started with the wrong active client configuration. You need to set the client configuration to the AOS that you wish to deploy to, even though you are overriding it on the client shortcut. Don't forget to restart AX afterwards - the setting is cached when AX is started.

Problem
The report cannot be deployed because it couldn't find the network path.

Solution
Start Windows service "Remote Registry"
See: http://technet.microsoft.com/en-us/library/gg724094.aspx

Problem
Error when running SSRS in batch:
"System.InvalidCastException: Unable to cast object of type 'Microsoft.Dynamics.Ax.Xpp.DictMethod' to type 'Dynamics.Ax.Application.SysDictMethod'."

Solution
Change SysDictMethod to DictMethod on line 3 in:
\Classes\SrsReportRdpRdlWrapperContractInfo\buildMemberAndNestedObjectMap

Problem
Error while setting report parameters. Error message: An error has occurred during report processing. (rsProcessingAborted)

Solution
See: https://community.dynamics.com/ax/b/axsupport/archive/2013/03/12/cannot-be-processed-at-the-receiver-due-to-a-contractfilter-mismatch-at-the-endpointdispatcher.aspx


Sales Order Creation Service : AX 2012 X++ code

Sales Order Creation in AX with Config

[AifCollectionTypeAttribute('return', Types::String), SysEntryPointAttribute(true)]
public str CreateSalesOrder(SalesIdBase _salesId,CustAccount _customerId,InventSiteId _site,TaxGroup _taxGroup,
                      )
{
    str                                     log;
    str                                     log_1,log_2,log_3,log_4,log_5,log_6,log_7,log_8,log_9;
    Inventsite                              site;
    InventLocation                          ware;
    SalesTable                              header,salesTable,salesTablechk;
    SalesLine                               line_1,line_2;
    SalesLine_IN                            line_In,line_Inc;
    NoYes                                   noyes;
    str                                     component;
    container                               con,_conchar,_concharvalue;
    int                                     i,j,configCount,k,counter;
    MarkupTable                             markTab;
    MarkupTrans                             trans;
    EcoResProductMaster                     ecoResProductMaster;
    EcoResConfiguration                     ecoResConfiguration;
    EcoResProductMasterConfiguration        ecoResProductMasterConfiguration;
    EcoResDistinctProductVariant            ecoResDistinctProductVariant;
    EcoResProductVariantConfiguration       ecoResProductVariantConfiguration;
    EcoResconfigurationName                 _name;
    container                               prodDimensions;
    RefRecId                                ecoResDistinctProductVariantRecId;
    ConfigChoice                            config,configrec;
    int                                     newconfigrec;
    ConfigGroup                             configGroup;
    ConfigGroupId                           groupId;
    TmpConfigId                             tempConfig;
    TmpConfigValue                          tempConfigValue;
    EcoResProductReleaseManagerBase         releaseManager;
    InventDim                               dim;
    InventDimCombination                    comb;
   // AxSalesTable                            axsalesTable;
    SalesFormLetter                         salesFormLetter;
    CompanyInfo                             info;
    DirPartyLocation                        dirPartyLocation;
    TaxInformation_IN                       taxInformation;
    compProductMasterDefault                 prodMasterdef;
    _conchar        = str2con(_charname,',');
    _concharvalue   = str2con(_charvalue,',');
    select * from prodMasterdef;
   changeCompany(prodMasterdef.DealerCompany)
    {
        select salesid from salesTablechk where salesTablechk.salesid ==_salesId;
  if(!salesTablechk.RecId && InventSite::exist(_site) && InventLocation::exist(_warehouse) && InventTable::exist(_item) && SalesTaxFormTypes_IN::exist(_saleTypeSalesTax)  &&  TaxGroupHeading::exist(_taxGroup))
    {
        configcount++;
        ttsBegin;
        //creating header
        header.clear();
        header.SalesId = _salesId;
        header.SalesType = SalesType::Sales;
        header.initValue();
        header.CustAccount = _customerId;
        header.InvoiceAccount = _customerId;
        header.initFromCustTable();
        header.InventSiteId = _site;
        header.InventLocationId = _warehouse;
        header.Payment = _paymTerm;
        header.ShippingDateRequested = _deliveryDate;
        header.CurrencyCode = _currency;
        header.LanguageId =  systemparameters::getSystemLanguageId();
        header.comp_SoldToParty = _soldToParty ;
        header.comp_ShipToParty = _shipToParty;
        header.comp_BilltoAddress = _billTo;
        header.comp_ShiptoAddress = _shipTo;
        header.DlvTerm = _delTerm;
        header.CustGroup = CustTable::find(_customerId).CustGroup;
        header.TaxGroup   =  _taxGroup;
        header.CustomerRef   = _ref;
        header.PurchorderFormNum = _custReq;
        header.comp_OrderType = _orderType;
        header.comp_OrderCat = _orderCategory;
        header.comp_SaleTypeExciseDuty = _saleTypeExcise;
        header.comp_E1Sale = str2enum(noyes,_e1Sale);
        header.comp_Domestic = str2enum(NoYes,_domestic);
        header.comp_Export = str2enum(NoYes,_export);
        header.comp_IncoTerm2 = _incoTerm;
        header.comp_FOCSpacesOffered = _FOCspaces;
        header.comp_FocInformation = _FOCInformation;
        header.comp_Financer = _financer;
        header.insert();
        line_1.initFromSalesTable(header,true);
        line_1.ItemId = _item;
        //line_1.QtyOrdered = _qty;
        line_1.SalesQty = _qty;
        line_1.initFromSalesLine_IN(line_1);
       // line_1.initFromSalesLineView_IN(
        //changes start
        select count(RecId) from configrec where configrec.ItemId == _item;
        {
            newconfigrec = int642int(configrec.RecId) + 1;
        }
       
        //changes foc product
        if(!conLen(_conChar)==0 && strLen(_charname) != 0)
        {
        _name = this.Config(_conChar,_conCharValue,_item);
        if(_name == '')
        {
                //creating configuration on basis of characteristic name and values
            //    _name = 'second';
                   _name = int2str(newconfigrec);
                 ecoResConfiguration = EcoResConfiguration::findByName(_name);
                if (!ecoResConfiguration)
                {
                    ecoResConfiguration.clear();
                    ecoResConfiguration.initValue();
                    ecoResConfiguration.Name = _name;
                    ecoResConfiguration.insert();
                }
                select ecoResProductMaster where ecoResProductMaster.DisplayProductNumber == _item;
                 Select firstonly ecoResProductMasterConfiguration where ecoResProductMasterConfiguration.ConfigProductMaster == ecoResProductMaster.RecId
                        && ecoResProductMasterConfiguration.Configuration == ecoResConfiguration.RecId;
                if (!ecoResProductMasterConfiguration)
                {
                    ecoResProductMasterConfiguration.clear();
                    ecoResProductMasterConfiguration.initValue();
                    ecoResProductMasterConfiguration.Configuration = ecoResConfiguration.RecId;
                    ecoResProductMasterConfiguration.ConfigProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, ConfigId));
                    ecoResProductMasterConfiguration.ConfigProductMaster = ecoResProductMaster.RecId;
                    ecoResProductMasterConfiguration.insert();
                }
                select tempConfig ;
                tempconfig.ConfigId =  ecoResConfiguration.Name;
                tempConfig.doInsert();
               for (i=1; i <= conlen(_conChar); i++)
                {
                   tempConfigValue.clear();
                   tempConfigValue.ConfigGroupId = conPeek(_conChar,i) ;
                   tempConfigValue.ItemId = conPeek(_conChar,i)+'_'+ conPeek(_conCharValue,i);
                   tempConfigValue.ConfigId = ecoResConfiguration.Name;
                   tempConfigValue.GroupNum = counter;
                   tempConfigValue.doInsert();
                   Counter++;
                   config.clear();
                   config.initValue();
                   config.initFromTmpConfigValue(tempConfigValue);
                   config.ItemId = _item;
                   config.ConfigId = ecoResConfiguration.Name;
                   config.Autogenerated = NoYes::No;
                   config.insert();
                }
                prodDimensions = EcoResProductVariantDimValue::getDimensionValuesContainer(_name);
                //Create Product search name
                ecoResDistinctProductVariant.DisplayProductNumber = EcoResProductNumberBuilderVariant::buildFromProductNumberAndDimensions('PC104',prodDimensions);
               //Create Product variant with Product and dimensions provided
                ecoResDistinctProductVariantRecId = EcoResProductVariantManager::createProductVariant(ecoResProductMasterConfiguration.ConfigProductMaster,ecoResDistinctProductVariant.DisplayProductNumber,prodDimensions);
                //Find newly created 4 Variant
                ecoResDistinctProductVariant = ecoResDistinctProductVariant::find(ecoResDistinctProductVariantRecId);
                //Now release the Product variant
               releaseManager = EcoResProductReleaseManagerBase::newFromProduct(ecoResDistinctProductVariant);
               releaseManager.release();
               dim.configId = _name;
        }
         else
            {
                dim.configId = _name;
            }
        }
        // dim.configId = InventTable::find(line.ItemId).StandardConfigId;
        dim.InventSiteId = _site;
        dim.InventLocationId = _warehouse;
       // dim.configId = _name;
        dim = InventDim::findOrCreate(dim);
        dim.write();
        //creating line
        line_1.InventDimId = dim.inventDimId;
        comb = InventDimCombination::findByInventDim(line_1.ItemId,dim);
        line_1.RetailVariantId = comb.RetailVariantId  ;
        line_1.createLine(true,true,true,false,true,true,false,false,'',true,true,false,null,0,'');
        select forUpdate line_2 where line_2.SalesId == line_1.SalesId;
        if(line_2.RecId)
        {
           line_2.SalesPrice = _price;
        }
        line_2.modifiedField(fieldnum(SalesLine,SalesPrice));
        line_2.update();
        //allocating charges
        if(_FOCSpares != 0 )
        {
            markTab = MarkupTable::find((MarkupModuleType::Cust),'1');
            trans.clear();
            trans.initFromSalesLine(line_1);
            trans.initFromMarkupTable(marktab);
            trans.MarkupCategory = MarkupCategory::Pcs;
            trans.Value = _FOCSpares/_qty;
            trans.LineNum = k;
            trans.insert();
            k++;
        }
        info = CompanyInfo::findByCompany_IN(curext());
        dirPartyLocation = DirPartyLocation::findPrimaryPartyLocation(info.RecId);
        if (dirPartyLocation)
        {
           line_In.CompanyLocation_IN = LogisticsLocation::find(dirPartyLocation.Location).RecId;
             select firstonly RecId from taxInformation
            where taxInformation.RegistrationLocation == LogisticsLocation::find(dirPartyLocation.Location).RecId
                    && taxInformation.IsPrimary == NoYes::Yes;
        }
       select forupdate line_IN where line_In.SalesLine == line_2.RecId;
        if(line_In.RecId)
        {
            line_In.CompanyLocation_IN  = LogisticsLocation::find(dirPartyLocation.Location).RecId;
            line_In.TaxInformation = taxInformation.RecId;
            line_In.SalesTaxFormTypes_IN = SalesTaxFormTypes_IN::findbyFormType(_saleTypeSalesTax).RecId;
            line_In.AssessableValue_IN = line_2.getMiscChargesAmount_IN();
            line_In.ExciseRecordType_IN = ExciseRecordType_IN::RG23D;
            line_In.ExciseType_IN = ExciseType_IN::Trader;
            line_IN.update();
        }
        //confirming Sales Order
        salesformletter = SalesFormletter::construct(DocumentStatus::Confirmation);
        salesTable = SalesTable::find(_salesId);
        salesFormLetter.update(salesTable);
        ttscommit;
        log = strfmt('Success : Sales Order Created successfully');
        k = 1;
    }
      else
        {
            if(salesTablechk.RecId)
             {
                log_9 = strfmt('Saled Order %1 already exist',_salesId) ;
            }
            if(!InventSite::exist(_site))
            {
                log_1 = strfmt('Site %1 is not valid for SO %2',_site,_salesId) ;
            }
            if(!InventLocation::exist(_warehouse))
            {
                log_2 = strFmt('Warehouse %1 is not valid for SO %2',_warehouse,_salesId) ;
            }
            if(!InventTable::exist(_item))
            {
                log_3 = strFmt('Item %1 is not valid for SO %2',_item,_salesId) ;
            }
            if(!SalesTaxFormTypes_IN::exist(_saleTypeSalesTax))
            {
                log_4 = strFmt('SalesTax FormType %1 is not valid for SO %2',_saleTypeSalesTax,_salesId) ;
            }
            if(!TaxGroupHeading::exist(_taxGroup))
            {
                log_5 = strFmt('Tax Group %1 is not valid for SO %2',_taxGroup,_salesId) ;
            }
            log = strFmt("%1/n%2/n%3/n%4/n%5/n%6",log_9,log_1,log_2,log_3,log_4,log_5);
        }
        info(strFmt("SO Integration : %1 - %2 ",_salesId,log));
        comp_RetailExceptionActivityLog::logEvent('Sales Order Creation:',infolog.export());
     return log ;
    }//change company
    }



Config Creation:
config creation
public str config(container _conChar,Container _conCharValue,ItemId _item)
{
    ConfigChoice            choice,_config;
    int                     length,i,choice_1,con,l;
    ItemId                  chosenItem;
    boolean                 configexist;
    ConfigIdStandard        configname;
    container               conTax ;
    length = conLen(_conChar);
    while  select ConfigId from _config    group by _config.ConfigId  where  _config.itemid == _item
    {
        choice_1 = 0;
        for(i=1;i<=length;i++)
        {
            chosenItem = conPeek(_conChar,i)+'_'+ conPeek(_conCharValue,i);
            select choice where choice.ConfigId ==  _config.ConfigId
                            &&  choice.ChosenItemId == chosenItem;
            if(choice)
            {
            choice_1++;
            }
        }
        if(choice_1 == length)
        {
            configexist = true;
            configname = choice.ConfigId;
        }
        if(configexist == true)
        {
            break ;
        }
    }
    return configname;
}

PURCHASE ORDER CATEGORY PRODUCT RECEIPT CALLER CLASS

Purchase category

1.       PO invoice and product receipt

Changes have been done in the forms clicked ok methods of post and close ok
Blow is code for product receipt
// po category start

    VendPackingSlipJour         vendPackingSlipJour;
    Vik_PurchaseOrderCategory   poCategory;
    int                         daydiff,prodreceiptcount;
    PurchTable                  purchTableLocal;

    if(curext() == 'SDS')
    {
        if( classidget(purchFormLetter) == classnum(PurchFormLetter_PackingSlip)) //&& (purchTable.Vik_PurchaseCategory != Vik_PurchaseCategory::None))
        {
            select purchTableLocal where purchTableLocal.PurchId == purchFormLetter.purchTable().PurchId;
            select poCategory where poCategory.Vik_PurchaseCategory == purchTableLocal.Vik_PurchaseCategory;
            select count(RecId) from vendPackingSlipJour where vendPackingSlipJour.PurchId == purchTableLocal.PurchId;

            prodreceiptcount = int642int(vendPackingSlipJour.RecId);

            if(prodreceiptcount > poCategory.DeliveryTimes)
                throw error(strFmt(" The Product receipt for Purchase Order %1 has exceeded for the category %2",purchTableLocal.PurchId,purchTableLocal.Vik_PurchaseCategory));
        }

    }
 //   po category end

Below is code for Invoice

void clicked()
{
    // po category start

    Vik_PurchaseOrderCategory   poCategory;
    int                         daydiff,prodreceiptcount;
    PurchTable                  purchTableLocal;



    if(curext() == 'SDS')
    {
        select purchTableLocal where purchTableLocal.PurchId == purchFormLetter.purchTable().PurchId;
        if( classidget(purchFormLetter) == classnum(PurchFormLetter_Invoice) && (purchTable.Vik_PurchaseCategory != Vik_PurchaseCategory::None))
        {
           
            select poCategory where poCategory.Vik_PurchaseCategory == purchTableLocal.Vik_PurchaseCategory;
          //  daydiff = purchTableLocal.createdDateTime - DateTimeUtil::getSystemDateTime();
            daydiff = DateTimeutil::getDifference(DateTimeUtil::getSystemDateTime(), purchtablelocal.createddatetime) / 86400;
            if(daydiff > poCategory.ExpireDays)
                throw error(strFmt(" The Purchase Order %1 has exceeded the expire days for the category %2",purchTableLocal.PurchId,purchTableLocal.Vik_PurchaseCategory));
        }

    }
 //   po category end
    // <GEERU>
    if (SysCountryRegionCode::isLegalEntityInCountryRegion([ #isoRU ]) && ! purchFormLetter.checkBeforePost())
    {
        return;
    }
    // </GEERU>
    super();
}

AX 2012 EXCEL UPLOAD CODE EXCELIMPORT :VIKAS :DYNAMICS AX 2012 : ITEM CATEGORY UPDATE FOR ITEMS

ITEM CATEGORY UPDATE FOR ITEMS
   VIKAS ITEM EXCEL IMPORT TESTED
    METHODS
       classDeclaration
        class Vik_ItemCategory_ExcelImport exts RunBaseBatch
        {
             DialogField                         dialogfile;
             FilenameOpen                        fileName;
             localmacro.CurrentList
              fileName
            macro
        }
     
       createcategory
        Public void createcategory(Itemid _itemno,EcoResCategoryCommodityCode _CategoryName,EcoResCategoryHierarchyName _name)
        {
       
                 //vikas
            EcoResDistinctProduct  ecoResDistinctProduct;
            EcoResProduct           ecoResProduct;
            EcoResProductTranslation ecoResProductTranslation;
            EcoResProductCategory   ecoResProductCategory;
            EcoResCategory          ecoResCategory;
            EcoResCategoryHierarchy ecoResCategoryHierarchy;
            ecoResCategoryTranslation   ecoResCategoryTranslation;
            //vikas
             //Create Producr Category (Hierarchy)
            select ecoResDistinctProduct where ecoResDistinctProduct.DisplayProductNumber == _itemno;
            Select firstOnly ecoResCategoryHierarchy where ecoResCategoryHierarchy.Name == _name;
            Select firstonly ecoResProductCategory where ecoResProductCategory.Product == ecoResDistinctProduct.RecId;
            if (!ecoResProductCategory)
            {
                ttsBegin;
                ecoResProductCategory.clear();
                ecoResProductCategory.initValue();
                ecoResProductCategory.CategoryHierarchy         = ecoResCategoryHierarchy.RecId;
                select * from ecoResCategory where ecoResCategory.Name == _CategoryName;
                ecoResProductCategory.Category                  = ecoResCategory.RecId;
                //ecoResProductCategory.category = ecoResCategoryTranslation.RecId;
                ecoResProductCategory.Product                   = ecoResDistinctProduct.RecId;
                //ecoResProductCategory.VIK_EcoResProductType     = VIK_EcoResProductType::findByProductType(_productType).RecId;
                //ecoResProductCategory.VIK_EcoResSubCategory     = VIK_EcoResSubCategory::findBySubCategory(_subCategory).RecId;
                ecoResProductCategory.insert();
                ttsCommit;
                info(strFmt("category for item %1 is created",_itemno));
            }
       
        }
     
       dialog
        protected Object dialog()
        {
            DialogRunbase  _dialog = super();
       
            _dialog.caption("Product Upload");
            dialogfile = _dialog.addField("FilenameOpen","Enter file path : ");
            dialogfile.value(fileName);
       
            return _dialog;
        }
     
       getFromDialog
        public boolean getFromDialog()
        {
            ;
            fileName = dialogfile.value();
            return true;
        }
     
       run
        public void run()
        {
            SysExcelApplication excel;
            SysExcelWorkbooks workbooks;
            SysExcelWorkbook workbook;
            SysExcelWorksheets worksheets;
            SysExcelWorksheet worksheet;
            SysExcelCells cells;
            COMVariantType type;
            int row =1;
            int _noofprints;
            EcoResCategoryCommodityCode _CatName;
            EcoResCategoryHierarchyName _Hiername;
            CustName name;
            int i,j;
            //sales price upload
            str queryPricingMaster,itemId,existingItemIdsList,tempValue;
            ResultSet resultSet;
            InventTable inventTable;
       
            //vikas
            EcoResProduct           ecoResProduct;
            EcoResProductTranslation ecoResProductTranslation;
            EcoResProductCategory   ecoResProductCategory;
            EcoResCategory          ecoResCategory;
            EcoResCategoryHierarchy checkEcoResCatH;
            EcoResCategory          checkEcoResCat;
               //checkEcoResCatH                     = EcoResCategoryHierarchy::findByName(_Hiername);
            //checkEcoResCat                      = EcoResCategory::findByName(_CatName,checkEcoResCatH.RecId);
            //vikas
       
            //vikas
            //sales price upload//
            str _relation,_accountcode,_accountselection,_itemcode,_temrelation,_unit,_curcode;
            real _from,_amtincur;
            date _todate,_fromdate;
            PriceType _pricetype;
       
            itemId tempItemId;
            str stritemid;
            AviFiles
            SysOperationProgress progress1 = new SysOperationProgress();
            ;
        
        //excel
        define.filename(fileName)
        excel = SysExcelApplication::construct();
        workbooks = excel.workbooks();
        try
        {
        workbooks.open(fileName);
        }
        catch (Exception::Error)
        {
        throw error("File cannot be opened");
        }
       
       
                workbook = workbooks.item(1);
                worksheets = workbook.worksheets();
                worksheet = worksheets.itemFromNum(1);
                cells = worksheet.cells();
                type = cells.item(row+1, 1).value().variantType();
       
         ttsBegin;
       
           while (type != COMVariantType::VT_EMPTY)
        {
            row++;
            tempItemId  = cells.item(Row,1).value().bStr();
           // stritemid = cells.item(Row,1).value().bStr();
            select inventTable where inventTable.ItemId == tempItemId;
            if(inventTable)
            {
            select ecoResProduct where ecoResProduct.DisplayProductNumber == inventTable.ItemId;
            select ecoResProductCategory    where ecoResProductCategory.product == ecoResProduct.RecId;
       
            _CatName  = cells.item(Row,2).value().bStr();
            _Hiername = cells.item(Row,3).value().bStr();
       
            checkEcoResCatH                     = EcoResCategoryHierarchy::findByName(_Hiername);
            checkEcoResCat                      = EcoResCategory::findByName(_CatName,checkEcoResCatH.RecId);
       
            if(!ecoResProductCategory && ecoResProduct && checkEcoResCatH && checkEcoResCat)
                {
                    this.createcategory(tempItemId,_CatName,_Hiername);
                }
            else if (ecoResProductCategory && ecoResProduct && checkEcoResCatH && checkEcoResCat)
                {
                    this.updatecategory(tempItemId,_CatName,_Hiername);
                }
            }
                 type = cells.item(row+1, 1).value().variantType();
        }
            ttsCommit;
        excel.quit();
        }
     
       updatecategory
        Public void updatecategory(Itemid _itemno,EcoResCategoryCommodityCode _CategoryName,EcoResCategoryHierarchyName _name)
        {
       
                 //vikas
            EcoResDistinctProduct  ecoResDistinctProduct;
            EcoResProduct           ecoResProduct;
            EcoResProductTranslation ecoResProductTranslation;
            EcoResProductCategory   ecoResProductCategory;
            EcoResCategory          ecoResCategory;
            EcoResCategoryHierarchy ecoResCategoryHierarchy;
            ecoResCategoryTranslation   ecoResCategoryTranslation;
            //vikas
             //Create Producr Category (Hierarchy)
            select ecoResDistinctProduct where ecoResDistinctProduct.DisplayProductNumber == _itemno;
            Select firstOnly ecoResCategoryHierarchy where ecoResCategoryHierarchy.Name == _name;
       
            while select forupdate ecoResProductCategory where ecoResProductCategory.Product == ecoResDistinctProduct.RecId
            if(ecoResProductCategory)
            {
                ttsBegin;
                //ecoResProductCategory.clear();
                //ecoResProductCategory.initValue();
                ecoResProductCategory.CategoryHierarchy         = ecoResCategoryHierarchy.RecId;
                select * from ecoResCategory where ecoResCategory.Name == _CategoryName;
                ecoResProductCategory.Category                  = ecoResCategory.RecId;
                //ecoResProductCategory.category = ecoResCategoryTranslation.RecId;
                ecoResProductCategory.Product                   = ecoResDistinctProduct.RecId;
                //ecoResProductCategory.VIK_EcoResProductType     = VIK_EcoResProductType::findByProductType(_productType).RecId;
                //ecoResProductCategory.VIK_EcoResSubCategory     = VIK_EcoResSubCategory::findBySubCategory(_subCategory).RecId;
                ecoResProductCategory.update();
                ttsCommit;
                info(strFmt("category for item %1 is updated",_itemno));
            }
       
        }
     
       main
        public static void main(Args _args)
        {
            Vik_ItemCategory_ExcelImport    Vik_ItemCategory_ExcelImport = new Vik_ItemCategory_ExcelImport();
       
            if(curext() == "COMP")
            {
             if(Vik_ItemCategory_ExcelImport.prompt())
                Vik_ItemCategory_ExcelImport.run();
            }
        }
     
    METHODS
  CLASS


***Element: 
Related Posts Plugin for WordPress, Blogger...