Search This Blog

Tuesday, 9 June 2015

Sales Order Creation Service : AX 2012 X++ code

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,
                       comp_SoldToParty _soldToParty,comp_ShipTOParty _shipToParty,SalesPrice _price,CurrencyCode _currency,CustPaymTermId _paymTerm,SalesDlvTermId _delTerm,
                       comp_IncoTerm2 _incoTerm,CustPurchaseOrder _custReq,CustRef _ref,SalesInventLocationId _warehouse,SalesFixedExchRate _exchRate,comp_FOCSpacesOffered _FOCspaces,
                       SalesShippingDateRequested _deliveryDate,Addressing _billTo,Addressing _shipTo,ItemId _item,Str1260 _charname,Str1260 _charvalue,SalesOrderedQty _qty,comp_OrderType _orderType,comp_OrderCat _orderCategory,FormType_IN _saleTypeSalesTax,comp_SaleTypeExciseDuty   _saleTypeExcise,
                        String50 _domestic,String50 _export,String50 _e1Sale,string30 _FOCInformation,string30 _financer,MarkupValue _FOCSpares,MarkupValue _salesDed,
                        MarkUpvalue _depotTransportCost,MarkUpValue _transportCust,MarkupValue _forward,MarkupValue _freight,MarkupValue _addnlCost,MarkUpValue _miscCharges,
                        MarkupValue _extSalesComm,MarkUpvalue _speTax,MarkUpvalue _entTax,MarkupValue _demo,MarkUpValue _freeInsur,MarkUpValue _addnWarrCost,MarkUpValue addnlCredit,
                        MarkUpValue _bucketCost,MarkUpValue _opCharges,MarkUpValue _promo,Markupvalue _dealComm,MarkupValue _percentdisc,MarkUpValue _cashDisc)
{
    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;
}

Wednesday, 27 May 2015

AX 2012 HCM Creating a Worker x++ code

Creating a worker in AX 2012

private HcmPersonnelNumberId nextPersonnelNumberId()
{
    HcmPersonnelNumberId    hcmPersonnelNumberId;
    NumberSequenceReference numberSeqReferencePersonnelNum;
    NumberSequenceTable     numberSeqTablePersonnelNum;
    NumberSeq               numberSeqPersonnelNum;

    // Number Sequence
    numberSeqReferencePersonnelNum  = NumberSeqReference::findReference(extendedTypeNum(HcmPersonnelNumberId));
    numberSeqTablePersonnelNum      = NumberSequenceTable::find(numberSeqReferencePersonnelNum.NumberSequenceId);

    if (numberSeqTablePersonnelNum)
    {
        // generate worker personnel number if number sequence code is created.
        numberSeqPersonnelNum = NumberSeq::newGetNumFromId(numberSeqTablePersonnelNum.RecId, true, true);

        if(numberSeqPersonnelNum)
        {
            hcmPersonnelNumberId = numberSeqPersonnelNum.num();
        }
    }
    return hcmPersonnelNumberId;
}

private void createHCMWorker()
{
    AxDirPerson             person;
    AxDirPersonName         personName;
    HcmWorker               worker;
    HcmPersonnelNumberId    hcmPersonnelNumberId;

    hcmPersonnelNumberId = this.nextPersonnelNumberId();

    if (!hcmPersonnelNumberId)
        return;

    // Create a person
    person = AxDirPerson::construct();
    person.parmName("Santa Claus");
    person.save();

    personName = AxDirPersonName::construct();
    personName.parmPerson(person.dirPerson().RecId);
    personName.parmFirstName(person.dirPerson().Name);
    personName.parmValidTo(DateTimeUtil::maxValue());
    personName.save();

    // Create the worker
    HcmWorkerTransition::newCreateHcmWorker(personName.dirPersonName(), hcmPersonnelNumberId);
}

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

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

Issue while working in Dev Environment

Client crashes very frequently.


Set-AXModelStore -InstallMode



QR Code DAX 2012

static void JobCreateforQRCode(Args _args)
{
    Image           image;
    container       imageContainer;
    str             url;
    EFDocQRCode_BR  qrCode;  
    
    // The url to create the QR code. 
    url = 'http://www.google.com';
    
    // Create an instance of the QR code class
    qrCode = new EFDocQRCode_BR();
    
    // Generate a QR code for the URL and save the result to a container
    imageContainer = qrCode.generateQRCode(url);
    
    // Use AX's good old Image class to load the image from the container
    // and save it as a file
    image = new Image();
    image.setData(imageContainer);
    
    image.saveImage("F:\QrCode.jpg", ImageSaveType::JPG);
}