Saturday, June 12, 2021

Sequence contains no matching element at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)

This error occurs when there is a parameter at the subnode (Dataset) level, which is  supposed to be mapped to report parameter; however, it does not map to one. 

This can happen when we selected to have the Dynamics Filters = True for the dataset (which would create corresponding elements at the report level) and later deleted them from the report level, thus leaving the dataset level filters as orphan and without a matching filter. 


In the screen above we can see that the HeaderFooter dataset refers to a parameter called HeaderFooter_parmBankAccountId and this does not exist at the report level. We should map this to a valid report parameter if it exists, or we can set the dynamic filters to false and then true again so that these filters are created again if missing. 


The number of defined parameters is not equal to the number of cell definitions in the parameter panel

 This issue can occur when a developer copies a report from an existing design and tries to make the changes to the dataset. 

There are parameters passed between the AX system and SSRS framework and these need to be in Sync. The parameters are stored at 3 levels and it needs to be in Sync. Sometimes it can happen that due to the edits one makes these move out of Sync in such cases we have to manually fix it. 

Its important that for every parameter at the report level, there is a corresponding parameter at the dataset level. 


The other odd place where the parameters are saved is in the XML file and it can sometimes not be seen/referred on the screen. Hence to fix these we should open the report using an xml editor. Right click the report and choose to open with XML editor.

Once the xml editor is opened , one can see that there parameters referred in the XML file which do not exist on the dataset. These are from a previous dataset PromotionSalaryDS which now is probably removed and hence the mismatch. 

We should manually delete these parameters to match the list as per the report parameters. 


You will also have to delete the parameters if they are referred in the Parameter cell definition. Please ensure that you delete each xml block as a unit. One unit is highlighted below it starts with CellDefinition and ends with /CellDefinition

   


Friday, June 11, 2021

X++ get T-SQL Statement

Something that is frequently required to debug SQL statement is the select query that is generated. To get the SQL statement associated with the x++ select 

Use the generate only and forceliterals clause in the statement. 

        select generateonly forceliterals disbursementJournal
            join disbursementDetails
            where disbursementJournal.DisbursementDetailsRecId == disbursementDetails.RecId
                && disbursementJournal.OffsetBankAccount == _bankAccountId
                && disbursementDetails.PayrollPeriodLine == _payrollPeriodLine
            join hcmWorker
            where hcmWorker.RecId == disbursementJournal.Worker
            join workerBankAccount
            where workerBankAccount.Worker == disbursementDetails.Worker
                && workerBankAccount.RecId == disbursementJournal.WorkerBankAccount
            join companyBankAccount
            where companyBankAccount.AccountID == disbursementJournal.OffsetBankAccount
            join payrollPeriodLine
            where payrollPeriodLine.RecId == disbursementDetails.PayrollPeriodLine;

        info( disbursementJournal.getSQLStatement()); 

Friday, June 04, 2021

DateTime in Dynamics

DateTime fields have some complexity added to them because these fields are stored in SQL server and are displayed in Dynamics as per the user timezone. 

Because timezone is not stored along with the DateTime filed in SQL; Dynamics always assumes that the date is in UTC date time format and if it needs to be displayed to the user then it is convereted from that timezone to the user timezone by the dynamics framework.

This understanding is important when working with DateTime fields as the data that one might see in the SQL database might be different and that is because the framework is converting the time from the user timezone to UTC.

The different timeZones that the system supports are defined as a TimeZone enum

  •    Timezone::GMTMINUS0600CENTRALTIME;
  •    Timezone::GMTMINUS0500EASTERNTIME;
  •    Timezone::GMTMINUS0800PACIFICTIME;

There are a lot of functions in the DateTimeUtil class to hanlde the different time conversion scenarios the important ones are : 

  • Convert to the logged in users TimeZone
    DateTimeUtil::applyTimeZoneOffset(myDateTime,DateTimeUtil::getUserPreferredTimeZone());
  • Convert to a specific TimeZone
    DateTimeUtil::applyTimeZoneOffset(myDateTime,myTimeZone);

Sunday, May 23, 2021

Power BI data export to SQL Server

There might be scenarios where you might want to export the data from Power BI to SQL server. In my case there were two dashboard where a certain value was not matching and i wanted to do a SQL query to figure out what was missing. 

