Reorganizing

This commit is contained in:
Jeremy Vyska 2021-10-30 22:09:32 +02:00
parent a4f6467d78
commit f4886ee235
326 changed files with 4 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -0,0 +1,39 @@
+++
title = "Singleton"
weight = 1090
+++
## Singleton
_By Bogdana Botez at Microsoft Development Center Copenhagen_
[![ ][image0]][anchor0]
**Context: **The pattern described in this article applies to Dynamics NAV only. For the general definition of the **Singleton** pattern, see for example [this link][anchor1].**
**
**Problem**: As a C/AL developer, you need to coordinate action (through a codeunit) or store information (in a table) that is unique across the system.
**Forces:**
* **Lost reference to centralizer:** An instance of a relevant object could attempt to centralize control or data in the system. However, once this object is no longer in scope, the reference to it is lost and cannot be retrieved for later coordination
* **Cannot rebuild the initial state: **A new instance of the same object could be created, however the last known state of the lost instance cannot be known anymore.
**Solution:** create an object which resides in memory in a single copy (instance). Have a way to retrieve this unique object from code. This object can either be a [**Singleton Table**][anchor2], or a [**Singleton Codeunit**][anchor3].
The implementation varies depending on the technology and language used. In object-oriented (OO) languages like C\#, C++ or Java, the **Singleton** uses static classes and class members to instantiate. There is a mechanism to ensure only one instance of the object can exist. This mechanism is many times explicit (like in OO languages) and sometimes implicit as part of the compiler or platform (as it is in NAV).
**Benefits:**
* **Centralization**: the setup information is stored in a single well-known place and easily retrievable from anywhere in the application code, by invoking a Record.GET. In case of a single-instance codeunit, any reference to it will retrieve the same instance, so the context will be preserved.
* **Persistence**: information remains even after the instance goes out of scope, because it continues to live in memory.
**Limitation: **The generic object-oriented **Singleton** pattern permits instantiation of a limited number n of objects (where usually n=1, but it can have other positive values too). However, in Dynamics NAV, the Singleton patterns are limited: n is always 1\.
[anchor0]: 0535.Singleton.png
[anchor1]: https://en.wikipedia.org/wiki/Singleton_pattern
[anchor2]: /nav/w/designpatterns/151.singleton-table
[anchor3]: /nav/w/designpatterns/283.singleton-codeunit
[image0]: 0535.Singleton.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View file

