Monday, February 24, 2025

Posting methods in x++

while posting packing Slip

class/SalesPackingSlipJournalPost/method/endUpdate();


[ExtensionOf(classStr(SalesPackingSlipJournalPost))]

final class TestSalesPackingJournalPost_Extension

{

     protected void endUpdate()

    {

            next endUpdate();

        // write your logic

    }

}

How to search metadata in x++

Query stringWhat it does
TrvExpTableIf the token is by itself, it is assumed to be the name. So this will find everything in the application that has "TrvExpTable" in the name.
type:form ccountFinds all forms that have "ccount" in their names.
type:form property:formtemplate=listpageFinds all forms that contain the property "FormTemplate" equal to ‘ListPage’.
type:table,formDesign property:"WorkflowDataSource=TrvExpTable"Finds formDesign nodes under tables, nothing would be found.
type:form,formmenufunctionbuttoncontrol property:Text=@SYS311998Finds all menu function button controls with the Text property equal to (a label) ‘@SYS311998’.
type:table,method name:insertFinds tables with a method containing "insert" in the method name.
type:table,tableindex name:ExportFinds tables with an index name containing the word "Export".
type:table,tableindexfield name:xpNumFinds table indexes with "xpNum" in the index field name.
type:table,tablefieldgroup name:EPNewFinds FieldGroups (in tables) containing ‘EPNew’ in their names.
type:form,formgridcontrol property:allowedit=no,heightmode=columnFinds form grid controls, with properties allowedit equal to "no" and heightmode equal to "column".
type:form,formtabcontrol property:arrangeMethod=Vertical,ViewEditMode=view,WidthMode=AutoFinds form tab controls, with properties arrangeMethod equal to "Vertical" and ViewEditMode equal to "view" and WidthMode equal to "Auto".
type:form,formDesign property:"WorkflowDataSource=TrvExpTable"Finds all forms with the "WorkflowDataSource" property in the FormDesign node set to the value "TrvExpTable".
model:”Application Suite” type:formdesign property:style=simplelistdetailFind all forms in Application Suite model that has the style property set to simpleListDetail in the FormDesign node.
code:"return null"Finds all places in the source code that contains "return null".
code:"element.lock()" type:formFinds all places in the forms source code that contain the snippet "element.lock()".
code:"insert" type:table,formFinds all places in the source code of either forms or tables that contain "insert".
code:"public display" type:form,methodFinds all form methods that contain the code "public display".
type:formbuttoncontrol property:text=Finds all form Button Controls that have empty text properties.


Reference;  Metadata search

 

Tuesday, February 4, 2025

Import Database ( Restore ) in d365 FO

 While restoring DB from  Tier2 to tier 1 environments (Bacpac to bak)

1) firstly we need  install the  SQl package  and extract it 



by using below command in command prompt  we restore the new DB in our dev machine 
2)SqlPackage.exe /a:import /sf:D:\Exportedbacpac\my.bacpac /tsn:localhost /tdn:<target database name> /p:CommandTimeout=1200 /TargetTrustServerCertificate:true 

  • tsn (target server name) – The name of the Microsoft SQL Server instance to import into.
  • tdn (target database name) – The name of the database to import into. The database should not already exist.
  • sf (source file) – The path and name of the file to import from.

EX



3)once New DB Created  we need to execute below script .

==========================================

CREATE USER axdeployuser FROM LOGIN axdeployuser

EXEC sp_addrolemember 'db_owner', 'axdeployuser'


CREATE USER axdbadmin FROM LOGIN axdbadmin

EXEC sp_addrolemember 'db_owner', 'axdbadmin'


CREATE USER axmrruntimeuser FROM LOGIN axmrruntimeuser

EXEC sp_addrolemember 'db_datareader', 'axmrruntimeuser'

EXEC sp_addrolemember 'db_datawriter', 'axmrruntimeuser'


CREATE USER axretaildatasyncuser FROM LOGIN axretaildatasyncuser


CREATE USER axretailruntimeuser FROM LOGIN axretailruntimeuser


CREATE USER axdeployextuser FROM LOGIN axdeployextuser