So with some research I found out that, Power BI uses SSAS services in the background to store and fetch data to and from the datamodel that is created. Power BI ships with the SSAS service "msmdsrv.exe" (found in bin folder of power bi installation) and an instance of this service is create for each power bi desktop session. 

If we can access this instance we should also be able to import data from the same. We know that the service would be running on the localhost but what we dont know is the port at which it is running. To find the port number is a two step process:

Step 1: Find the ProcessID of the msmdsve.exe on the local server use the following command on an elevated command prompt. 

       
	TASKLIST /FI "imagename eq msmdsrv.exe" /FI "sessionname eq console"
 


Now one needs to chose the PID and fetch the details of the process using the following command in an elevated command prompt:
       
	netstat /ano | findstr "<PID from step 1>"
 
 

We have used PID 15480 from the first command and from the TCP responses the first line exposes the port number that is being used by the service. 

Create a SSIS project in Visual Studio and drag the DataFlow task on the canvas as shown below. 

Right click the data flow task and choose edit. This should take us to the DataFlow tab from the control flow tab. In the dataflow tab select Source assitance and create a new connection to the local SSAS server that we figured out in the steps above

While creating the Connection make sure that you select the provider as OLE DB Provider for Analysis Server (as shown below).


Use the server name details as discovered with NT authentication and just select the intial catalogue whcih is randomly generated. 

Now create a destination connection using the Destination assistant from the toolbar. Once the source and destination connections are created we will end us with a screen as shown below. We need to then connect the two tasks that are created. 

Now, edit the source connection and populate the details similar to as show below. 

The SSIS package can now be executed to import the data. One issue that I have noticed with the above procedure is that the data type for the different columns is not correctly identified and a lot of the columns end up being imported as varchar(255) an alternate to this could be to format this data in excel file and then import from excel after formatting the columns there.

To import the data into excel we need to create a connection to the SSAS server with the same details as above.  The only trick that is required in this process is to treat the SSAS source as a table rather than a cube so that flat data can be imported. 

When the connection to SSAS cube is created the connection is saved as a folder "C:\Users\santosh.singh\Documents\My Data Sources" (replace santosh.singh with the user name that you are logged in with). 



In this folder locate the connection that you have just created and edit this as a text file replace the two fields (CommandType and CommandText)


Enter the CommandType as Query and CommandText with a DAX Query which to extact a flat table from a cube is evaluate <TableName>


Once the above changes are done import the data using Excel and the data would appear as a flat table rather than a cube (Pivot). Once the import is done format the columns with the correct data type and then import the excel into SQL server using SSIS.





Wednesday, May 19, 2021

SSIS OData Package

While testing a PowerBI report we realized that the data being presented is wrong due to some join issue. Its always easier to analyze the impact of an incorrect join when we have a access to SQL database. We are using Dynamics data in PowerBI using Odata entities. Hence in order to check the validity of the joins, it was desired to have the Data in SQL Server. 

We decided to write an SSIS package to copy the data from Dynamics D365 to SQL Server. When we starting OData we received an error  

[OData Source [2]] Error: Cannot acquire a managed connection from the run-time connection manager.

[SSIS.Pipeline] Error: OData Source failed validation and returned error code 0xC020801F.

We can resolve this using the below steps:

Install Microsoft .NET 4.6 and above on your computer and Enforce TLS 1.2 on your machine through registry settings. 

In an elevated command prompt run the following commands:

reg add HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 /v SchUseStrongCrypto /t REG_DWORD /d 1 /reg:64

reg add HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 /v SchUseStrongCrypto /t REG_DWORD /d 1 /reg:32

Monday, May 17, 2021

SOAP vs REST Web APIs

Have started working on some integration pieces and it required clarity on the standards to be used. From the little research that I have done below is the understanding. For any interaction to happen between applications we need to have a handshake at two levels :- 
  1.  The protocol to be used to exchange the data packets. 
  2.  The format in which the data packets will be exchanged. 
The two popular standards that are used to access Web services (APIs) over http are 
SOAP: 
This is a full protocol. Its like an envelop which is added on top of the message. Because SOAP is an envelope the messages need to be packed and unpacked to and from the enveloped. The message is however formatted in XML. 


REST: 
Rest does not directly compare to SOAP as its not a protocol. Its like a postcard which is open and it is transferred over http protocol. Thus making it light and faster however less secure. The messages in REST standard are formatted as JSON. 

