Monday, August 28, 2017

Usefull Query information (SQL and AX)

//Usefull Query information (SQL and AX)
--Check the Microsoft Dynamics AX Kernel and Application versions installed with the restored database.
select * from SYSSETUPLOG where DESCRIPTION = 'finished' order by CREATEDDATETIME desc

select * from SYS.sysprocesses --Query get to Some blocked object information
sp_GetNextRecId - genearte next recid seq
select * from SystemSequences - check next RecId seq for specific table
select * from modelElement where Name = 'objectname' --based on element type, Query will return are parent and root object in ax
select * from ElementTypes - Related objects in AX

--The record returned at the top of the list indicates the last time the setup or upgrade checklist was run, note the APPBUILD and KERNELBUILD versions.
select distinct(KERNELBUILD) from SYSSETUPLOG
select * from SysLastValue -- AX usage data records
select * from sysClientSessions - AX login user list
select * from sysServerSessions - AX server login list
select SID, Networkdomain, networkalias from userinfo where networkalias = 'Admin' --user information records
select * from SysBCProxyUserAccount
select * from SysWorkflowParameters
select * from SysServerConfig
select * from BatchServerConfig
select * from SysClusterConfig
select * from BatchGroup
select * from Batch
update batch set SERVERID = '<01@NewAOS>' where serverid = '<02@OldAOS>'
update sysserverconfig set enablebatch = 1 where serverid = '<01@NewAOS>'
update BATCHSERVERCONFIG set SERVERID = '<01@NewAOS>' where serverid = '<02@OldAOS>'
select * from SYSEMAILPARAMETERS
select * from SYSEMAILSMTPPASSWORD
select * from SYSGLOBALCONFIGURATION
select * from SysFileStoreParameters
select * from BIANALYSISSERVER
select * from BICONFIGURATION
select * from SRSSERVERS
select * from EPGLOBALPARAMETERS
select * from EPWEBSITEPARAMETERS
select * from COLLABSITEPARAMETERS
select * from SYNCPARAMETERS
select * from AIFWEBSITES
select * from SysSQMSettings
AxUpdatePortal -listvirtualservers
AxUpdatePortal -redeploy [-updatewebsites] [-iisreset]
AxUpdatePortal -deploy [-createsite] -websiteurl <value>
AxUpdatePortal -createsite -websiteurl <value>
AxUpdatePortal -updateall -websiteurl <value>
AxUpdatePortal -proxies -websiteurl <value>
AxUpdatePortal -images -websiteurl <value>
AxUpdatePortal -updatewebcomponent -treenodepath <value>  -websiteurl <value>

//DB backup script
DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(100) -- used for file name
Declare @fullpath nvarchar(250)
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name IN (
'AXDB_BI1',
'AXDB_BI1_model',
'AXDB_DEV1',
'AXDB_DEV1_model'
)

SET @path = 'F:\AzureShare\SQL_Backup\';
OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name 
WHILE @@FETCH_STATUS = 0 
BEGIN 
       SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)                        
       SET @fileName = @name +'_'+@fileDate +'.BAK'
       SET @fullpath=@path+@fileName;
       SET @fileDate=''''+@fileName+'''Full Backup';
       print @name
       Backup Database @name TO
                   DISK=@fullpath
       WITH NOFORMAT,NOINIT,
                   NAME=@fileDate,
                   SKIP,NOREWIND,NOUNLOAD,STATS=10
      
       FETCH NEXT FROM db_cursor INTO @name 