CREATE USER [NT AUTHORITY\NETWORK SERVICE] FROM LOGIN [NT AUTHORITY\NETWORK SERVICE]

EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'


UPDATE T1

SET T1.storageproviderid = 0

    , T1.accessinformation = ''

    , T1.modifiedby = 'Admin'

    , T1.modifieddatetime = getdate()

FROM docuvalue T1

WHERE T1.storageproviderid = 1 --Azure storage


DROP PROCEDURE IF EXISTS SP_ConfigureTablesForChangeTracking

DROP PROCEDURE IF EXISTS SP_ConfigureTablesForChangeTracking_V2

GO

-- Begin Refresh Retail FullText Catalogs

DECLARE @RFTXNAME NVARCHAR(MAX);

DECLARE @RFTXSQL NVARCHAR(MAX);

DECLARE retail_ftx CURSOR FOR

SELECT OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_id) fullname FROM SYS.FULLTEXT_INDEXES

    WHERE FULLTEXT_CATALOG_ID = (SELECT TOP 1 FULLTEXT_CATALOG_ID FROM SYS.FULLTEXT_CATALOGS WHERE NAME = 'COMMERCEFULLTEXTCATALOG');

OPEN retail_ftx;

FETCH NEXT FROM retail_ftx INTO @RFTXNAME;


BEGIN TRY

    WHILE @@FETCH_STATUS = 0 

    BEGIN 

        PRINT 'Refreshing Full Text Index ' + @RFTXNAME;

        EXEC SP_FULLTEXT_TABLE @RFTXNAME, 'activate';

        SET @RFTXSQL = 'ALTER FULLTEXT INDEX ON ' + @RFTXNAME + ' START FULL POPULATION';

        EXEC SP_EXECUTESQL @RFTXSQL;

        FETCH NEXT FROM retail_ftx INTO @RFTXNAME;

    END

END TRY

BEGIN CATCH

    PRINT error_message()

END CATCH


CLOSE retail_ftx; 

DEALLOCATE retail_ftx; 

-- End Refresh Retail FullText Catalogs


--Begin create retail channel database record--

declare @ExpectedDatabaseName nvarchar(64) = 'Default';

declare @DefaultDataGroupRecId BIGINT;

declare @ExpectedDatabaseRecId BIGINT; 

IF NOT EXISTS (select 1 from RETAILCONNDATABASEPROFILE where NAME = @ExpectedDatabaseName)

BEGIN 

select @DefaultDataGroupRecId = RECID from RETAILCDXDATAGROUP where NAME = 'Default'; 

insert into RETAILCONNDATABASEPROFILE (DATAGROUP, NAME, CONNECTIONSTRING, DATASTORETYPE)

values (@DefaultDataGroupRecId, @ExpectedDatabaseName, NULL, 0); 

select @ExpectedDatabaseRecId = RECID from RETAILCONNDATABASEPROFILE where NAME = @ExpectedDatabaseName; 

insert into RETAILCDXDATASTORECHANNEL (CHANNEL, DATABASEPROFILE)

select RCT.RECID, @ExpectedDatabaseRecId from RETAILCHANNELTABLE RCT

inner join RETAILCHANNELTABLEEXT RCTEX on RCTEX.CHANNEL = RCT.RECID

        update RETAILCHANNELTABLEEXT set LIVECHANNELDATABASE = @ExpectedDatabaseRecId where LIVECHANNELDATABASE = 0

END; 

--End create retail channel database record


4) Stop the below 4 services

  • World Wide Web Publishing Service
  • Microsoft Dynamics 365 Unified Operations: Batch Management Service
  • Management Reporter 2012 Process Service
  • Microsoft Dynamics 365 Unified Operations: Data Import Export Framework Service 
5) Rename the DB.

2
3
4
5
6
ALTER DATABASE AXDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE AXDB MODIFY NAME = AXDB_Orig
GO
ALTER DATABASE AXDB_Orig SET MULTI_USER
GO

6) start the below  4 services 
  • World Wide Web Publishing Service
  • Microsoft Dynamics 365 Unified Operations: Batch Management Service
  • Management Reporter 2012 Process Service
  • Microsoft Dynamics 365 Unified Operations: Data Import Export Framework Service