Primary Use:
Primarily REST API are created for CRUD operations on data (tables) over internet. REST is focused on accessing named resources through a single consistent interface.

SOAP  focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

OData: 
Odata is an implementation of REST APIs in a standard that further simplifies/ standardizes the process of handling the request and response headers, status codes, HTTP methods, URL conventions, media types, payload formats, query options, etc. when working with REST API calls.  

WSDL:
WSDL is often used in combination with SOAP service. WSDL defines the service for the consumer and acts as a standard between the consumer and the provider.  It describes how to access a web service and what operations it will perform. A client program connecting to a web service can read the WSDL to determine what functions are available on the server this is also release to the developers to develop the interface with the service and enabling intellisense. 


Saturday, May 08, 2021

Extend trial period

 The windows servers are installed in trial mode and can be extended as follows: 

The trial periods can be extended 6 times. To view the status of the trial and how many trial extensions are remaining the following command should be used on the PowerShell 

       
slmgr -dlv
 
To extend the period by 180 days when the expiry is reached use the following command
       
slmgr -rearm
 
The the settings can be seen using the following command
To extend the period by 180 days when the expiry is reached use the following command
       
slmgr -dli
 

Wednesday, April 28, 2021

Formatting code block blog post

 Below is the style for formatting a code block:

 
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: &quot;Andale Mono&quot;, &quot;Lucida Console&quot;, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;">       <code style="color: black; overflow-wrap: normal; word-wrap: normal;">

--code goes here

 </code><br />
</pre>
<p>&nbsp;</P>

Tuesday, April 27, 2021

insert_recordset with type casting

Its a well known fact that the insert_recordset is used for performance reasons when we want to use set operations instead of doing record based loop and roundtrips to the server. 

The only problem being that there is no type casting allowed. Consider a scenario like below where there is a data mismatch between the fields being inserted to and the fields being selected from: 

In the statement below using the int2str function is not allowed so how do we type cast ? 

       

            insert_recordset PriorityTmp( PriortyCode, Description, OrderPlaningId, WrkCtrId, PriorityNum )
            select "P" + int2str( PriorityNum) , "P" + int2str( PriorityNum ) , OrderPlaningId , WrkCtrId, PriorityNum
            from LocalOrderPlanning
            order PriorityNum asc
            where LocalOrderPlanning.RecId         != orderPlanning.RecId &&
                LocalOrderPlanning.WrkCtrId         == orderPlanning.WrkCtrId &&
                LocalOrderPlanning.PlanningStatus   == OrderPlanning.PlanningStatus &&                
		LocalOrderPlanning.MergeLine ==  NoYes::NO;
Unfortunately there is no direct solution for the above using the statements, basically we would want to use a typecast function at the SQL level and this can only be done using views or direct sql statement. For this case we will try to create a view with the necessary type casting : 

The view would have a computed column with the below method :
       

    static server str PriorityCode()
    {
        DictView dictView2;
        str sPriorityNumField, sReturnField;

        // Construct a DictView object for the present view.
        dictView2 = new DictView(tableNum(AFZOrderPlanningView));

        // Get a string that has the target field name
        // propertly qualified with an alias (such as "A." or "B.").
        sPriorityNumField = dictView2.computedColumnString("AFZOrderPlanning",  fieldStr(AFZOrderPlanning, PriorityNum ), FieldNameGenerationMode::FieldList, true);

        sReturnField = strFmt(" 'P' + cast( %1 as varchar)", sPriorityNumField);

        return sReturnField;
    }
The above column is then added to the fields of the view and is used in the function above. The advantage of using the computed columns is also that it can be filtered upon unlike the display methods that are used in AX. 

Please Note: When adding a computed column to the view, there are two methods to choose from, on the computed column property sheet. These are Method and ViewMethod. Please ensure that ViewMethod property is used to specify the name of the method. 

Thursday, April 22, 2021

Deploying User control in EP

Once a certain functionality has been developed using User Controls for EP, the next step is to deploy this functionality on the EP portal. Following are the steps that are used to deploy an SSRS report, using a parameters forms (User control) on EP.

Basically the process involves two steps :- 

  1. Creating the UserControl to accept the report parameters
  2. Creating a new page to host the UserControl, which is used to accept the parameters. 
  3. Creating a navigation to viewing this page.