END 
CLOSE db_cursor 
DEALLOCATE db_cursor
//Shrinking DB ax 2012
USE MicrosoftDynamicsAX;
ALTER DATABASE DBNAME
SET RECOVERY SIMPLE;
DBCC SHRINKFILE (DBNAME_Log, 0);
ALTER DATABASE DBNAME
SET RECOVERY FULL;
//Finding Modified Element in SQL DB model
select E.[Name] as [Element Name],
EY.[ElementTypeName] as [Element Type],
E1.[Name] as [Root Element Name],
EY1.[ElementTypeName] as [Root Element Type],
ED.[LayerId],
L.[Name] as [Layer Name],
ED.[MODIFIEDDATETIME],
ED.[MODIFIEDBY],
ED.[CREATEDDATETIME],
ED.[CREATEDBY],
ED.[ElementVersion],
ED.[ModelId]
from [ModelElement] as E
inner join [ModelElementData] as ED on E.[ElementHandle] = ED.[ElementHandle]
inner join [ModelElement] as E1 on E1.[ElementHandle] = E.[RootHandle]
inner join [ElementTypes] as EY on EY.[ElementType] = E.[ElementType]
inner join [ElementTypes] as EY1 on EY1.[ElementType] = E1.[ElementType]
inner join [Layer] as l on l.[Id] = ED.[LayerId]
where ED.[LayerId] = 10
//Get Server /DB/ Domain name in x++
    str               database,servername;
   InteropPermission   permission;
    str                 userName;
    str                 userDomain;
    ;
    database        =   SysSQLSystemInfo::construct().getloginDatabase();
    servername   =   SysSQLSystemInfo::construct().getLoginServer();
    info(strFmt("ServerName - %1  Data Base -- %2",servername,database));
   
    permission = new InteropPermission(InteropKind::ClrInterop);
    permission.assert();
    userDomain  = System.Environment::get_UserDomainName();
    userName    = System.Environment::get_UserName();
    info(strFmt(@"%1\%2", userDomain, userName));
//Ax Build in AX 2012
Delete Log file fromt his Folder Path:
C:\Users\administrator.FCCI\Microsoft\Dynamics Ax\Log
C:\Program Files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\Log
Cmd
//C:\Program Files (x86)\Microsoft Dynamics AX\6.0\Client\Bin
C:\Program Files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\bin
To Start AX build
axbuild.exe  xppcompileall  /s=01 /altbin="C:\Program Files (x86)\Microsoft Dynamics AX\6.0\Client\Bin"
axbuild.exe  xppcompileall  /s=01

// Deploy POS Report AX
Retail > Periodic > Data distribution > Distribution schedule.
Select job, click Run
//Deploy EP Pages
cd C:\Program Files\Microsoft Dynamics AX\60\Setup
AxUpdatePortal -updateWebSites -iisreset -verbose > "C:\EPUpdate.log"
//Deploy ssrs Reprot in Management shell
open Dynamics ax 2012 management shell run as administrator
Get-AXReport -ReportName *
Publish-AXReport –Id SSRSConfigID -ReportName ReportName,Report
Publish-AXReport –Id SSRSConfigID –ReportName *
Publish-AXReport –ReportName *