reference: Import Database


 

User License

 using Microsoft.Dynamics.AX.Security.Management;

using Microsoft.Dynamics.AX.Security.Management.Querying;

using Microsoft.Dynamics.AX.Security.Management.UI;


class test

{


    public static Str getDefaultDimName(DimensionDefault _dimensionDefault)

    {

        DefaultDimensionView    dimensionView;

        str                     dimensionValue;



        while select dimensionView

            where dimensionView.DefaultDimension == _dimensionDefault

        {

            dimensionValue += dimensionView.DisplayValue + '~';

        }


        return dimensionValue;

    }


    public static DimensionDefault createDefaultDim(Name _dimensionName, str _dimValue ,  DimensionDefault _oldDefaultDimenion = 0)

    {

        DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();

        DimensionDefault                    result;


        int                                 i;

        DimensionAttribute                  dimensionAttribute;

        DimensionAttributeValue             dimensionAttributeValue;

        DimensionDefault                    newDefaultDimension;

   

        dimensionAttribute = dimensionAttribute::findByName(_dimensionName);


        if (dimensionAttribute.RecId != 0 && _dimValue)

        {

            dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValueNoError(dimensionAttribute, _dimValue, false, true);

            valueSetStorage.addItem(dimensionAttributeValue);

        }

        result = valueSetStorage.save();

        newDefaultDimension   = LedgerDimensionDefaultFacade::serviceMergeDefaultDimensions(result,_oldDefaultDimenion);


        return newDefaultDimension;

    }


    public static LedgerJournalTable createLedgerJournal(LedgerJournalNameId    _journalName, CurrencyCode  _currencyCode = "")

    {

        LedgerJournalTable      ledgerJournalTable;

        LedgerJournalTableData  jourTableData;

        ;


        jourTableData = JournalTableData::newTable(ledgerJournalTable);


        ledgerJournalTable.JournalNum  = jourTableData.nextJournalId();

        ledgerJournalTable.JournalName = _journalName;

        ledgerJournalTable.initFromLedgerJournalName(_journalName);


        if(_currencyCode)

        {

            ledgerJournalTable.CurrencyCode = _currencyCode;

        }

        ledgerJournalTable.insert();


        return ledgerJournalTable;

    }


    public static boolean  checkUserLicence(UserLicenseType _userLlicenceType, UserId _userId = curUserId())

    {

        SecurityLicenseRole SecurityLicenseRole;

        SecurityRole        role;

        SecurityUserRole    userRole;

        UserInfo            userInfo;

        boolean             ret = false;


        DialogService::PopulateSysSecurityRolesWithAggregateLicense(SecurityLicenseRole.getPhysicalTableName(), SysSecurity::GetSecurityRepository());


        while select role

            exists join userRole

                where userRole.User == _userId

                   && userRole.SecurityRole == role.RecId

        {

            select firstonly SecurityLicenseRole

                where SecurityLicenseRole.SecurityRole == role.recId;

            

            if(SecurityLicenseRole.RecId)

            {

                List strlist = new List(Types::String);

                strlist = strSplit(SecurityLicenseRole.License, ',');

                ListIterator iterator = new ListIterator(strlist);

                str licenseString;

                boolean isFirst = true;

                while (iterator.more())

                {

                    UserLicenseType license = any2Enum(iterator.value());

                    if( license == _userLlicenceType )

                    {

                        ret = true;

                        break;

                    }

                    iterator.next();

                }

            }

        }

       

        return ret;

}


}

Cannot stop DynamicsAxBatch service on computer Dynamics 365 for finance and operations

Cannot stop DynamicsAxBatch service on computer Dynamics 365 for finance and operations 


Uploading: 134828 of 134828 bytes uploaded.


The message already shows the service name. ” DynamicsAXBatch” You can copy it from Service detail dialog.

So Open CMD with run as administrator and run the following command and get  pid

sc queryex DynamicsAxBatch


Now I have IP.

And kill the Process Id 