Step 1: Creating of the user control to accept report parameters

  • Start by creating a new project in Visual Studio for the EP Web Application and then add EP User Control to the project. 
  • The control that would be used for viewing a report would be the AxReportViewer control and to be able to use this we will have to ensure that the AxBaseUserControl is added and reference to the ApplicationProxies is added to the project.  
  •  Create the necessary interface for accepting the parameters on the screen. This could be a combination of asp and Ax controls if required. 
  • The Report that needs to be printed should be a SSRS report and should be based on the SRSReportDataProviderBase class
  • The report should have an output menu ( LeaveBalance in this example ) 
  • Add the AxReportViewerControl from the toolbox and assign the output menu as a property as shown below 
  • Now lets add the code for the print button click. The first thing we need to do is to open our SSRS report and view all the parameters that are present. Its important that we assign a value to all the parameters that the report uses
  • Please note that we can ignore the DynamicParameter as these are due to query dialogs on the report and cannot be used on the EP.

  • Now that we know we have three parameters as highlighted above being used in the report. Please create the button click procedure to pass all the parameters to the report and when the AddParameters method is called the report is triggered. 
public partial class SPYLeaveBalanceReport : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Dictionary parms = new Dictionary();

        parms.Add("LeaveDetails_AsOnDate", DateTime.Parse(txtAsOnDate.Text).ToString("G"));

        if ( chkShowDetails.Checked == true)
        {
            parms.Add("LeaveDetails_ShowDetails", "Yes");
        }            
        else
        {
            parms.Add("LeaveDetails_ShowDetails", "No");
        }            
        parms.Add("LeaveDetails_absenceCode", "");

        this.axLeaveBalanceReport.AddParameters(parms);        
    }
}

Step 2: Creating a page to host the User control created in step 1
  • Open Enterprise portal and navigate to the page where the new link has to be created and then click on -> Site Actions –> More Options –> Page –> Create –> 
  • Provide name for the page –> Select the layout –> Select Library as Enterprise Portal –> OK.

Please use the right page type (Header, Footer, 3 columns) else the page might not show the page navigation of the parent page. A new page will now be created relative to the page we started from. The address of the newly created page will be visible in the address bar. Click edit to open the page in design mode and add a webpart called SPYLeaveBalancesESS created above.



Step 3: Create a navigation to the above sharepoint page
Now that the sharepoint page with the UserControl has been created and saved. We have to create a navigation to the same from the menu where we desire. 
  • So we start from the front end screen where we wish to place the new link. Given the screen below one would start from the Web Menus in the AOT

  • We browse the Web menu intuitively to figure out the above menu. Once we get the menu in the property sheet we will be able to find the WebMenu that is used in the property sheet under the property QuickLaunch : SPYHCPMListPageQuickLaunch (shown below)

Once the Web Menu name is identified we can expand the same in the AOT and we will be able to notice that the Web Menu is a group of Web Menu Items of url type. 


Each Menu item is hence a url to a specific page on the sharepoint portal. We will have to now create a new URL web menu item and add the page that we created in step 1 as the URL. The URL should begin relative from the portal where it is being assigned. Hence the url for web page "Leave balance.aspx" which was added under employee portal would be 

EmployeeServices/Enterprise%20Portal/Leave%20balance.aspx 

Once the menu has been created and the URL has been specified the page can be imported into AOT from the sharepoint portal. This is useful when the deployment has to be migrated from the DEV server to the Production server. Once the page has been imported we will get an Info Log as shown below.


The last piece of the deployment is to add this newly created Web Menu URL to the Web Menu by dragging and drop it on the menu. 



 

Wednesday, April 21, 2021

Format date as per user setting

 In SSRS when dates need to be formatted as per the user preferences and time zone use the below expressions: 

       
Microsoft.Dynamics.Framework.Reports.DataMethodUtility.ConvertUtcToAxUserTimeZoneForUser(Parameters!AX_CompanyName.Value, Parameters!AX_UserContext.Value, System.DateTime.UtcNow, "d", Parameters!AX_RenderingCulture.Value)
 

In the above expression System.DateTime.UtcNow should be replaced with the actual data.

Tuesday, April 20, 2021

Exists join in select statement

