Tuesday, October 31, 2017

Process AIF in Ax 2012

static void San_ProcessAIF(Args _args)
{
    new AifGatewayReceiveService().run();
    new AifInboundProcessingService().run();
    new AifOutboundProcessingService().run();
    new AifGatewaySendService().run();
}

Project Quotation Sent/Confirm & transfer in AX 2012 (X++)

//Sales Project Quotation Sent/Confirm & transfer in X++

static void SalesProjQuotation(Args _args)
{
    SalesQuotationLine              salesQuotationLine;
    CustQuotationJour               custQuotationJour;
    CustQuotationTrans              locCustQuotationTrans;
    SalesQuotationTable             salesQuotationTable;
    SalesQuotationProjLinkWizard    salesQuotationProjLinkWizard;
    ProjTable                       projTable;
    CustQuotationConfirmJour        custQuotationConfirmJour;
    SalesQuotationTransferToProject salesQuotationTransferToProject;

    #AviFiles
    SysOperationProgress progress = new SysOperationProgress();
    int i;
 //Function to send Project Quotation
void salesProjectQuotationSent(Common _record, DocumentStatus _documentStatus, QuotationDocNum  _quotationDocNum = '')
{
    #define.project('Project')
    SalesQuotationTable             salesQuotationTable;
    SalesQuotationParmTable         salesQuotationParmTable;
    SalesQuotationEditLinesForm     salesQuotationEditLinesForm = SalesQuotationEditLinesForm::construct(_documentStatus, #project, true);
    ParmId                          parmId = salesQuotationEditLinesForm.parmId();

    if (_record)
    {
        if (_record.TableId == tableNum(SalesQuotationTable))
        {
            salesQuotationTable = _record;
            salesQuotationEditLinesForm.initParmSalesQuotationTable(salesQuotationTable);
        }
        salesQuotationEditLinesForm.createParmUpdate();
        salesQuotationEditLinesForm.createParmTable(salesQuotationParmTable, salesQuotationTable);
        salesQuotationParmTable.insert();

        salesQuotationEditLinesForm.callerModuleAxapta(SalesQuotationEditLinesForm::getCallerModuleFromParm(#project));
        salesQuotationEditLinesForm.parmId(parmId);
        salesQuotationEditLinesForm.parmTransDate(systemDateGet());
        salesQuotationEditLinesForm.prePromptInit();
        salesQuotationEditLinesForm.run();
    }
}

    ;
    // Approve Sales Quotations
    ttsBegin;
    update_recordSet salesQuotationTable
        setting QuotationStatus = SalesQuotationStatus::Approved
        where salesQuotationTable.QuotationStatus == SalesQuotationStatus::Created;
    ttsCommit;

    info("Updated to Approved successfully.");

    // Send the Quotation
    ttsBegin;
    while select forUpdate salesQuotationTable
        where salesQuotationTable.QuotationStatus == SalesQuotationStatus::Approved
    {
        salesProjectQuotationSent(salesQuotationTable, DocumentStatus::Quotation);
    }
    ttsCommit;

    info("Updated to Sent successfully.");


    // Confirm and Transfering to Project
    salesQuotationTransferToProject = new SalesQuotationTransferToProject();
    salesQuotationProjLinkWizard =  new SalesQuotationProjLinkWizard ();

    progress = SysOperationProgress::newGeneral(#aviUpdate, 'Confirming Sales Project Quotation.', 1000);

    while select salesQuotationTable
        where salesQuotationTable.QuotationStatus == SalesQuotationStatus::Sent
    {
        infolog.clear();
        projTable.clear();
        salesQuotationLine.clear();
        custQuotationJour.clear();
        custQuotationConfirmJour.clear();

        projTable = ProjTable::find(salesQuotationTable.ProjIdRef, true);

        select firstOnly forUpdate custQuotationJour
                where custQuotationJour.ProjIdRef       == salesQuotationTable.ProjIdRef;

        if(projTable.status().validateConfirmAndTransfer())
        {           
            salesQuotationProjLinkWizard.parmProjTable(projTable);
            salesQuotationProjLinkWizard.parmSalesQuotationTable(salesQuotationTable);
            salesQuotationProjLinkWizard.linkQuotationToProject(projTable.ProjId, projTable.ProjInvoiceProjId);
            salesQuotationProjLinkWizard.linkConfirmationToProject(projTable.ProjId, projTable.ProjInvoiceProjId);

            ttsBegin;
            // update the Sales project Quotation
            salesQuotationProjLinkWizard.parmModelId(ProjParameters::find().ModelId);
            salesQuotationProjLinkWizard.transferForecastToProject();
            salesQuotationProjLinkWizard.transferItemReq();
            salesQuotationProjLinkWizard.updateTransferredToProject(true, true);
            ttsCommit;
        }

        i++;
        progress.incCount();
        progress.setText(strfmt("Sales Project Quotation confirmed: %1", i));
        sleep(100);
    }
}

Posting Project BegBalance in AX 2012

    ProjJournalTable            projJournalTable;
    ProjBegBalJournalCheckPost  projBegBalJournalCheckPost;
    LedgerVoucher               ledgerVoucher;
    JournalTableData            journalTableData;
    ;

    try
    {
        ttsBegin;

        while select forUpdate projJournalTable
                         where projJournalTable.Posted      == NoYes::No &&
                               projJournalTable.JournalType == ProjJournalType::BegBalance
        {
            projBegBalJournalCheckPost = null;
            projBegBalJournalCheckPost = ProjBegBalJournalCheckPost::newJournalCheckPost(false,
                                                            false,
                                                            JournalCheckPostType::Post,
                                                            projJournalTable.TableId,
                                                            projJournalTable.JournalId);

            journalTableData = JournalTableData::newTable(projJournalTable);

            projBegBalJournalCheckPost.postTransLedger(journalTableData.journalTransList().journalTransData(), ledgerVoucher);

        }

        ttsCommit;

        info("Posted successfully.");
    }
    catch
    {
        info("Posting failed.");
    }
}

Get Organisation hierarchies through X++/SQL

In AX 2012

//Project XPO Download link

Organisation Hierarchies

XPO Project Contains,

1) Query - OrganisationHierarchies
2) View - OrganisationHierarchies
3) Job - GetOrgansationalHierarchy