@ -0,0 +1,105 @@
+++
title = "Singleton Codeunit"
weight = 1100
+++
## Singleton Codeunit
_By Bogdana Botez at Microsoft Development Center Copenhagen
_
_[![ ][image0]][anchor0]
_
**Problem**: In some situations, global state needs to be preserved at runtime throughout a session.
There are functionality areas in NAV where centralized application management code is needed, like for example managing permissions, notifications, the debugger etc. State needs to be preserved across calls to the management codeunit.
For example:
* The debugger needs to remember the session which is being debugged
* The permission manager has a testability function, where it can be set to emulate that it's running as a SaaS (Software As A Service -- the cloud) platform, even when the tests run in a "on-premise" local lab.
Take for example the following test of Azure ML (Azure Machine Learning) integration with NAV.
Context: Azure Machine Learning services are paid. However, Dynamics NAV includes a monthly pre-paid quota of Azure ML, which can be used for free by the users. There is an upper limit to this quota, and when it is reached, Azure ML services are turned off until the next month starts and a new quota becomes available for consumption.
The test below checks that, when the monthly quota is exceeded, then the function IsAzureMLLimitReached returns TRUE.
\[Test\]
PROCEDURE AzureMLProcessingTimeExceedsLimit@11();
VAR
AzureMachineLearningUsage@1004 : Record 2002;
ProcessingTime@1000 : Decimal;
BEGIN
// \[SCENARIO\] Azure Machine Learning Processing time exceeds AzureML limit
// \[GIVEN\] AzureMachineLearningUsage \> 0
Initialize; // calls PermissionManager.SetTestabilitySoftwareAsAService(TRUE);
ProcessingTime := LibraryRandom.RandDec(1000,2);
AzureMachineLearningUsage.IncrementTotalProcessingTime(ProcessingTime);
// \[WHEN\] When IsAzureMLLimitReached is invoked with Limit more than Processing time
// \[THEN\] HasAzureLimitReached returns TRUE
Assert.IsTrue(AzureMachineLearningUsage.IsAzureMLLimitReached(ProcessingTime - 1),
'HasAzureLimitReached returns wrong value when Processing time exceeds Limit.');
PermissionManager.SetTestabilitySoftwareAsAService(FALSE);
END;
The figure below explains what happens when the Permission Manager is not a singleton. When it is invoked from different places (first from the test, second from the production code), then different instances of the Permission Manager will fire up and answer. In detail:
1. The test calls Initialize which sets SaaS=TRUE in codeunit Permission Manager
2. The test calls into production code to validate it works as expected. It calls AzureMachineLearningUsage codeunit to find out if the monthly quota has been reached. The function IsAzureMLLimitReached in AzureMachineLearningUsage codeunit is designed only for SaaS. If the code doesn't run in SaaS, then it always returns FALSE.
3. Therefore, a call to PermissionManager is made, to find out if the environment is SaaS.
4. However, a different instance of Permission Manager is reached -- and instance where SaaS was never set to TRUE. This is a mistake -- the test intended to simulate SaaS, but the state it set in the beginning is not reachable from production code.
5. The production code will assess (wrongly) that it's not running SaaS, and say that the Azure ML limit has not been reached (incorrect -- and the test fails).
[![ ][image1]][anchor1]
****
**Solution:** restrict the number of instantiations of a codeunit to only one, by setting the codeunit property **SingleInstance** to **Yes**.
Returning to the previous example, let's analyze the case when the codeunit Permission Manager is a singleton codeunit:
[![ ][image2]][anchor2]
When the codeunit Permission Manager is a singleton, then no matter from where it is invoked, the same instance will be reached. Therefore, the status set by the test (SaaS = TRUE) will be reachable from the production code, and the test will pass, as seen in the figure below.
**[![ ][image3]][anchor3]
**
**Consequences**
1\. Use Singleton Codeunit with care and only when there is no other solution. Preserving a global state could often enough be more harmful than useful. One risk is that tests might fail apparently non-deterministically.
For example, a problem we have met in the development team for Madeira release, was that the singleton codeunit function PermissionManager.SetSoftwareAsAService(TRUE) is often used to emulate and test SaaS conditions. However, if a test 'forgets' to reset the state to default (FALSE), then another codeunit which is not supposed to emulate SaaS, will suddenly run as SaaS and will fail. Even if the test has code that resets the state to FALSE, this code might never be reached because of an earlier failure or other error in the test which would stop execution.
2\. The singleton codeunit is only "alive" for the current session. If the user logs out, the old session is closed and the singleton cleared out so any values stored in the old session's singleton will be lost when the session was closed. When the user logs in again, a new session (with a new fresh instance of the singleton) will be created.
**NAV Usages**
Most of the usages in NAV refer to the so-called "management codeunits". The management codeunits are needed to run, in a centralized way, various modular parts of the application (features), like the CRM integration, Permissions, Workflows etc. Some of the **Singleton Codeunits** in NAV are listed below:
* Codeunit 423 Change Log Management
* Codeunit 1503 Workflow Record Management
* Codeunit 1511 Notification Lifecycle Mgt.
* Codeunit 1629 Office Attachment Manager
* Codeunit 1632 Office Error Engine
* Codeunit 5150 Integration Management
* Codeunit 9002 Permission Manager
* Etc.
**Note:** while the object-oriented **Singleton** pattern can restrict the number of instantiations of the singleton to an integer n \> 0, in Dynamics NAV the **Singleton Codeunit** can only have n=1\.
__
[anchor0]: Singleton-Codeunit.png
[anchor1]: Singleton-Codeunit-_2D00_-example-_2D00_-bad.PNG
[anchor2]: 2313.Singleton-Codeunit-_2D00_-CSIDE-SingleInstance-property.PNG
[anchor3]: Singleton-Codeunit-_2D00_-example-_2D00_-good.PNG
[image0]: Singleton-Codeunit.png
[image1]: Singleton-Codeunit-_2D00_-example-_2D00_-bad.PNG
[image2]: 2313.Singleton-Codeunit-_2D00_-CSIDE-SingleInstance-property.PNG
[image3]: Singleton-Codeunit-_2D00_-example-_2D00_-good.PNG

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View file