Exists joins are required when we want to check for an existence of a records in an table without having duplicate records returned. I had this strange problem today where i was trying to fetch the records using an exists join and the results where not generating.
       

select generateOnly forceLiterals sum(Qty) from projEmplTrans
     where projEmplTrans.TransDate >= tsStartDate &&
	projEmplTrans.TransDate <= tsEndDate &&
	projEmplTrans.ProjId == projId
    exists join journalId from payrollJournalTable
	where payrollJournalTable.JournalId == conPeek( payrollJournalCon, i )
    join worker from payrollJournalLine
	where payrollJournalLine.Worker == projEmplTrans.Worker
	&& payrollJournalLine.PayrollJournal == payrollJournalTable.RecId;

 
The SQL Statement that is generated is
       

SELECT SUM(T1.QTY) FROM PROJEMPLTRANS T1 
WHERE (((T1.PARTITION=5637144576) AND (T1.DATAAREAID=N'0001')) AND (((T1.TRANSDATE>={ts '2021-02-01 00:00:00.000'}) 
AND (T1.TRANSDATE<={ts '2021-02-28 00:00:00.000'})) AND (T1.PROJID=N'BAA'))) 

AND EXISTS 

(SELECT 'x' FROM SPYPAYROLLJOURNALLINE T2 CROSS JOIN SPYPAYROLLJOURNALTABLE T3 
WHERE (((T2.PARTITION=5637144576) AND (T2.DATAAREAID=N'0001')) AND (T2.WORKER=0)) 
AND (((T3.PARTITION=5637144576) AND (T3.DATAAREAID=N'0001')) AND ((T2.PAYROLLJOURNAL=T3.RECID) AND (T3.JOURNALID=N'0001-00000181'))))

 
The problem here is that the T2.Worker == 0 which ideally should have been T2.Worker == T1.Worker. 

After a lot of trials realized that the Worker field in projEmplTrans is a deprecated field and hence the system was equating it to zero (0).

Thursday, April 01, 2021

XDS Security

The extended security model is used to create a customer rule for limiting the access to records. In simple words, XDS is placing a Where clause on any SQL Select, Update, Delete, or Insert statement based on parameters from another related table. 

Scenario: Users are clubbed in a group and this group is then associated with a Sales Order. A user should only be allowed to view the sales orders which belong to a group where the users is associated.   

The different components of the XDS security are : 

1. Query: Query created for a table which is then extended to all the related tables where this table is a foreign key. 

For the above scenarios because we need to filter the Sales Order, so we will find a table where the Sales Order has a relationship. Eg: ( CommissionSalesGroup ) however the sales commission group does not have users associated to it, so we create a new table ( AFZCommissionSalesGroupUsers ). Now the query that we will create will be based on the table which has a direct link the sales order (CommissionSalesGroup ) and we will restrict this based on a join with the (AFZCommissionSalesGroupUsers) where the user= curUserID()

Next step is to add a security policy object.

2. Security policy: Once the query is designed, the next step is to plan which all table would this query restrict access to. A policy is used to link the query (created in step 1) with a list of tables which need to be restricted for security (constraint tables). 

It also has a policy context which is used to determine when the policy is applied, this is generally set to a security role (i.e. anyone which the configured role would be applied with the record level security). 

The security policy also has a primary table mentioned which is the root of the query that is created. The primary table should have an explicit relationship with all the tables where the constraint is being applied. 

Every security policy would also have a property called Constrained Table which can be set to Yes or No to decide if the policy would be applied on the primary table itself or not. 

When the policy is applied on the primary table it be already applied before the xds method is called in MyTables. If the xds method needs access to the records in the primary table, this might be a concern as the policy would already be applied and not all the rows in the primary table would be available for the xds method. In cases like this a view based on the primary table can be created and that should be used instead of the actual table. 

Alternatively within the XDS method if the xds needs to be by-passed the below constructs can be used

in AX2012 use 

       
XDSServices.setXDSState(0)
 

in Dynamics F&O you can use the below code block 

       
unchecked(Uncheck::XDS)
{
    select ValidTimeState(_asOfDate) maxof(ValidTo) from hcmEmployment
        where hcmEmployment.Worker == _workerRecId;
}
 
Ensure that you set the Constrained Table property to Yes and add the primary table is set to the primary table of the Query that is attached. 
 