static void  GetOrgansationalHierarchy(Args _args)
{
    //Reference Query : OMHierarchy
    OMHierarchyType OMHierarchyType1;
    OMHierarchyRelationship OMHierarchyRelationship1;
    OMRevisionEdit OMRevisionEdit1; //check this too
    OMInternalOrganization  omInternalOrganizationP,omInternalOrganizationC;
    OMOperatingUnit  omOperatingUntInt;
 
    //Function to Clear
    void clearBuffer()
    {
        OMHierarchyType1.clear();
        omInternalOrganizationP.clear();
        omInternalOrganizationC.clear();
        omOperatingUntInt.clear();
        OMRevisionEdit1.clear();
        OMHierarchyRelationship1.clear();
    }
    ;
    clearBuffer();
    while select Name,RecId
                from OMHierarchyType1
    {
        while select HierarchyType,ParentOrganization,ChildOrganization
                from  OMHierarchyRelationship1
            where OMHierarchyRelationship1.HierarchyType == OMHierarchyType1.RecId
                    && OMHierarchyRelationship1.ParentOrganization != 0
               outer join  omInternalOrganizationP //Parent Organization
                     where omInternalOrganizationP.RecId == OMHierarchyRelationship1.ParentOrganization
                outer join omInternalOrganizationC //Child Organization
                    where omInternalOrganizationC.RecId == OMHierarchyRelationship1.ChildOrganization
                outer join omOperatingUntInt // Operating unit Type
                    where omOperatingUntInt.PartyNumber == omInternalOrganizationC.PartyNumber
                 
        {
            info(strFmt("Org,%1,%2,%3,%4",OMHierarchyType1.Name,
                                   omInternalOrganizationP.Name,
                                   omInternalOrganizationC.Name,
                                   omOperatingUntInt.OMOperatingUnitType
                                   ));
        }
    }
}


In SQL

SQL Script Query