Create Field and Field Group in AX 2012 Tables

    TreeNode        treeNode = TreeNode::findNode(@'\\Data Dictionary\Tables\Table1\');
    SysDictClass    sysDictClass = new SysDictClass(treeNode.applObjectId());
    FormRun         formRun = new FormRun(new Args(formStr(AifAction)));
    Form            form = new Form(formStr(AifAction));
    ClassBuild      classBuild;
    SysDictTable    sysDictTable = new SysDictTable(tableNum(table1)); // Maps are treated like tables
    SysDictMethod   sysDictMethod;
    int             i;
    AOTTableFieldList fieldList;
    MemberFunction  method;
    str             methodSource = 'public static str getTime()\n{\n\treturn "3/3/2015";\n}';
    treeNode = sysDictTable.treeNode().AOTfindChild('field Groups').AOTadd('getTime1');
    method = sysDictTable.treeNode().AOTfindChild('field Groups').AOTfindChild('getTime1').AOTadd('mobile');
    method.AOTsave();
    method.AOTsetSource(methodSource, true);
    method.AOTsave();
   
    if (sysDictTable.treeNode().AOTcompile())
    {
        sysDictTable.treeNode().AOTsave();
        info(strFmt("Added"));
    }

Data and tables Recover in SQL from Transaction Log and LSNs

//Data and tables Recover in SQL from Transaction Log and LSNs
//Note:If it is DB backup is not available means
https://www.mssqltips.com/sqlservertip/3160/recover-deleted-sql-server-data-and-tables-with-the-help-of-transaction-log-and-lsns/
https://www.experts-exchange.com/articles/28199/How-to-recover-deleted-rows-in-SQL-Server.html
//if it not DB sync after dropped out tables use this.
http://dev.goshoom.net/en/2011/11/id-change/
https://solutioncenter.apexsql.com/how-to-recover-a-single-table-from-a-sql-server-database-backup/

Get Report to Position

HcmPositionRecId                        SelfPosition;
HcmPositionHierarchy                    PositionHierarchy;
uctdatetime utcDT = dtatimeutlill::;
SelfPosition = HcmPositionWorkerAssignment::find(HcmWorkerPrimaryPosition::findByWorker(HcmWorker::findByPerson("current person").RecId).PositionAssignment).Position;
    select validTimeState(utcDT) PositionHierarchy
    where PositionHierarchy.Position  == SelfPosition  && PositionHierarchy.PositionHierarchyType != 0;
    report to postion = HcmWorker::find(HcmWorkerPrimaryPosition::findByPositionAssignment(HcmPositionWorkerAssignment::findByPosition(PositionHierarchy.ParentPosition).RecId).Worker).Person;

Title in EP web Page

ITitleProvider titleProvider = AxBaseWebPart.GetWebpart(this) as ITitleProvider;
    // Specify the title to pass as the AxPageTitle
    titleProvider.Caption = "Page title goes here";
    // Do not include the context in the title
    titleProvider.ShowContext = false;

Get Excel cell value in common

anytype getExcelCellValue(int _row,
                          int _col)
{
    COMVariantType  comVariantType;
    SysExcelCells               cells;
    anyType retVal;
    ;
    comVariantType    = cells.item(_row, _col).value().variantType();
    switch (comVariantType)
    {
        case COMVariantType::VT_BSTR  :
            retVal = cells.item(_row, _col).value().bStr();
            break;
        case COMVariantType::VT_R8    :
            retVal = cells.item(_row, _col).value().double();
            break;
        case COMVariantType::VT_INT    :
            retVal = cells.item(_row, _col).value().int();
            break;
        case COMVariantType::VT_DATE  :
            retVal = cells.item(_row, _col).value().date();
            break;
        case COMVariantType::VT_EMPTY :
            retVal = cells.item(_row, _col).value().bStr();
            break;
        default :
            retVal = "";
            break;
    }
    return retVal;
}

Ledger dimension in to Table and FORM

//Addding Ledger dimension in to Table and FORM
//Table
//Table1
//Drag -> ledgerDimensionAccount EDT to Table1
//Field Named as Accountledger
//Relations - Normal - DimensionAttributeValueCombination(RecId) -- Table1(NewFieldName)
//Form
->Class Declaration
LedgerDimensionDefaultAccountController AccountController;
->Init
AccountController                 = LedgerDimensionDefaultAccountController::construct(Table1_ds, fieldStr(Table1, Accountledger));
AccountController.parmControl(Group_AccountLedger);
AccountController.parmFilterLedgerPostingType(LedgerPostingType::None);
->Datasource(Table1)-Field(Accountledger)-Method-
public Common resolveReference(FormReferenceControl _formReferenceControl)
{
    return AccountController.resolveReference();
}
-> Design Group Control - field - Overide Method
public void jumpRef()
{
    AccountController.jumpRef();
}
public void loadAutoCompleteData(LoadAutoCompleteDataEventArgs _e)
{
    AccountController.loadAutoCompleteData(_e);
    super(_e);
}
public void loadSegments()
{
    super();
    AccountController.loadSegments();
}
public void segmentValueChanged(SegmentValueChangedEventArgs _e)
{
    super(_e);
    AccountController.segmentValueChanged(_e);
}
public boolean validate()
{
    boolean isValid;
    isValid = super();
    isValid = AccountController.validate() && isValid;
    return isValid;
}

Get Month List

MonthListTmp GetMonthyearList()
{
    MonthListTmp   listMonthYearTmp;
    int i,j,k,l,m,n;
    ;
    k = mthOfYr(fromdate);
    l = year(fromdate);
    m = mthOfYr(todate);
    n = year(todate);
    delete_from listMonthYearTmp;
    for (i=k;i<=12;i++)
    {
        listMonthYearTmp.clear();
        listMonthYearTmp.Month = i;
        listMonthYearTmp.year = l;
        listMonthYearTmp.insert();
        if(m == i && l == n)
            break;
        if(i==12)
        {
            i=0;
            l = l+1;
        }
    }
    return listMonthYearTmp;
}

Workflow in Enterprise Portal

https://msdn.microsoft.com/en-us/library/ee677494.aspx

ODATA with DAX 365 Operations

https://us.hitachi-solutions.com/blog/how-to-access-dynamics-365-for-operations-data-entities-using-odata-protocol-and-net/
https://docs.microsoft.com/en-us/dynamics365/unified-operations/dev-itpro/data-entities/odata

Get voucher Transactions Original documents

Originaldocuments           originaldocuments;
    TmpLedgerBase               tmpLedgerBase;
    Common                      common;
    GeneralJournalAccountEntry  accountEntry;
    LedgerTransModule           ledgerTransModule;
    ;
    accountEntry = GeneralJournalAccountEntry::find(this.RecId,false);
    common = accountEntry;
    //Consider first - original documents
    originaldocuments   = new Originaldocuments(common);
    originaldocuments.findRelations();
    tmpLedgerBase.setTmpData(originaldocuments.relations());
   
    if(!tmpLedgerBase)//if it Original Document is not There means  - then as per requested considering Transaction Origin
    {
        ledgerTransModule=new LedgerTransModule();
        ledgerTransModule.createTransModule(accountEntry.RecId);
        tmpLedgerBase.setTmpData(ledgerTransModule.transModule());
    }
    return tmpLedgerBase;

SQL query to identify Modified objects

select top 10000 (select top 1  name from ModelElement where ModelElement.ElementHandle = ModelElementData.ElementHandle),
(select top 1  name from ModelElement where ModelElement.RootHandle = ModelElementData.ElementHandle),
(select top 1  name from ModelElement where ModelElement.ElementHandle =ModelElementData. ParentHandle),
(select top 1  name from ModelElement where ModelElement.RootHandle = ModelElementData.ParentHandle),
MODIFIEDDATETIME,*
 from ModelElementData where  layerid=14 order by ModelElementData.MODIFIEDDATETIME desc 

Get Parm DP Query in Controller Class

this.parmReportContract().parmQueryContracts().lookup(this.getFirstQueryContractKey())

Build and deploy scripts for Microsoft Dynamics AX 2012

//Build and deploy scripts for Microsoft Dynamics AX 2012
https://gallery.technet.microsoft.com/scriptcenter/Build-and-deploy-for-b166c6e4
https://marketplace.visualstudio.com/items?itemName=SDK4NET.AxBuildTools
http://dynamicsaxadmin.codeplex.com
http://dynamicsaxbuild.codeplex.com/
http://dev.goshoom.net/en/2012/01/in-place-build-script-2/

Sales Order Posting Custom Validations

//Sales Order Posting Custom Validations
Validate code
SalesTable
-->  Classes -> SalesFormLetterProvider -> checkHeading()
SalesLine
--> Classes -> SalesFormLetterProvider -> checkLines()

Get Table Field Name and Field Properties AX 2012

//Get Table Field Name and Field Properties AX 2012

SysDictTable    dictTable = new SysDictTable(tableNum(yourTable));
    SysDictField    dictField;
    TreeNode        treeNode;
    TmpTable     tempTableChk;
    FieldId         fieldId = dictTable.fieldNext(0);
    while (fieldId)
    {
        dictField = dictTable.fieldObject(fieldId);
        if (dictField.isSql() && !dictField.isSystem() && dictField.name() != "Modified")
        {
            treeNode = dictField.treeNode();
            tempTableChk.Field = dictField.name();
            tempTableChk.Label = treeNode.AOTgetProperty("Label");
            tempTableChk.insert();
        }
        fieldId = dictTable.fieldNext(fieldId);
    }

Error : Invalid data container type. (AIF)

//Error : Invalid data container type. (AIF)
Resolution
Class : AfStronglyTypedDataContainer
Do Compile Forward

Correct product receipt Purchase order in X++

//Correct product receipt Purchase order in X++
static void CorrectPurchOrderPackingSlip(Args _args)
{
    PurchFormLetter         purchFormLetter;
    PurchFormletterParmData purchFormLetterParmData;
    PurchParmUpdate         purchParmUpdate;
    PurchParmTable          purchParmTable;
    PurchParmLine           purchParmLine;
    PurchTable              purchTable;
    PurchLine               purchLine;
    PurchId                 purchId;
    Num                     packingSlipId;
    VendPackingSlipJour     vendPackingSlipJour;
    VendPackingSlipTrans    vendPackingSlipTrans;
    ;
    purchId       = "CBS-000188";
    packingSlipId = "PS-188-1";
    purchTable = PurchTable::find(purchId);
    select * from vendPackingSlipJour
        where vendPackingSlipJour.PurchId == purchId
            && vendPackingSlipJour.PackingSlipId == packingSlipId;
    ttsBegin;
    purchFormLetterParmData = PurchFormletterParmData::newData(
        DocumentStatus::PackingSlip,
        VersioningUpdateType::Correction);
    purchFormLetterParmData.parmOnlyCreateParmUpdate(true);
    purchFormLetterParmData.createData(false);
    purchParmUpdate = purchFormLetterParmData.parmParmUpdate();
    purchParmTable.clear();
    purchParmTable.TransDate             = SystemDateGet(); //need to mention Required date
    purchParmTable.Ordering              = DocumentStatus::PackingSlip;
    purchParmTable.ParmJobStatus         = ParmJobStatus::Waiting;
    purchParmTable.ParmId                = purchParmUpdate.ParmId;
    purchParmTable.Num                   = packingSlipId;
    purchParmTable.ReCalculate           = true;
    purchParmTable.PurchId               = purchTable.PurchId;
    purchParmTable.PurchName             = purchTable.PurchName;
    purchParmTable.DeliveryName          = purchTable.DeliveryName;
    purchParmTable.OrderAccount          = purchTable.OrderAccount;
    purchParmTable.InvoiceAccount        = purchTable.InvoiceAccount;
    purchParmTable.CurrencyCode          = purchTable.CurrencyCode;
    purchParmTable.DeliveryPostalAddress = purchTable.DeliveryPostalAddress;
    purchParmTable.VendPackingSlipJour   = vendPackingSlipJour.RecId;
    purchParmTable.insert();
    while select purchLine
        where purchLine.PurchId == purchTable.purchId
    {
        select * from vendPackingSlipTrans
            where vendPackingSlipTrans.OrigPurchid == purchLine.PurchId
                && vendPackingSlipTrans.PurchaseLineLineNumber == purchLine.LineNumber;
        purchParmLine.ParmId = purchParmTable.ParmId;
        purchParmLine.TableRefId = purchParmTable.TableRefId;
        purchParmLine.InitFromPurchLine(purchLine);
        purchParmLine.ReceiveNow = 200; //Qty
        purchParmLine.modifiedReceiveNow();
        purchParmLine.PreviousReceiveNow = vendPackingSlipTrans.Qty;
        purchParmLine.PreviousInventNow = vendPackingSlipTrans.InventQty;
        purchParmLine.setQty(DocumentStatus::PackingSlip, false);
        purchParmLine.setLineAmount();
        purchParmLine.insert();
    }
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PackingSlip);
    purchFormLetter.parmVersioningUpdateType(VersioningUpdateType::Correction);
    purchFormLetter.purchParmUpdate(purchFormLetterParmData.parmParmUpdate());
    purchFormLetter.parmCallerTable(vendPackingSlipJour);
    purchFormLetter.parmParmTableNum(purchParmTable.ParmId);
    purchFormLetter.parmId(purchParmTable.ParmId);
    purchFormLetter.specQty(PurchUpdate::ReceiveNow);
    purchFormLetter.transDate(systemDateGet());
    purchFormLetter.proforma(false);
    purchFormLetter.run();
    ttsCommit;
}