3. MyTables : These are special tables created to be used in the security query, where custom logic can be written to populate data. These table names are prefixed with "My" keyword and the logic is written in xds function.

       

    public RefreshFrequency xds()
    {
        MyAFZCategory   myCategory;
        SPYHCMWorker       hcmWorker; //view is used as the primary table is contrained
        DirPersonUser   dirPersonUser;

        AFZEmployeeCategory afzEmployeeCategory;
        AFZWorkerCategoryUserAccess workerCategoryUserAccess;        
       
        insert_recordset myCategory(HcmWorkerRecId)
        select RecID from hcmWorker
        join afzEmployeeCategory
            where afzEmployeeCategory.Code == hcmWorker.AFZCategoryCode
        join workerCategoryUserAccess
            where workerCategoryUserAccess.UserId == curUserId()
            && afzEmployeeCategory.CodeGroup == workerCategoryUserAccess.CodeGroup ;             

        /*
        select generateOnly forceLiterals RecID from hcmWorker
        join afzEmployeeCategory
            where afzEmployeeCategory.Code == hcmWorker.AFZCategoryCode
        join workerCategoryUserAccess
            where workerCategoryUserAccess.UserId == curUserId()
            && afzEmployeeCategory.CodeGroup == workerCategoryUserAccess.CodeGroup ;
        info( hcmWorker.getSQLStatement() );
        */


        //Calculate current worker value
        select firstonly PersonParty, ValidFrom, ValidTo from dirPersonUser
            where dirPersonUser.User == curUserId();

        select firstonly RecId from hcmWorker
            where hcmWorker.Person == dirPersonUser.PersonParty;

        myCategory.initValue();
        myCategory.HcmWorkerRecId = hcmWorker.RecId;
        myCategory.insert();

        // This is static data, so only refresh when session is restarted
        return RefreshFrequency::PerSession;
    }

}

When a table is being added to the constraint table. There are two options:
  • Constraint Table : Allows us to select tables from which the data would be filtered. These tables should have a relationship defined with the primary table of the xds query. 
  • Constraint Expressions: Allows us to select tables and define a realtionship of our own. 

In the example below a InventTable is being added to the constraint tables with an explicit relationship (InventTable.ItemID == InventItemPurchSetup.ItemID)



The XDS security policies are saved in the database and hence its important to have the project "Synchronize Database on build" turned on when changes are being done to the security policy. The table where the security filters are saved is ModelSecPolRuntimeEx. This table also stores a  
       
select QUERYOBJECTAOTNAME, CONSTRAINEDTABLE, MODELEDQUERYDEBUGINFO , MODELEDQUERYPACKDATA
from ModelSecPolRuntimeEx 
where [Name] like 'AFZ_NonStoppedItemPolicy'
 
Some times the containers in the database might not get updated and you might get an error as below when the security is applied. 


This only indicates that the Query is not updated in the database. To update the required data in the database against a XDS query execute the below code in a job class. 






Monday, March 22, 2021

Data entities using Dimension for Power BI

When we work with dimension one of the key tables used is the DimensionAttributeValueCombination. However, when we look at the definition of this table in the AOT vs in the database we will notice that there is a difference.

AOT only has a subset of the fields that exists in the physical SQL Table 

AOT View

Certain fields like the SystemGeneratedAttribute are not visible in the AOT. 

SQL View

This is possible because Microsoft introduced a feature for configuration of custom fields in D365 (Platform update 13). This feature is using technology which enables creating table extensions on runtime. As dimensions are configured at runtime and not at design stage, the framework makes use of this feature where a table extension is created at runtime using the configuration to create this columns as table extension. 

When we are required to export the dimension values on a data entity, the process followed is to expose the financial dimensions as separate fields on the entity using extension. These adjustments are made in a resilient manner by using the extension approach, so that minimal maintenance will be required when we upgrade the code base to newer versions in the future. 

  • There is a ready made wizard that is provided to create an entity extension for the required dimensions. This wizard can be accessed from the Dynamics 365 -> Addins -> Add financial dimension for Odata


 In the resulting wizard screen the name of the dimensions required to be exported should be provided and this can be obtained from General Ledger -> Dimensions -> Financial dimension configuration for integrating applications


The resulting dimension combination would be displayed which can then be copied based on the need on the wizard screen.