@ -0,0 +1,100 @@
+++
title = "Singleton Table"
weight = 1110
+++
## Singleton Table
_By Elly Nkya at Microsoft Development Center Copenhagen_
## [![ ][image0]][anchor0]
_
_
**Problem**: The developer needs to define a single record that can contain a set of rules and behavior (optional, mandatory, or defaulting mechanisms), that apply to a functionality, and can be configured by a user.
****
**Forces**
* You want a central place to define the address and logo of your company (see Company Information table).
* You want to define the no. series that should be used for your sales documents (see Sales & Receivables Setup table).
* You want to know whether your sales documents should be archived (see Sales & Receivables Setup table).
* You want to define the rounding accuracy your system should (see General Ledger Setup table).
**Solution:** Define a single record that can contain a set of rules and behavior (optional, mandatory, or defaulting mechanisms), that apply to a functionality, and can be configured by a user.
In a functionality that is large enough (such as sales, inventory, fixed) you may want to define a global set of rules, that are configurable by the user.
**Implementation**
**1\. Define: **Create a Setup Table with Dummy a Primary Key. Typically with type Code=10\. Then add fields to define the global rules.
**2\. Instantiate: **Place the instantiation code in a central place where it is guaranteed to be invoked before the functionality uses it. This is done in Codeunit 2\.
**3\. Enforce: **Give the user access to the record so that he can change the default setup, by creating a Card page. On the page, enforce the singleton to prevent deletion of the record or insertion of a new record
**4\. Use: **Access the rule in code and use it
****
**NAV Usages**
Rounding rules for Unit-Amounts and Amounts are implemented using the Singleton pattern.
**1\. Define:** The General Ledger Setup is used for this.
**2\. Instantiate:** In codeunit 2, the following code is invoked
WITH GLSetup DO
IF NOT FINDFIRST THEN BEGIN
INIT;
INSERT;
END;
**3\. Enforce:** On the General Ledger Setup. The following properties are setup:
DeleteAllowed=false,
InsertAllowed=false
**4\. Use:** Access the rounding rules are used
...
GLSetup.GET;
UnitCostCurrency := ROUND(...,GLSetup."Unit-Amount Rounding Precision");
...
Or if accessing the rule multiple times and performance is a consideration, use lazy instantiation:
...
GetGLSetup;
UnitCostCurrency := ROUND(...,GLSetup."Unit-Amount Rounding Precision");
...
LOCAL GetGLSetup()
IF NOT GLSetupRead THEN
GLSetup.GET;
GLSetupRead := TRUE;
**Related topics**
[Singleton design pattern][anchor1].
The **Singleton Table** has two established applications in Dynamics NAV:
1. [**Setup Tables**][anchor2] -- which are commonly storing user setup data in NAV,
2. **Cue Tables** -- used to calculate values for the visual representation of Cues on the NAV role center pages.
YouTube Video of NAV Singleton:
[watch?v=aQPu s9FkYI&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=13][anchor3]
[anchor0]: 5554.Singleton-Table.png
[anchor1]: https://en.wikipedia.org/wiki/Singleton_pattern
[anchor2]: /nav/w/designpatterns/76.setup-table
[anchor3]: https://www.youtube.com/watch?v=aQPu-s9FkYI&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=13
[image0]: 5554.Singleton-Table.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View file

@ -0,0 +1,141 @@
+++
title = "Cue Table"
weight = 440
+++
## Cue Table
_By Bogdana Botez at Microsoft Development Center Copenhagen
_
_[![ ][image0]][anchor0]
_
Cues are the second usual application of the [**Singleton Table**][anchor1] pattern in Dynamics NAV, after [**Setup Tables**][anchor2].
**Context**: The user gets overview information about the business on the Dynamics NAV Role Center page.
Figure 1 - Cue information in Dynamics NAV shows cue information seen by the user on the **Sales Order Processor** role center.
[![ ][image1]][anchor3]
The overview information consists of summed-up numbers, calculated from business data, like for example how many sales orders are still open, how many shipments are ready to go, or partially shipped, how many documents are waiting for approval etc.
**Problem**: NAV stores data in tables. By definition, a table is a repetitive structure containing multiple lines, each line having a different piece of the information. But sometimes this repetitive information needs to be summed-up or otherwise synthetized, and presented as an overview.
**
**
**Solution:** Store overview information in a singleton table.
****
There are two ways of calculating overview information in NAV.
1. By using a FlowField. This applies for simpler calculations, like filtered or unfiltered counts, sums etc.
2. By writing C/AL code to perform custom calculations. Use this when:
* * The way to calculate the overview is too complex for flow fields, or
* The data needs to be pulled from an external system (like Dynamics CRM, QuickBooks or any external integration).
**
**
The implementation of Cues is already described in detail on MSDN, in [Creating and Customizing Cues][anchor4] and in [Walkthrough: Creating a Cue Based on a FlowField][anchor5].
**NAV Usages**
Table 1 - Cue tables in Dynamics NAV****shows some examples of singleton tables used for creating Cues.
Table ID
Table Name
1313
Activities Cue
5370
CRM Synch. Job Status Cue
9042
Team Member Cue
9050
Warehouse Basic Cue
9051
Warehouse WMS Cue
9052
Service Cue
9053
Sales Cue
9054
Finance Cue
9055
Purchase Cue
9056
Manufacturing Cue
9057
Job Cue
9058
Warehouse Worker WMS Cue
9059
Administration Cue
9060
SB Owner Cue
9061
RapidStart Services Cue
9063
Relationship Mgmt. Cue
9069
O365 Sales Cue
9070
Accounting Services Cue
Table 1 - Cue tables in Dynamics NAV
___
_
[anchor0]: Cue-Table.png
[anchor1]: /nav/w/designpatterns/151.singleton-table
[anchor2]: /nav/w/designpatterns/76.setup-table
[anchor3]: Cue-Table-Figure-1.JPG
[anchor4]: https://msdn.microsoft.com/en-us/library/dn789553(v=nav.90).aspx
[anchor5]: https://msdn.microsoft.com/en-us/library/ff477101(v=nav.90).aspx
[image0]: Cue-Table.png
[image1]: Cue-Table-Figure-1.JPG

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View file