taskkill /f /pid 11524  

Now I start the service again.

Project is successfully complied             

Wednesday, January 22, 2025

Debugging Test/UAT Data from Development VM in D365FO

 JIT access to TEST/UAT

Just-in-time access which is required for various troubleshooting efforts, running unplanned queries, or data upgrade problem solving.

Go to LCS and select the environment for which you wanted to connect the database. In my case, I am using TEST.

Enter the firewall by adding the IP address of the Dev VM from where the database will be connected.

Upon clicking Confirm, there will be a message which says about the expiry time of this firewall. Usually 8 hours.

The next step is accessing the database and the mode needed.

In the LCS page, under Database Accounts section, 4 options will be displayed for the accessing reason. As we are troubleshooting, we need write access and thus selecting ‘Troubleshooting tuning for AX”.

Select the reason and enter the details.

Click ‘Request Access’ and refresh the page. User will be presented with the login details .

Note down the details of SQL server, database name , user name and password.

These are needed when we connect the database from dev VM.

Refer Microsoft link for further information

Connect to Test Database

Now with the above credentials, connect to the TEST database and create a new login which will be used for debugging.

Use SQL Server authentication login(not Windows) to connect the database

Execute the below query which creates the new user used for debugging .

CREATE USER [axdevdebugadmin] WITH PASSWORD=N'Pass@word1', DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', 'axdevdebugadmin'
GO

Web.Config changes:

Connect to the VM and navigate to the folder having ‘AOS Service’ -> WebRoot and select web.config file.

Take a copy of this file as we are going to modify some of the details in the file to connect the dev VM to TEST database.

Stop the following services :

IIS

World wide publishing

MS Dynamics 365 Batch

MS Dynamics 365 DIXF

Close the VS

Any active connection to local SQL db.

Right click on ‘Web.config’ file and open in Notepad. Make changes to the following tags.

<add key="DataAccess.Database" value="LCS JIT database name" />
<add key="DataAccess.DbServer" value="LCS JIT database server />
<add key="DataAccess.SqlUser" value="LCS JIT user name" />
<add key="DataAccess.SqlPwd" value="LCS JIT password" />
<add key="DataAccess.AxAdminSqlPwd" value="pass@word1" />
<add key="DataAccess.AxAdminSqlUser" value="axdevdebugadmin" />

Start the IIS and World wide publishing service.

Connect the Dev VM URL . You can check if it is accessing the test database by navigating to

System Administration -> Inquiries -> Database -> Database Information

Now the system is ready to start the debugging.

Tips and precautions while doing the process

  1. Make sure the VM and the higher environment are in the same version .
  2. Latest code in the VM where the debugging is triggered. Remove unwanted pending changes and do a buikd+sync in the VM before initiating the connection.
  3. It is always recommended to have the code base same in both the environments.
  4. Do not trigger database sync after connecting to TEST/UAT database .
  5. Take a copy of the web.config file before making the changes.
  6. Revert the changes once the debugging is finished. If left with the same web.config file , the URL will be inaccessible after 8 hours. Please note the JIT is alive only for 8 hours.
  7. If the database is refreshed within 8 hours, we need to generate a new JIT access.

Tuesday, January 21, 2025

Difference between datetime x++


In this post I am going to show the difference between 2  utc datetime and it will return the Days,Hours,Minute,Seconds



 utcDatetime PreparedOn ;
 utcDatetime DispensedOn ;
 str diffTime ;
 int time;

if(DispensedOn !=utcdatetimenull() && PreparedOn!=utcdatetimenull())
 {
     time           = DateTimeUtil :: getDifference(DispensedOn,PreparedOn);
     diffTime    = strFmt('%1d:%2h:%3m:%4S',(time div 86400),((time Mod 86400) div 3600),((time Mod 3600) div 60),((time Mod 3600) Mod 60));
  }


Reference :https://msaxcrm.blogspot.com/2018/09/difference-between-2-utc-datetime-ax.html

Capturing Infolog messages in D365FO using X++.

      Capturing info log messages in D365FO. We can get it in multiple ways.      Way 1.        public static str getError() {     SysInfol...