Cancel product receipt journal in X++

//Cancel product receipt journal in X++
static void CancelPOPackingSlip(Args _args)
{
    PurchTable           purchTable = PurchTable::find("CBS-000187");
    VendPackingSlipJour  vendPackingSlipJour;
    PurchFormLetter      purchFormLetter;
    ;
    select * from vendPackingSlipJour  where vendPackingSlipJour.PackingSlipId == "PS-187-1";
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PackingSlip);
    PurchFormLetter.parmVersioningUpdateType(VersioningUpdateType::Cancel);
    PurchFormLetter.parmCallerTable(vendPackingSlipJour);
    PurchFormLetter.allowEmptyTable(true);
    PurchFormLetter.initAllowEmptyTable(true);
    PurchFormLetter.multiForm(true);
    purchFormLetter.update( purchTable, 
        vendPackingSlipJour.PackingSlipId, 
        VendPackingSlipJour.DeliveryDate,
        PurchUpdate::ReceiveNow,
        AccountOrder::None,
        NoYes::No,
        NoYes::No,
        NoYes::Yes);
}

Process AIF Gateway Queue in X++

//Process AIF Gateway Queue in X++
static void AXProcessAIFQueue(Args _args)
{
    // Inbound
    new AifGateWayReceiveService().run();       // read the messages
    new AifInboundProcessingService().run();    // process the messages in queue
    // Outbound
    new AifOutboundProcessingService().run();   // process messages in queue
    new AifGateWaySendService().run();          // send messages
}