Once the wizard is completed the extensions would be generated into a new project. This project should be compiled to ensure that the required tables are generated. Its needs to be ensured that the project is marked for database sync on build. 




We are now ready to add the DimensionCombinationentity entity to our existing entity wherever the dimension values are required additionally to be exposed. It should also be ensured that DimensionCombinationentity entity is outer-joined as showed below


Once the join has been established the Dimension fields would be Visible. To make the fields available on the Data Entity, the desired fields should be dragged and dropped on the field node and the necessary relation should be set.




Wednesday, December 09, 2020

Budgeting at Totals

The AX system has two level check for budget. 

  • Level 1: Budget control rule which works at the individual account + dimension combination level.  
  • Level 2: The budget group rule executes a secondary budget check. This is applied after the level 1 check is failed. This is performed at a summary of 1 or more accounts which is created using an entity called budget groups. 
To budget for a group of accounts as a block, we need to create budget group. The budget groups must be created on the **Budget control configuration ** page. The criteria that you specify must include the total main account and the range of accounts. The criteria can further be nested to accommodate multiple queries and when a group is considered then all the queries nested below it are accumulated before the check is performed. This provides enough flexibility to create complex budget groups.

It is also important to note here that sometimes when the budget registers are posted before the budget configurations are enabled, the budget control statistics might not be udpdate. AX now provided a period job to process any such budget register entries that have not been processed or were posted before the budget controls were enabled. 

To process any pending budget register entries we need to do the following: 

  1. We need to ensure that all the financial periods with the budgets are open. To open the financial periods you can go to General Ledger-> Ledget Setup -> Ledger Calender option. 
  2. Once the periods are opened then any pending registers can be processed using the periodic job in Budgeting -> Periodic-> Budget control data maintenance 
Please ensure that the budget control is enabled before the budget control data maintenance is initiated. 

Sunday, September 06, 2020

Outlook out of memory

When you get out of memory error on the outlook client. One of the solutions that worked is as follows:-

1. Goto the below folder and delete all the xml files in there

%appdata%\Local\Microsoft\Outlook\16

2. Start the Microsoft outlook client in safe mode to reconfigure the mails. 


Wednesday, September 02, 2020

AX Dialog : Override controls

 Dialog is a another important framework in AX 2012. When a dialog is created using classes it demands a good understanding of what happens under the hood. 

Each dialogField that is added using the dialog classes is internally given a system name and this name can then be used to attach events to the runtime Field. The fieldName method in the dialog class creates the name for a field being added. 

We can find the systemName that a control has been assigned by calculating it from the sequence it was added in or alternatively we can run the dialog and check the name from the personalization form. 

Once we have the name we can write the extension methods for the control in the class. Follow the following steps for the same

//To allow the system to do Overloading of the function :
public void dialogPostRun(DialogRunbase _dialog)
{
;
super(_dialog);
// allow the dialog infrastructure to raise dialog field events _dialog.dialogForm().formRun().controlMethodOverload(true); _dialog.dialogForm().formRun().controlMethodOverloadObject(this);
}


// To override the lookup method of a field. (For the third field)
private void fld3_1_lookup(FormControl _formControl, str _filterStr)
{
Object control;
;
control = dialog.formRun().controlCallingMethod();
WMSLocation::lookupLocationId(control, DlgFromWrhs.value(),InventLocation::find(DlgFromWrhs.value()).InventSiteId,true);
}

//modified
// To override the modified method of a field. (For the second field)

public boolean fld2_1_modified()
{
boolean                     ret;
Object                      control = dialog.formRun().controlCallingMethod();

WMSLocationIdDefaultIssue   WMSLocationIdDefaultIssue;
;
ret = control.modified();

if (ret)
{
    WMSLocationIdDefaultIssue = InventLocation::find(DlgFromWrhs.value()).WMSlocationIdDefaultIssue;

if (WMSLocationIdDefaultIssue)

DlgFromLocation.value(WMSLocationIdDefaultIssue);

else

DlgFromLocation.value('');

}

return ret;

}


There is a second method which is more concise in cases where we directly want to overload the runtime control properties 


–> A lookup method is required in the first place. Below is the sample code to lookup the exchange rates.

private void journal_Lookup(FormStringControl _control)