CREATE VIEW vORGANISATIONHIERARCHIES
AS
SELECT
T1.NAME AS HIERARCHYNAME,
T2.CHILDORGANIZATION AS CHILDORGANIZATION,
T2.PARENTORGANIZATION AS PARENTORGANIZATION,
T2.HIERARCHYTYPE AS HIERARCHYTYPE,
T3.NAME AS PARENT,
T4.NAME AS CHILD,
T5.OMOPERATINGUNITTYPE AS ChildOMOPERATINGUNITTYPE,
T5.OMOPERATINGUNITNUMBER AS ChildOMOPERATINGUNITNUMBER,
T6.OMOPERATINGUNITNUMBER AS ParentOMOPERATINGUNITNUMBER,
T6.OMOPERATINGUNITTYPE AS ParentOMOPERATINGUNITTYPE
FROM OMHIERARCHYTYPE T1
CROSS JOIN OMHIERARCHYRELATIONSHIP T2
LEFT OUTER JOIN DIRPARTYTABLE T3
ON (T2.PARENTORGANIZATION=T3.RECID)
LEFT OUTER JOIN DIRPARTYTABLE T4
ON (T2.CHILDORGANIZATION=T4.RECID)
LEFT OUTER JOIN DIRPARTYTABLE T5
ON ((T4.RECID=T5.RECID)
AND (T5.INSTANCERELATIONTYPE IN (2377) ))
LEFT OUTER JOIN DIRPARTYTABLE T6
ON ((T3.RECID=T6.RECID)
AND (T6.INSTANCERELATIONTYPE IN (2377) ))
 WHERE ( NOT ((T2.PARENTORGANIZATION=0))
AND (T1.RECID=T2.HIERARCHYTYPE))

Thursday, October 26, 2017

Import Currency Exchange Rates in Dynamics AX


\\Input
Parm Class

CurrencyCode                fromCurrencyCode;
CurrencyCode                toCurrencyCode;
TransDate                   exchangeRateDate;
CurrencyExchangeRate        exchangeRate;
ExchangeRateTypeRecId       exchangeRateTypeRecId;
ExchangeRateDisplayFactor   exchangeRateDisplayFactor;

fromCurrencyCode = CompanyInfo::standardCurrency();
exchangeRateType            = "Default";
exchangeRateTypeRecId = ExchangeRateType::find(exchangeRateType).RecId;
updateExchangeRates         = Noyes::yes;
exchangeRateDisplayFactor   = ExchangeRateDisplayFactor::One;

Table: ExchangeRate
Table Method
/// <summary>
/// Imports an exchange rate between the from currency and the accounting currency for the default
/// exchange rate type.
/// </summary>
/// <param name="_fromCurrencyCode">
/// The from currency.
/// </param>
/// <param name="_toCurrencyCode">
/// The to currency.
/// </param>
/// <param name="_exchangeRateTypeRecId">
/// The exchange rate type ID.
/// </param>
/// <param name="_exchangeRateDate">
/// The exchange rate date.
/// </param>
/// <param name="_exchangeRate">
/// The exchange rate.
/// </param>
/// <param name="_insertExchangeRate">
/// A Boolean value that determines whether to insert exchange rates.
/// </param>
/// <param name="_updateExchangeRate">
/// A Boolean value that determines whether to update exchange rates.
/// </param>
/// /// <param name="_exchangeRateDisplayFactor">
/// An exchange rate display factor
/// </param>
public static void importExchangeRate(
    CurrencyCode _fromCurrencyCode,
    CurrencyCode _toCurrencyCode,
    ExchangeRateTypeRecId _exchangeRateTypeRecId,
    TransDate _exchangeRateDate,
    CurrencyExchangeRate _exchangeRate,
    boolean _insertExchangeRate,
    boolean _updateExchangeRate,
    ExchangeRateDisplayFactor _exchangeRateDisplayFactor = 0)
{
    ExchangeRateCurrencyPair exchangeRateCurrencyPair;
    ExchangeRate exchangeRate;
    ;
    date exchangeRateDate = _exchangeRateDate;
    ttsbegin;
    if (_insertExchangeRate || _updateExchangeRate)
    {
        select RecId from exchangeRateCurrencyPair
            where exchangeRateCurrencyPair.FromCurrencyCode == _fromCurrencyCode
                && exchangeRateCurrencyPair.ToCurrencyCode == _toCurrencyCode
                && exchangeRateCurrencyPair.ExchangeRateType == _exchangeRateTypeRecId;
        if (exchangeRateCurrencyPair)
        {
            select firstonly forupdate validtimestate(exchangeRateDate) ExchangeRate from exchangeRate
                where exchangeRate.ExchangeRateCurrencyPair == exchangeRateCurrencyPair.RecId
                    && exchangeRate.ValidFrom == exchangeRateDate;
        }
        if (exchangeRate)
        {
            if (_updateExchangeRate)
            {
                exchangeRate.ExchangeRate = _exchangeRate;
                exchangeRate.update();
            }
        }
        else
        {
            if (_insertExchangeRate)
            {
                if (!exchangeRateCurrencyPair)
                {
                    exchangeRateCurrencyPair.FromCurrencyCode = _fromCurrencyCode;
                    exchangeRateCurrencyPair.ToCurrencyCode = _toCurrencyCode;
                    exchangeRateCurrencyPair.ExchangeRateType = _exchangeRateTypeRecId;
                 
                    if (_exchangeRateDisplayFactor)
                    {
                        exchangeRateCurrencyPair.ExchangeRateDisplayFactor = _exchangeRateDisplayFactor;
                    }
                 
                    exchangeRateCurrencyPair.insert();
                }
                exchangeRate.clear();
                exchangeRate.ExchangeRateCurrencyPair = exchangeRateCurrencyPair.RecId;
                exchangeRate.ExchangeRate = _exchangeRate;
                exchangeRate.ValidFrom = _exchangeRateDate;             
                if (_exchangeRateDisplayFactor)
                {
                    exchangeRateCurrencyPair.ExchangeRateDisplayFactor = _exchangeRateDisplayFactor;
                }             
                exchangeRate.insert();
            }
        }
    }
    ttscommit;
}