AIF Document Service Outbound Message trigger in X++

//AIF Document Service Outbound Message trigger in X++
//Trigger outbound message through AIF document service
static void sendOutMsg(XMLDocPurpose _xMLDocPurpose,AifSendMode   _aifSendMode = AifSendMode::Async)
{
    AxdSendContext    axdSendContext = AxdSendContext::construct();
    AifEntityKey      aifEntityKey = AifEntityKey::construct();
    AifConstraintList aifConstraintList = new AifConstraintList();
    AifConstraint     aifConstraint = new AifConstraint();
    VendTable         vendTable;
    Map               keyData;
   
    vendTable = VendTable::find("V05000");
   
    keyData = SysDictTable::getKeyData(vendTable);
    aifEntityKey.parmTableId(vendTable.TableId);
    aifEntityKey.parmRecId(vendTable.RecId);
    aifEntityKey.parmKeyDataMap(keyData);
    axdSendContext.parmXMLDocPurpose(_xMLDocPurpose);
    axdSendContext.parmSecurity(false);
    aifConstraint.parmType(AifConstraintType::NoConstraint);
   
    aifConstraintList.addConstraint(aifConstraint);
    AifSendService::submitDefault(
        classnum(VendVendTableService),
        aifEntityKey,
        aifConstraintList,
        _aifSendMode,
        axdSendContext.pack());
}