{    

    SysTableLookup sysTableLookUp;

    QueryBuildDataSource qbds;


    Query query = new Query();


    qbds = query.addDataSource(tableNum(LedgerJournalTable));    


    qbds.orderMode(OrderMode::OrderBy);

    qbds.addSortField( fieldNum( LedgerJournalTable , JournalNum), SortOrder::Descending);    


    query.allowCrossCompany(true);

    query.addCompanyRange( dlgLegalEntity.value() );        


    sysTableLookUp = SysTableLookup::newParameters(tableNum(LedgerJournalTable), _control, true);

    sysTableLookUp.addLookupfield(fieldNum(LedgerJournalTable, JournalName), false);


    sysTableLookUp.addLookupfield(fieldNum(LedgerJournalTable, JournalNum), true);

    sysTableLookUp.addLookupfield(fieldNum(LedgerJournalTable, Name));

    sysTableLookUp.addLookupfield(fieldNum(LedgerJournalTable, OriginalJournalNum));

    sysTableLookUp.addLookupfield(fieldNum(LedgerJournalTable, OriginalCompany));


    sysTableLookUp.parmQuery(query);

    sysTableLookUp.performFormLookup();


}

–> The above method can then be called in the dialog method of the runbase class


public Object dialog()

{

FormStringControl control;

dialog = super();


    dlgPostPayrolldlg = dialog.addFieldValue( extendedTypeStr(JournalId),postPayrollJournalId, "Journal to split");


   sourceJournalControl = dlgSourceBatch.control();

    journalToSplitControl.registerOverrideMethod(methodstr(FormStringControl, lookUp),methodstr(AFZ_CostAllocChangeProcess, journalToSplit_Lookup),this);


return dialog;


}

Sunday, August 30, 2020

Getting rid of Unidentified Network

 Had a bad network experience for a few days. My network was slow on the machine and was i was losing the connection a no of times in a day. 

Luckily if found a quick fix for the problem. Start the cmd command on an elevated command prompt and enter the following command 

C:\>netsh winsock reset

After this command restart your computer and hopefully the problem would be resolved. 

Friday, May 15, 2020

X++ SysOperation Framework

Firstly, what is a framework:
To understand frameworks we first need to understand libraries. Libraries are a bunch of code that is pre-written and packaged to save our time. When we need to do a task, we just call the appropriate library and it does the job for us. We don’t need to know the details of how the functions inside the libraries work, we just need to know how to call them.

Frameworks are just like libraries in a way that they make our job easier, but we can't call frameworks in the same way as libraries. To use framework, we have to learn the framework, the framework gives us a structure to place and call our code, and not the other way round.

In simple terms framework is to structure what libraries is to code. Using library we reuse code, and using a framework we reuse a class structure.

When we work with X++ there are these set of framework classes that are used all over X++ development.

SysOperation framework:  
The SysOperation is used whenever there is a user interface which triggers a certain functionality. Its quite close to the MVC pattern and work on the similar principles of segregating code to remove dependencies. 

The Model : Data contract
Its the model class from the MVC pattern in which we define attributes we need for our operation, commonly set as parameters by the user in a dialog. A regular class is identified as a SysOperation Data Contract class by adding the DataContractAttribute attribute to its declaraion.

Additionally, if we want a set of methods to be available to us, we can also extend the SysOperationDataContractBase base class. With this class, we can define how our basic dialog will look like to the user. We can define labels, groups, sizes and types of the parameters.

The View : UI Builder
Its an optional class and is the view part from the MVC pattern. Generally AX creates the dialog for us with a standard view, however if are not happy with the standard view of we want to extend it we use the UI Builder class.

The Controller : Controller 
The controller orchestrates the whole operation. It holds information about the operation, such as if it should show a progress form, if it should show the dialog, and its execution mode - asynchronous or not. To create a controller class you should extend the SysOperationServiceController.

Service
While using the MVC we have to understand that not everything is a perfect MVC and as per OOP principles we have to ensure the dependencies between the classes is minimal. Technically one could put the business logic in the controller, however what if the same business logic has to be used outside the controller and without an interaction ? Hence, it a good idea to store the business logic outside the controller and hence we have the service classes. 

The service class stores the business logic. To create a service class we have to extend it from the SysOperationServiceBase class. When constructing your controller, you can indicate which class holds the operation that the controller will trigger.