@ -0,0 +1,73 @@
+++
title = "Setup Table"
weight = 1070
+++
## Setup Table
_By Abhishek Ghosh, at Microsoft Development Center Copenhagen_
## [![ ][image0]][anchor0]
This is the first and most well-known of the two usual applications of the **Singleton Table** pattern in Dynamics NAV.
**Problem:** the developer needs to store information about the operating setup or environment in the database, in a way that can be persisted across sessions.
**Solution:** The information is stored in a table with one record only. The user is subsequently able to modify, but not add or delete records in the table.
The implementation of the pattern involves several considerations:
* Suffixing the table name with Setup (ex: General Ledger Setup).
* Defining a suitable primary key
* Creating a page where the user can view and edit a record, but not add new records or delete an existing one
* Optionally, updating the Company - Initialize codeunit.
**Defining a Primary Key**
Since this kind of tables is a collection of several environment or setup parameters, the primary key does not refer to any business attributes for this kind of tables. However, for maintaining the integrity of the database, it is necessary to define a primary key.
So, the most common implementation is to have a field "Primary Key" of Code\[10\]. This is populated with a blank value when the record is inserted. This field is not added to the page, so that the user cannot be modify it later.
**Creating a Page**
The **CardPage** type is most suitable for representing this kind of tables. In addition, the **InsertAllowed** and **DeleteAllowed** properties in the page should be set to false to prevent the user from adding or deleting records in the table.
In the **OnOpenPage** trigger, the following code should be added to insert a record when the user opens the page for the first time, if a record does not exist already.
OnOpenPage()
RESET;
IF NOT GET THEN BEGIN
INIT;
INSERT;
END;
The following diagram describes the flow of the program, once the user tries to access the setup information. The user opens the page. If the record containing setup information already exists, then the page opens on the existing record. Else, a new empty record is created and the page opens on it.
[![ ][image1]][anchor1]
**Company-Initialize Codeunit**
The Company-Initialize codeunit (codeunit 2) is executed when a new company is created. We recommended that you add records to the single-record tables in this codeunit. If some of the fields are expected to have default values, they can also be populated here.
**NAV Usages**
Several Setup tables in NAV implement this pattern. Some of those are:
* Table 98 General Ledger Setup
* Table 311 Sales & Receivables Setup
* Table 312 Purchases & Payables Setup
* Table 313 Inventory Setup
* Table 242 Source Code Setup
**Variation: **While most tables just insert a record with empty primary key in codeunit 2, table 242 ("Source Code Setup") offers an example of inserting default values into all fields of the table (method "InitSourceCodeSetup"). This practice, wherever feasible, is likely to reduce the effort during implementation.
**Related resources:** [Considerations on optimizing the Singleton Table, by Søren Klemmensen][anchor2].
[anchor0]: Setup-Table.png
[anchor1]: 6675.NAVSetupTablePattern2.png
[anchor2]: http://www.klemmensen.ca/Blog/Post/35/Initialize-Setup-Tables
[image0]: Setup-Table.png
[image1]: 6675.NAVSetupTablePattern2.png