DIXF - cross company Data import Ax 2012

//DIXF - cross company Data import Ax 2012
//Example for Customer Entity
Step -1
-->Add new field AXCompany to DMFCustomerEntity table
 --> set the properties as follows
  -->Mandatory - Yes
  -->AllowEdit - No
Step -2
-->Add new method existsAXCompany to CustTable table
 -->Code
  static server boolean existsInCompany(
    CustAccount _custAccount,
     DataAreaId _dataAreaId)
  {
       boolean found;
       changeCompany(_dataAreaId)
       {
           found = (select firstonly RecId from CustTable
                 index hint AccountIdx
                           where custTable.AccountNum == _custAccount).RecId != 0;
       }
       return found;
  }
Step -3
-->Customize method insertUpdate of class DMFCustomerEntityClass
 --> Code
public Common insertUpdate(Common _target, boolean _callInsertLogic = false, boolean _callValidateLogic = false)
{
    Common                              ret;
    CustTable                           custTable;
    boolean                             isUpdate;
    Set     permissionSet; //Added by Admin on 08 05 2016 - mod
    Boolean    existsAXCompany; //Added by Admin on 08 05 2016 - Mod
    if(target.RecId)
    {
        isUpdate = true;
    }
    //Added by Admin on 08 05 2016 - mod
     permissionSet = newSet(Types::Class)
     permissionSet.add(new OverwriteSystemFIeldsPermission());
     CodeAccessPermission::assertMultiple(permissionSet);
     if(_target.RecId)
     {
 custTable = _target as custTable;
 existsAXCompany = custTable::existsAXCompany(custTable.AccountNum,entity.AXCompany);
     }
     ChangeCompany(entity.AXCompany)
     {
 _target.overwriteSystemFields(true);
 _target.(filednum(common, dataAreaId)) == entity.AXCompany;
 if(_target.RecId && !existsAXCompany)
 {
  _target.RecId = 0;
 }
 ret = super(_target, _callerInsertLogic, _CallValidateLogic);
     }   
    //ret = super(_target, _callInsertLogic, _callValidateLogic);
    //End Code - Mod
    if (!this.parmIsCompare())
    {
        custTable = CustTable::find(entity.AccountNum);
        if (custTable && (entity.AccountBalance != 0) && !isUpdate) //check for customer/Accountbalance
        {
            this.generateBalance();
        }
    }
    return ret;
}
Step -4
-->Change the RunOn property of class DMFCustomerEntityClass to Server
Step -5
-->Create New processing group in DIXF
-->Select entities(customer entity) for processing group
-->Format as CSV
-->generate Source file
-->enter some sample customer data (Note: try to include  different AXCompany name)
-->Genrate source mapping
-->preview source file
-->get staging data
-->Copy data to target
Step 6
--> verify data in imported Legal entity customer data