Wednesday, October 25, 2017

Multiselect lookup in form Datasource fields in AX 2012

// Multi select lookup in form Data source fields in AX 2012

Note: This will not work for Dynamic string control in FORM


Class declaration
SysLookupMultiSelectCtrl    msCtrl;

Init
SysLookupMultiSelectCtrl::construct(element, <control name>, querystr(<queryName>));

Properties
string control auto declaration property set to Yes

SysLookupMultiSelectCtrl class
Method -> Init
//Function
boolean isOnGrid(FormStringControl _ctrl)
    {
        FormControl     parentControl;
        FormControl     currentControl;
        boolean         retValue;
        currentControl  = _ctrl;
        retValue        = false;
        while(currentControl.parentControl() && !retValue)
        {
            parentControl = currentControl.parentControl();
            if(parentControl is FormGridControl)
                retValue = true;
            else
                currentControl = currentControl.parentControl();
        }
        return retValue;
    }
;
     if(isOnGrid(fsCtrlNames))
    {
        fsCtrlNames.registerOverrideMethod('modified', 'ctrlNames_textChange', this);
    }
    else
    {
        fsCtrlNames.registerOverrideMethod('textChange', 'ctrlNames_textChange', this);
    }

Method -> ctrlNames_textChange
 FormDataSource      fds;
    Common              anyBuffer;
    _fsCtrlNames.text(fsCtrlNamesTmp.text());
    fds = _fsCtrlNames.dataSourceObject();
    if(fds)
    {
        anyBuffer = fds.cursor();
        anyBuffer.(_fsCtrlNames.dataField()) = fsCtrlNamesTmp.text();
        fds.refresh();
    }
    fsCtrlNames.modified();


Other Reference: https://krishhdax.blogspot.in/2015/06/editable-multi-select-lookup-in-grid.html

Friday, October 13, 2017

Encrypt and Decrypt in SQL

declare @encrypt varbinary(20)
select @encrypt = EncryptByPassPhrase('key', 'admin@1234' )
select @encrypt
select convert(varchar(100),DecryptByPassPhrase('key', @encrypt ))

//Encryption and Decryption in AX 2012

https://sangeethwiki.blogspot.in/2014/11/encrypt-and-decrypt-string-in-ax-2012.html

Using SQLPackage to import or export Azure SQL DB

Reference Source Link:

https://blogs.msdn.microsoft.com/azuresqldbsupport/2017/01/31/using-sqlpackage-to-import-or-export-azure-sql-db/

Purpose:

Explain how to easily and quickly use SQLPackage to import or export your Azure SQL Database.

Locating the SQLPackage.exe:

The SQLPackage.exe is part of the DacFramework which installed with SSMS or with SQL Server Data Tools
Or you can download only the DacFramework if you do not have already the management tools
Once the DacFramework / SSMS / SSDT is installed you can locate the SQLPackage.exe in this path
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin
* Change the drive letter if you installed it to different location.

Export from Azure SQL DB to bacpac file:

to export database from your Azure SQL DB to bacpac file use this command:
sqlpackage.exe /Action:Export /ssn:tcp:<ServerName>.database.windows.net,1433 /sdn:<DatabaseName> /su:<UserName> /sp:<Password> /tf:<TargetFile> /p:Storage=File

example:

sqlpackage.exe /Action:Export /ssn:tcp:MyOwnServer.database.windows.net,1433 /sdn:AdventureWorks /su:AdminUser /sp:AdminPassword1 /tf:C:\Temp\AW.bacpac /p:Storage=File

Import from bacpac file to Azure SQL DB:

to import database from bacpac file to your Azure SQL DB use this command:
sqlpackage.exe /Action:Import /tsn:tcp:<ServerName>.database.windows.net,1433 /tdn:<TargetDatabaseName> /tu:<UserName> /tp:<Password> /sf:<Path to bacpac file> /p:DatabaseEdition=Premium /p:DatabaseServiceObjective=P4 /p:Storage=File

example:

import database to default target service tier S0:
sqlpackage.exe /Action:Import /tsn:tcp:MyServer.database.windows.net,1433 /tdn:AdventureWorks /tu:AdminUser /tp:AdminPassword1 /sf:C:\temp\AW.bacpac /p:Storage=File
import database and set target service tier to P2
sqlpackage.exe /Action:Import /tsn:tcp:MyServer.database.windows.net,1433 /tdn:AdventureWorks /tu:AdminUser /tp:AdminPassword1 /sf:C:\temp\AW.bacpac /p:DatabaseEdition=Premium /p:DatabaseServiceObjective=P2 /p:Storage=File

Remarks:

  • /p:Storage=File : is used to redirect the backing storage for the schema model used during extraction, this helpful with large databases that may cause out-of-memory exception if the default memory location is used.
  • Note that for large databases its recommended to set the service tier during the import, this help import process to run faster.
  • When exporting from active database, the database may not be transactional consistent as this process go object by object. If transactional consistent is needed it's recommended to export from copied database. (learn how to copy Azure SQL DB)
    (thanks to ErikEJ for his comment)

Migrate your SQL Server database to Azure SQL Database

Thursday, October 12, 2017

Tuple in Python


Tuple: like as container or array

Sample:
Tuple:
tup1 = ('Sangeeth', 'chennai','1309','gowtham',1990', '2000','0406');
tup2 = (1,2,3,4,5,6,7,8);
print  tup1[1]
print  tup2[3:5]

output:
chennai
3,4,5

String:
var1 = "sangeeth"
var2 = "gowtham"
print var1[0]

print var2[0:3]

output:
s
gow


Packing and Unpacking

Sample:

x = ("Sangeeth", chennai, "madurai")    # Tuple packing code
(me, where, too) = x    # Tuple unpacking Code
print me
print where
print to

Output
Sangeeth
chennai
madurai

Comparison Operator
A comparison operator in Python can work with tuples.It starts with comparing the first element from each of the tuples

Sample:
a=(3,8)
b=(2,4)
if (a>b):print "a is bigger"
else: print "b is bigger"
    
a=(4,7)
b=(4,3)
if (a>b):print "a is bigger"
else: print "b is bigger"
    
a=(2,3)
b=(4,1)
if (a>b):print "a is bigger"
else: print "b is bigger"

Built In Function
all(), any(), enumerate(), max(), min(), sorted(), len(), tuple(), etc.


Skip Inventory reservation on Sales order lines in D365FO

[ExtensionOf(classStr(InventUpd_Reservation))] final class InventUpd_ReservationCls_SAN_Extension {     void updateNow()     {         if(mo...