Get error message

Log                     errorMessage;
SysInfologEnumerator    sysInfologEnumerator;
catch(Exception::Error)
        {
            sysInfologEnumerator = SysInfologEnumerator::newData(infolog.infologData());
            errorMessage = "";
            while (sysInfologEnumerator.moveNext())
            {
                errorMessage += sysInfologEnumerator.currentMessage() + "; ";
            }
        }

Access denied: sysoperationservice controller

Error:
Access denied: sysoperationservice controller
For particular user
Resolution:
To fix this, please follow the steps below:
Create Code Permission
Link it with the menu item
Create a new code permission under AOT > Security > Code Permissions.
Add a server method for the newly created code permission. Specify the following properties for the server method added:
Class: Your SysOperation service class
Method: Method name to invoke
EffectiveAccess: Invoke
ManagedBy: Manual
Linking to menu item
Go to your menuiitem
Properties
Linkedpermissiontype: codepermission
LinkedPermissionObject: your code permission name

Migration Between domain checklist

https://dynamicsessentials.net/2015/04/14/how-to-move-your-ax-2012-deployment-to-a-different-domain/
https://msdax.wordpress.com/2011/04/24/move-dynamics-ax-database-to-different-domainmachine/
https://blogs.msdn.microsoft.com/emeadaxsupport/2010/02/16/checking-database-entries-after-restoring-a-microsoft-dynamics-2009-sql-database-to-another-domain-or-environment/

Adding Query range in Multiple lookup in ax 2012

//Adding Query range in Multiple lookup in ax 2012
public void addRangeMultipleValue(tableId _table, fieldId _field, Query _query,str _delimitedMultipleValues)
{
    List                list;
    ListEnumerator      items;
    str                 currentItem;
    list = new List(Types::String);
    if (_delimitedMultipleValues != strMin())
    {
        list = strSplit(_delimitedMultipleValues, #ExpressionDelimiter);
        items = list.getEnumerator();
        while (items.moveNext())
        {
            currentItem    = items.current();
            if (currentItem != strMin())
            {
                this.addSearchCriteriaString(_table, _field, _query,currentItem, true);
            }
        }
    }
}
public void addSearchCriteriaString(tableId _tableId, fieldId _fieldId, str _attributeValue,Query _query,boolean _like = true)
{
    QueryBuildDataSource    qbds;
    QueryBuildRange         qbr;
    qbds = query.dataSourceTable(_tableId);
    if (qbds != null)
    {
        qbr  = qbds.addRange(_fieldId);
        if (_like)
        {
            qbr.value(SysQuery::valueLike(_attributeValue));
        }
        else
        {
            qbr.value(SysQuery::value(_attributeValue));
        }
    }
}

Integration Technologies for Dynamics AX 2012

//Integration Technologies for Dynamics AX 2012
http://www.sonata-software.com/blog/dynamics/integration-technologies-dynamics-ax-2012

standard class for sending Notification

//standard class for sending Notification
AxdSend

AxdDocument

Error : Entity name must be field in -  after upgrade

//Error : Entity name must be field in -  after upgrade
static void San_EntityNameUpd(Args _args)
{
    ReleaseUpdateDB63_DMF  updateEntity = new ReleaseUpdateDB63_DMF();
    updateEntity.updateEntityType();
}

Limitations Of OData Service in AX 2012

//Limitations Of OData Service in AX 2012
->No JSON support: The OData protocol supports Atom as well as JSON, but Microsoft Dynamics AX 2012 only supports Atom.
->No create, update, or delete: only reading  eature is supported in Microsoft Dynamics AX 2012.
->No support for query options:
->No support for queries with fetch mode 1:n:fetch mode to 1:1, which is the only supported fetch mode in AX 2012.
->No support for views:

Send outbound documents with AIF in AX 2012

Send outbound documents with AIF in AX 2012
http://www.sonata-software.com/blog/dynamics/send-outbound-documents-aif-ax-2012-0

Consuming Web service in ax 2012 without VS

// Add service reference without using VS in ax 2012
//Consuming Web service in ax 2012 without VS
Create new Project
->Add new object for reference and set properties->ProjectGroupType to Reference
->Right new created object in Project
 -> Three option is appplicable
  -> Group
  -> Reference
  -> Service reference
-> Use service reference for consume web service in ax 2012

EMail with outgoing email table as system std

static void MailTest_san(Args _args)
{
    VendTable       vendTable;
    void SendEmail(Str _Recipitent,Str    _subject,Str _message,VendTable    _vendTable)
    {
        SysOutgoingEmailTable               outgoingEmailTable;
        SysOutgoingEmailData                outgoingEmailData;
        SysEmailItemId                      nextEmailItemId;
        Map                                 map;
        BinData                             binData = new BinData();
        container                           data;
        container                           embeddedBinaryData;
        Filename                            filePath;
        Filename                            filename;
        Filename                            fileExtension;
        CLRObject                           ex;
        ;
        try
        {
            map = new Map(Types::String, Types::String);
            map.insert('Supplier Id', _vendTable.AccountNum);
            map.insert('Supplier Name', _vendTable.name());
            map.insert('Supplier Type', _vendTable.SupplierType);
            map.insert('Supplier Category', _vendTable.SupplierCategory);
            map.insert('Supplier Sub Category', _vendTable.SupplierSubCategory);
            map.insert('Contact Details',strFmt("%1/%2",_vendTable.phone(),_vendTable.email()));
            ttsBegin;
            nextEmailItemId                                 = EventInbox::nextEventId();
            outgoingEmailTable.EmailItemId                  = nextEmailItemId;
            outgoingEmailTable.IsSystemEmail                = NoYes::No;
            outgoingEmailTable.Sender                       = "test@gmail.com";
            outgoingEmailTable.SenderName                   = "ADNEC";
            outgoingEmailTable.Recipient                    = _Recipitent;
            outgoingEmailTable.Subject                      = _subject;
            outgoingEmailTable.Priority                     = eMailPriority::High ;
            outgoingEmailTable.WithRetries                  = false;
            outgoingEmailTable.RetryNum                     = 2;
            outgoingEmailTable.UserId                       = curUserId();
            outgoingEmailTable.Status                       = SysEmailStatus::Unsent;
            outgoingEmailTable.Message                      = SysEmailMessage::stringExpand(_message, map);
            outgoingEmailTable.LatestStatusChangeDateTime   = DateTimeUtil::getSystemDateTime();
            outgoingEmailTable.insert();
            ttsCommit;
        }
        catch
        {
            ex = CLRInterop::getLastException();
            while(ex != null)
            {
                error(ex.ToString());
                ex = ex.get_InnerException();
            }
        }
    }
    ;
    while select * from vendTable
            //where vendTable.AccountNum == "vendornum"
    {
        SendEmail("senderemail address",strFmt("%1 - Suplier Id %2",SysEmailMessageTable::find("emailtest","en-us").Subject,vendTable.AccountNum),
                                                SysEmailMessageTable::find("emailtest","en-us").Mail,vendTable);
    }
}

Convert Call stack to readable format in D365FO X++

//Input --container _xppCallStack = xSession::xppCallStack();  Public static str POL_formatXppCallStack(container _xppCallStack, int _skipFr...