diff --git a/content/NAVPatterns/1-sensitive-data-encapsulation/Data-Encapsulation-_2D00_-figure-1.png b/content/NAVPatterns/1-sensitive-data-encapsulation/Data-Encapsulation-_2D00_-figure-1.png new file mode 100644 index 00000000..a0c7b342 Binary files /dev/null and b/content/NAVPatterns/1-sensitive-data-encapsulation/Data-Encapsulation-_2D00_-figure-1.png differ diff --git a/content/NAVPatterns/1-sensitive-data-encapsulation/Logo-_2D00_-Protected-Data-Encapsulation.png b/content/NAVPatterns/1-sensitive-data-encapsulation/Logo-_2D00_-Protected-Data-Encapsulation.png new file mode 100644 index 00000000..65ebd0ff Binary files /dev/null and b/content/NAVPatterns/1-sensitive-data-encapsulation/Logo-_2D00_-Protected-Data-Encapsulation.png differ diff --git a/content/NAVPatterns/1-sensitive-data-encapsulation/Multi-_2D00_-1-2.JPG b/content/NAVPatterns/1-sensitive-data-encapsulation/Multi-_2D00_-1-2.JPG new file mode 100644 index 00000000..0ad6ad70 Binary files /dev/null and b/content/NAVPatterns/1-sensitive-data-encapsulation/Multi-_2D00_-1-2.JPG differ diff --git a/content/NAVPatterns/1-sensitive-data-encapsulation/index.md b/content/NAVPatterns/1-sensitive-data-encapsulation/index.md new file mode 100644 index 00000000..f641a053 --- /dev/null +++ b/content/NAVPatterns/1-sensitive-data-encapsulation/index.md @@ -0,0 +1,146 @@ ++++ +title = "1-sensitive-data-encapsulation.md" +weight = 120 ++++ +## Sensitive Data Encapsulation + +_By Bogdana Botez at Microsoft Development Center Copenhagen_ + +_ +_ + +[![ ][image0]][anchor0] + +** +** + +**Aliases:** Encapsulation, Separation of Concerns \[1\] + +** +** + +**Context**: You want to store and protect sensitive data which already exists in a system, but it is not clear which data needs protection and how to store it. + +**Problem**: Sensitive data is scattered and mixed with other data in various parts of the system (passwords residing in the same table with non-sensitive data, part of the private information might be stored in files, hardcoded text constants, hardcoded info as part of the code etc.). + +**** + +**Forces:** + +* **Obscurity:** sensitive data mixed with other data and code makes it hard to have an overview of what needs to be protected. +* **Effort:** the protection mechanisms needs to be applied multiple times, once for each location of the sensitive data. +* **Diversity:** different data storage mediums can require different protection solutions. +* **Cohesiveness:** code, low importance data, highly sensitive data are all monolithically mixed which might make it hard to select and protect only what is important. +* **Low** **Performance**: protecting all data can slow down the system. + +**Solution:** Extract and separate sensitive data into a single known repository. + +To apply this pattern in Dynamics NAV, a table structure similar to Table 1261 Service Password can be used. The Service Password table also contains additional functionality which will help to further apply related patterns like [**Access Control**][anchor1] and [**Encryption**][anchor2]. + +Figure 1 describes the definition of a table which is already available in Dynamics NAV. This table can be used for storing sensitive data. As a minimum, the table only needs two fields: + +1. The key is of type GUID (Globally Unique Identifier), which is a 128-bit value consisting of multiple groups of hexadecimal digits \[2\]. Each key needs to be unique and will be used for storing and retrieving the protected information. +2. The value (the actual data to be encapsulated) is of type BLOB (Binary Large OBject) \[3\], which contains the encrypted or un-encrypted data (for encryption, see the related [**Encryption** ][anchor2]pattern). + +[![Figure 1- Example definition, table used for Data Encapsulation][image1]][anchor3] + +_Figure 1- Example definition, table used for **Sensitive** **Data** **Encapsulation**_ + +** +** + +Let's use a software system (which can be a Dynamics NAV extension or customization). Chances are that the system will look similar to the one described in part 1 of Figure 2: there is data handled in various places of the system, on various storage solutions. Intertwined with normal data, there is sensitive data. For example: Dynamics CRM (Customer Relationship Management) connection information could be all stored in one table, and consists of the connection URI (normal data), enabled/disabled status (normal data), and connection password (sensitive data). + +Figure 2 illustrates the system before and after applying the **Sensitive Data Encapsulation** pattern. + +* Before: picture part 1 shows the initial system, where most likely the data is scattered across the system. Furthermore, it is stored in different mediums, like + * In a table (possible together with low-importance data) + * Hardcoded (in Dynamics NAV, it can be a text constant, or just plainly typed in the code) + * In files + +Furthermore, actors which have to interact with the data, need to remember where to find each piece of information and how to retrieve it. + +* After: the part 2 of Figure 2 shows the same system after application of **Sensitive Data Encapsulation**. Now, all data is stored in one place, and all actors which interact with it can read it from the unique location. + +[![ ][image2]][anchor4] + +_Figure 2 - Data access before and after **Sensitive** **Data** **Encapsulation.**_ + +. + +**Benefits:** + +* **Clarity:** when all sensitive data is encapsulated in one place, it is clear which is the information that needs to be protected. +* **Simplicity:** easier to protect just a limited number of known resources when they are grouped. +* **Homogeneity: **the same protection can be applied to all data, since it is stored in the same place.**** +* **Separation of concerns: **treat each section of the computer program differently, by separating it and clearly addressing its own requirements and limitations. \[1\] +* **Performance**: data protection techniques like **Access Control** and **Encryption **can now be applied only to the sensitive data (not to everything), which improves the performance of the system. + +**Drawbacks:** + +* **Single point of failure:** a maliciously intended actor has no longer a need to reverse engineer the places where important data is stored. In the unwanted situation when this actor would have already obtained access to the system, they can more easily locate the sensitive information. This is a step towards information disclosure, but mechanisms like [**Encryption** ][anchor2]and logging can provide further protection. +* **Limited Text Length**: there is a limit on how long the encrypted text can be. This limit is imposed by the OS encryption service and it depends on the composition of the text as well as on the system specifics. In NAV, we had implemented the Encrypted Text for text values of max 250 chars, which is enough to cover passwords, person ID numbers, credit card info, but it might turn insufficient in other future scenarios. +* **Nomenclature**: the name of the table **Service Password** is too specific, since it started by being used for passwords, but it has the capability and it now contains other sensitive data like API Keys, credit card numbers etc. + +**References** + +\[1\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Separation\_of\_concerns. + +\[2\] + +"GUID Structure," \[Online\]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx. + +\[3\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Binary\_large\_object. + +\[4\] + +E. Wauters, "How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2". + +\[5\] + +Microsoft, "Multitenant Deployment Architecture," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx. + +\[6\] + +B. Botez, "Setup Table design pattern," Microsoft, 2013\. \[Online\]. Available: https://community.dynamics.com/nav/w/designpatterns/76.setup-table. \[Accessed 31 07 2016\]. + +\[7\] + +"Shotgun Surgery," \[Online\]. Available: https://en.wikipedia.org/wiki/Shotgun\_surgery. \[Accessed 31 07 2016\]. + +\[8\] + +M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999\. + +\[9\] + +"Masking out," \[Online\]. Available: https://en.wikipedia.org/wiki/Data\_masking\#Masking\_out. \[Accessed 29 7 2016\]. + +\[10\] + +"Key Vault," Microsoft, \[Online\]. Available: https://azure.microsoft.com/en-us/services/key-vault/. + +\[11\] + +"How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx. \[Accessed 2 8 2016\]. + +\[12\] + +"sniffer," \[Online\]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef\_sniffer.htm. \[Accessed 02 08 2016\]. + + + +[anchor0]: Logo-_2D00_-Protected-Data-Encapsulation.png +[anchor1]: /nav/w/designpatterns/277.3-single-point-of-acces +[anchor2]: /nav/w/designpatterns/276.2-data-encryption +[anchor3]: Data-Encapsulation-_2D00_-figure-1.png +[anchor4]: Multi-_2D00_-1-2.JPG + + +[image0]: Logo-_2D00_-Protected-Data-Encapsulation.png +[image1]: Data-Encapsulation-_2D00_-figure-1.png +[image2]: Multi-_2D00_-1-2.JPG diff --git a/content/NAVPatterns/2-anti-patterns/index.md b/content/NAVPatterns/2-anti-patterns/index.md new file mode 100644 index 00000000..871ef0d0 --- /dev/null +++ b/content/NAVPatterns/2-anti-patterns/index.md @@ -0,0 +1,17 @@ ++++ +title = "2-anti-patterns.md" +weight = 130 ++++ +Some of the software development practices, had **not** stood the test of time. Despite that, some are still being used today by developers everywhere. + +"An **anti-pattern** (or **antipattern**) is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive" (from [Wikipedia][anchor0]) + +Since almost the beginning of the NAV Design Patterns project, we talked about documenting the anti-patterns - but never found the time. Until, spontaneously, the April 1st 2015 article had practically wrote itself in a couple of hours, with priceless contributions coming from Andreas, Elly, Nikola - and last but not least, waldo. + +Best regards, + +Bogdana Botez + + + +[anchor0]: http://en.wikipedia.org/wiki/Anti-pattern diff --git a/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-1.JPG b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-1.JPG new file mode 100644 index 00000000..212c606a Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-1.JPG differ diff --git a/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-2.png b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-2.png new file mode 100644 index 00000000..82a747a9 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-2.png differ diff --git a/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-3.png b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-3.png new file mode 100644 index 00000000..f8827028 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-3.png differ diff --git a/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-4.png b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-4.png new file mode 100644 index 00000000..54928d28 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-4.png differ diff --git a/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-5.png b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-5.png new file mode 100644 index 00000000..545780b6 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Encryption-_2D00_-5.png differ diff --git a/content/NAVPatterns/2-data-encryption/Logo-_2D00_-Encryption.png b/content/NAVPatterns/2-data-encryption/Logo-_2D00_-Encryption.png new file mode 100644 index 00000000..f4a79ce3 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Logo-_2D00_-Encryption.png differ diff --git a/content/NAVPatterns/2-data-encryption/Multi-_2D00_-1-2-3.JPG b/content/NAVPatterns/2-data-encryption/Multi-_2D00_-1-2-3.JPG new file mode 100644 index 00000000..b3c706d1 Binary files /dev/null and b/content/NAVPatterns/2-data-encryption/Multi-_2D00_-1-2-3.JPG differ diff --git a/content/NAVPatterns/2-data-encryption/index.md b/content/NAVPatterns/2-data-encryption/index.md new file mode 100644 index 00000000..f6917d5f --- /dev/null +++ b/content/NAVPatterns/2-data-encryption/index.md @@ -0,0 +1,230 @@ ++++ +title = "2-data-encryption.md" +weight = 140 ++++ +## Encryption + +_By Bogdana Botez at Microsoft Development Center Copenhagen_ + +__ + +_[![ ][image0]][anchor0] +_ + +**** + +**Context**: After applying [**Sensitive Data Encapsulation**][anchor1], all sensitive data is gathered in a known place in the database. This makes it possible to apply further protection best practices. + +**Problem**: If any non-authorized actor manages to get access to a copy of the database, the sensitive data is immediately available in clear-text. + +** +** + +**Forces:** + +* **Accessibility:** anyone who managed to steal a copy of the database can at once read the sensitive information. + +**Solution:** Encrypt sensitive data. Dynamics NAV offers a simple mechanism for data encryption, to be used by NAV developers. + +Figure 1 adds one more step (in continuation of the figure in pattern **[Sensitive Data Encapsulation][anchor2]**), in which the first two panels describe how sensitive data has all been gathered in one known place. This makes the current pattern, **Encryption**, much easier -- since now data needs to be encrypted in only one place. The last panel of Figure 1 shows the system after the next step, **Encryption**, has been implemented. This shows the iterative process of applying patterns and making the code better step by step. + +[![ ][image1]][anchor3] + +_Figure 1- **Encryption** becomes easier after first applying [**Sensitive Data Encapsulation**][anchor1]._ + +**** + +**Usage**: in Dynamics NAV, codeunit 1266 Encryption Management offers an API for encryption of data. The available functionality is described in Table 1\. + +Table 1- Encryption functionality in Dynamics NAV (found in codeunit 1266 Encryption Management) + +**Procedure****** + +**Description****** + +**EnableEncryption** + +Confirms with the user before enabling encryption in all companies of the current database. + +**EnableEncryptionSilently** + +Enables encryption without UI interaction (to be used for web services). + +**DisableEncryption** + +Disables encryption. Has a boolean "Silent" parameter which enables/disables UI interaction. + +**Encrypt** + +Checks that encryption is possible before encrypting the given text. + +**Decrypt** + +Checks that encryption is possible before decrypting the given text. + +**ExportKey** + +If encryption is possible, it shows a confirmation dialog to confirm the export of the encryption key, and proceeds to saving it to a location chosen by the user. + +**ImportKey** + +Imports the encryption key from a user chosen location. + +**ChangeKey** + +Changes the encryption key. + +**IsEncryptionEnabled** + +Returns TRUE is encryption is enabled. + +**IsEncryptionPossible** + +Check is the correct key is present, which only works if encryption is enabled. + +**DeleteEncryptedDataInAllCompanies** + +Confirms through UI and if the user agrees, deletes all data stored in the Service Password table for all companies in the current database. At the end, it deletes the encryption key. + +**User confirmation of encryption** + +Ideally, encryption should be enabled by default. + +However, in some versions of Dynamics NAV, there are places where any user who happens to hit a sensitive field (like a password) is asked if they want to encrypt or not. If user confirmation is needed, then let only the security administrators decide (not any random user). + +To ask the security administrator if they want to enable encryption, plug the code below into the OnValidate trigger of the data field which is to be encrypted. This trigger will then get executed each time there's a change on the password field. For example, if the user is entering a password, then add a call to this procedure to Password -- OnValidate() trigger: + +EncryptionIsNotActivatedQst@1001 : TextConst 'ENU=Data encryption is not activated. It is recommended that you encrypt data. \\Do you want to open the Data Encryption Management window?'; + +LOCAL PROCEDURE CheckEncryption@6(); + +BEGIN + +IF NOT ENCRYPTIONENABLED THEN + +IF CONFIRM(EncryptionIsNotActivatedQst) THEN + +PAGE.RUN(PAGE::"Data Encryption Management"); + +END; + +The code above will guide the user on encrypting, storing the encryption key and choosing a safe password, as follows. Consider for example that NAV is used by a small business, where Stan is the business owner. Hence, Stan has access to all NAV setup and security decisions. Stan wants to enable a connection between NAV and CRM. In NAV, he opens page CRM Connection Setup and enters the URL, user name and password for CRM (Figure 10). When Stan leaves the password field, if data encryption is not enabled, then he sees the confirmation message in Figure 2\. + +[![ ][image2]][anchor4] + +_Figure 2- The administrator is advised to enable encryption._ + +Now Stan becomes aware that there is no encryption and has the opportunity to enable it. If he clicks on "Yes", Stan will be taken to the Data Encryption Management page (Figure 3). + +[![ ][image3]][anchor5] + +_Figure 3- Data Encryption Management page_ + +Stan can now choose "Enable Encryption" from the ribbon which informs him that an encryption key will be created (Figure 4). + +[![ ][image4]][anchor6] + +_Figure 4- The administrator is encouraged to save a copy of the encryption key._ + +Stan has the option to save the encryption key in a safe location. He invokes the action Enable Encryption and is guided forward (Figure 5). + +[![ ][image5]][anchor7] + +_Figure 5- The encryption key needs to be protected by a password._ + +Stan chooses a password, which in this implementation requires minimum 8 characters with at least one uppercase character, one lowercase character and one digit. If the chosen password is too weak, Stan is given information on the expected complexity (Figure 6). + +[![ ][image6]][anchor8] + +_Figure 6- The administrator chooses a strong password._ + +In the end, Stan chooses a location for the encryption key on disk, in a standard file save dialog. The layout of the file save dialog depends on the display target used (web browser, rich client etc.). + +**NAV Usages. **Encryption examples can be found in NAV in the following places: + +* Page 1260 Bank Data Conv. Service Setup +* Page 1270 OCR Service Setup +* Page 5330 CRM Connection Setup +* Table 1275 Doc. Exch. Service Setup + +**Benefits:** + +* **Protection**: even if the database has been compromised, the sensitive data is encrypted hence not immediately accessible. Combined with best user practices like setting strong passwords, encryption can prove to be a very strong protection mechanism. + +**Anti-patterns:** + +* **Performance:** Do not encrypt everything, because it will have a performance impact on the system. Only important information should be encrypted. +* **System calls and "Do It Yourself" solutions**: Although system calls for encryptions are available in NAV (ENCRYPT, DECRYPT and ENCRYPTIONKEY), unless there is no other way, refrain from using them directly. Use instead he API in codeunit 1266 Encryption Management, which is safer to use, because it protects against common mistakes (like attempting to encrypt an already encrypted string, enabling encryption in only one company which makes data not usable in another on the same tenant etc.). Use the [**Single Point of Access **][anchor9]pattern to handle sensitive data which needs to be encrypted. +* **System-level encryption.** The similar codeunit API 1803 Encrypted Key/Value Management is not intended to be reused by partner NAV developers. Normal NAV users do not have permission to access this resource. This stores sensitive data to be accessed by system NAV functionality. + +**References** + +\[1\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Separation\_of\_concerns. + +\[2\] + +"GUID Structure," \[Online\]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx. + +\[3\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Binary\_large\_object. + +\[4\] + +E. Wauters, "How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2". + +\[5\] + +Microsoft, "Multitenant Deployment Architecture," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx. + +\[6\] + +B. Botez, "Setup Table design pattern," Microsoft, 2013\. \[Online\]. Available: https://community.dynamics.com/nav/w/designpatterns/76.setup-table. \[Accessed 31 07 2016\]. + +\[7\] + +"Shotgun Surgery," \[Online\]. Available: https://en.wikipedia.org/wiki/Shotgun\_surgery. \[Accessed 31 07 2016\]. + +\[8\] + +M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999\. + +\[9\] + +"Masking out," \[Online\]. Available: https://en.wikipedia.org/wiki/Data\_masking\#Masking\_out. \[Accessed 29 7 2016\]. + +\[10\] + +"Key Vault," Microsoft, \[Online\]. Available: https://azure.microsoft.com/en-us/services/key-vault/. + +\[11\] + +"How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx. \[Accessed 2 8 2016\]. + +\[12\] + +"sniffer," \[Online\]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef\_sniffer.htm. \[Accessed 02 08 2016\]. + + + +[anchor0]: Logo-_2D00_-Encryption.png +[anchor1]: /nav/w/designpatterns/275.1-sensitive-data-encapsulation +[anchor2]: /nav/w/designpatterns/275.sensitive-data-encapsulation +[anchor3]: Multi-_2D00_-1-2-3.JPG +[anchor4]: Encryption-_2D00_-1.JPG +[anchor5]: Encryption-_2D00_-2.png +[anchor6]: Encryption-_2D00_-3.png +[anchor7]: Encryption-_2D00_-4.png +[anchor8]: Encryption-_2D00_-5.png +[anchor9]: /nav/w/designpatterns/277.3-single-point-of-acces + + +[image0]: Logo-_2D00_-Encryption.png +[image1]: Multi-_2D00_-1-2-3.JPG +[image2]: Encryption-_2D00_-1.JPG +[image3]: Encryption-_2D00_-2.png +[image4]: Encryption-_2D00_-3.png +[image5]: Encryption-_2D00_-4.png +[image6]: Encryption-_2D00_-5.png diff --git a/content/NAVPatterns/3-cal-coding-guidelines/index.md b/content/NAVPatterns/3-cal-coding-guidelines/index.md new file mode 100644 index 00000000..4b0d7224 --- /dev/null +++ b/content/NAVPatterns/3-cal-coding-guidelines/index.md @@ -0,0 +1,25 @@ ++++ +title = "3-cal-coding-guidelines.md" +weight = 150 ++++ +We've decided to publish our current C/AL coding guidelines. They are actual, as per January 2015 when this is published (but might fall out of sync as time goes by). + +You can also [download the C/AL coding guidelines as pdf,][anchor0] all in one document. In contrast, on this wiki, the coding guidelines are published individually. The reason is: give you the chance to comment and share your oppinion on each one. Thanks to [waldo][anchor1] for this idea and for helping out. + +The guidelines are debatable - and it is good when they are generating debate. There is variation of opinion on the rules at Microsoft too. The plan is to simply expose what we use now. And more important, to say that guidelines could be used. Debate on individual guidelines can become heated for any programming language, but the benefit of using some guidelines stays. + +For us, those guidelines are enforced at check-in time - we are using a tool which verifies and only allows compliant check-ins. While this tool is internal and not ready to publish, we had anyways decided to open up and present the rules we use to the community, as inspiration. + +Question: Since we're having the guidelines, how come there is still C/AL code in NAV which doesn't respect them? + +Answer: all new C/AL code is bound to follow the guidelines (else it cannot be checked-in). However, the code that existed before the rules - it does not. We had done cleanup in a certain degree. Now we're gradually improving the old code base as we visit various objects in order to add new functionality, however chances are that code we didn't touch in a long time had remained in its old form. + +We're looking forward to your comments. Where you can, do provide concrete examples of the alternatives, Good and Bad. + +[watch?v=z6skKy0pkmU&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=26][anchor2] + + + +[anchor0]: https://blogs.msdn.microsoft.com/nav/2015/01/09/cal-coding-guidelines-used-at-microsoft-development-center-copenhagen "download the C/AL coding guidelines as pdf" +[anchor1]: /members/waldo/default.aspx "waldo" +[anchor2]: https://www.youtube.com/watch?v=z6skKy0pkmU&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=26 diff --git a/content/NAVPatterns/3-single-point-of-access/Logo-_2D00_-Single-Point-of-Access.png b/content/NAVPatterns/3-single-point-of-access/Logo-_2D00_-Single-Point-of-Access.png new file mode 100644 index 00000000..571894e3 Binary files /dev/null and b/content/NAVPatterns/3-single-point-of-access/Logo-_2D00_-Single-Point-of-Access.png differ diff --git a/content/NAVPatterns/3-single-point-of-access/Multi-_2D00_-1-2-3-4.JPG b/content/NAVPatterns/3-single-point-of-access/Multi-_2D00_-1-2-3-4.JPG new file mode 100644 index 00000000..7c18166f Binary files /dev/null and b/content/NAVPatterns/3-single-point-of-access/Multi-_2D00_-1-2-3-4.JPG differ diff --git a/content/NAVPatterns/3-single-point-of-access/index.md b/content/NAVPatterns/3-single-point-of-access/index.md new file mode 100644 index 00000000..71658581 --- /dev/null +++ b/content/NAVPatterns/3-single-point-of-access/index.md @@ -0,0 +1,114 @@ ++++ +title = "3-single-point-of-access.md" +weight = 160 ++++ +## Single Point of Access + +_By Bogdana Botez at Microsoft Development Center Copenhagen_ + +_[![ ][image0]][anchor0] +_ + +__ + +**Context**: Protected data needs to be used. There are many types of entities which might attempt to use the data. + +**Problem**: If no standard way of accessing data exists, then each entity might attempt to build its own system for handing the sensitive data. The data access layer might be implemented over and over again by each entity, without reuse of known best practices and with a lot of code duplication. + +**** + +**Forces:** + +* **Code duplication: **if each entity attempts to write its own routines for data access, invariably this will bring duplication. +* **No knowledge reuse: **if a bug is found and fixed in one of the implementations, there is no guarantee that all the other implementations will be updated. For example + * **Double-Encryption**: lack of care or knowledge could lead a NAV developer to attempt to double-encrypt strings, which would render them unusable. + * **Multi-company configuration \[4\]**: in NAV, it is possible to store multiple companies on the same tenant \[5\] database. A developer who has not investigated such a configuration and its consequences on encryption, can attempt to encrypt data in (for example) a Setup Table \[6\] of only one company, which would make this table unusable from any unencrypted company (since the server will observe that encryption is enabled, and try to retrieve it as it were enabled for all companies and fails). + * **"Shotgun surgery" \[7\]:** one change in the data access technique (like a new requirement to validate the user's identity before viewing any protected data), calls for updates in every single implementation of data access, if multiple implementations exist. Hence, one change of requirement triggers multiple efforts to update the product. + +**Solution:** In Dynamics NAV the same library which offers [**Encryption**][anchor1], is also intended to be used as a **Single Point of Access**. Write code to create, read and remove sensitive data only through codeunit 1266 Encryption Management, and never directly. + +In Figure 9 (figure numbering is continued from pattern **[Encryption][anchor2]**), the panels 1, 2 and 3 have applied the [**Sensitive Data Encapsulation**][anchor3] and [**Encryption** ][anchor1]patterns. Once data is encapsulated, no matter if it has been encrypted or not, the next pattern, **Single Point of Access**, becomes available as seen in the panels 2 and 3 of Figure 1\. + +You can observe that, in panel 3, each usage needs to access separately the encrypted data. This means that each usage needs to implement again the encryption capabilities. This is resolved in panel 4, where all users access one common API which encrypts, hence the workload of encryption is moved from the usages, to the API, and needs to be implemented only once. + +[![ ][image1]][anchor4] + +_Figure 1- **Single Point of Access **pattern applied._ + +This shows how pattern application is an iterative process, where one step follows another. Refactoring \[8\] the code to apply one pattern, cleans and clarifies the code and in some cases, makes clear the possibility of further refactoring. + +**Usage**: call the procedures available in codeunit 1266 Encryption Management to store and access sensitive data. + +**Benefits:** + +* **Simplicity**: only one implementation exists. +* **Knowledge reuse**: if a bug is found and fixed, there is just one place which needs to be repaired. Therefore, there is no risk that some of the usages would still be flawed by the same bug. For example: + * **Double encryption**: The**Single Point of Access** API already implements knowledge to avoid encryption of already encrypted strings. + * **Multi-company**: The**Single Point of Access** API already implements knowledge for handling encryption in a multi-company setup. + * **Easy maintenance**:****a change in specification needs only one code update. + +**Consequences:** + +* **Single point of failure:** A defect in the access library will affect all usages until it is found and fixed. + +**References** + +\[1\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Separation\_of\_concerns. + +\[2\] + +"GUID Structure," \[Online\]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx. + +\[3\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Binary\_large\_object. + +\[4\] + +E. Wauters, "How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2". + +\[5\] + +Microsoft, "Multitenant Deployment Architecture," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx. + +\[6\] + +B. Botez, "Setup Table design pattern," Microsoft, 2013\. \[Online\]. Available: https://community.dynamics.com/nav/w/designpatterns/76.setup-table. \[Accessed 31 07 2016\]. + +\[7\] + +"Shotgun Surgery," \[Online\]. Available: https://en.wikipedia.org/wiki/Shotgun\_surgery. \[Accessed 31 07 2016\]. + +\[8\] + +M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999\. + +\[9\] + +"Masking out," \[Online\]. Available: https://en.wikipedia.org/wiki/Data\_masking\#Masking\_out. \[Accessed 29 7 2016\]. + +\[10\] + +"Key Vault," Microsoft, \[Online\]. Available: https://azure.microsoft.com/en-us/services/key-vault/. + +\[11\] + +"How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx. \[Accessed 2 8 2016\]. + +\[12\] + +"sniffer," \[Online\]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef\_sniffer.htm. \[Accessed 02 08 2016\]. + + + +[anchor0]: Logo-_2D00_-Single-Point-of-Access.png +[anchor1]: /nav/w/designpatterns/276.2-data-encryption +[anchor2]: /nav/w/designpatterns/276.encryption +[anchor3]: /nav/w/designpatterns/275.1-sensitive-data-encapsulation +[anchor4]: Multi-_2D00_-1-2-3-4.JPG + + +[image0]: Logo-_2D00_-Single-Point-of-Access.png +[image1]: Multi-_2D00_-1-2-3-4.JPG diff --git a/content/NAVPatterns/4-get-involved/index.md b/content/NAVPatterns/4-get-involved/index.md new file mode 100644 index 00000000..4dc547f1 --- /dev/null +++ b/content/NAVPatterns/4-get-involved/index.md @@ -0,0 +1,37 @@ ++++ +title = "4-get-involved.md" +weight = 170 ++++ +**Spread the info** + +NAV Design Patterns are excellent materials for training and knowledge transfer. In your company, you can help new developer get to speed with NAV by recommending them to read and then present to the team one of the most common patterns: [No. Series][anchor0], [Setup Table][anchor1] and definitely [Hooks ][anchor2]which will be a great investment in reducing your upgrade time. The more experienced developers can read directly the newer patterns, like [Surrogate Key][anchor3], [Easy Update][anchor4], [Totals on Subpages][anchor5], [Using Queries instead of nested loops][anchor6] etc. + +**Become a NAV Design Pattern author** + +You have a pattern that you have used successfully? You have ideas on new patterns? You've found some existing design patterns which are used in the product but nobody (except a few) knows how it works, but you find it worth it to explain it for the NAV C/AL developers out there? + +Send your pattern idea to [Bogdana Botez][anchor7] as a private message on the community webpage. Once your first pattern is ready, we will review it as a team, and when signed off, you get author permissions on the Wiki site and from then on, you can continue publishing and editing existing patterns. However, only publish on the Wiki materials that we had signed-off (we don't have moderation capabilities yet, so we count on each author to only make meaningful/agreed changes). + +You and your company also get credit by being mentioned on the pattern and also on our patterns authors page. + +Once you have the idea, writing it down shouldn't take long. You will be helped by adopting [the template ][anchor8]that we've used. + +**Remember the rules** + +When handling design patterns, content quality is critical. We are trying our best to only publish content that is correct, relevant and has been reviewed by multiple developers. Therefore, we review and sign-off all patterns before publishing them (except for the videos made prior to 2015). All text content found on this Wiki and on the NAV Team Blog has been through one, usually multiple iterations of review. If you find something to correct, please comment on the pattern or contact [Bogdana Botez][anchor9], and we will review and update it. + +We are working on creating a set of rules, which would help keeping the content clean and the project on the correct track. [Find the rules here][anchor10]. + + + +[anchor0]: /nav/w/designpatterns/74.no-series.aspx "No. Series" +[anchor1]: /nav/w/designpatterns/76.single-record-setup-table.aspx "Setup Table" +[anchor2]: /nav/w/designpatterns/117.hooks-pattern.aspx "Hooks" +[anchor3]: /nav/w/designpatterns/122.implementation-of-surrogate-keys-using-autoincrement-pattern.aspx +[anchor4]: /nav/w/designpatterns/104.easy-update-of-setup-or-supplementary-information.aspx +[anchor5]: /nav/w/designpatterns/155.totals-and-discounts-on-subpages-sales-and-purchases.aspx +[anchor6]: /nav/w/designpatterns/123.using-cal-query-objects-instead-of-nested-loops.aspx +[anchor7]: /members/bogdana-botez/default.aspx +[anchor8]: /nav/w/designpatterns/107.template-for-writing-nav-design-patterns.aspx +[anchor9]: /members/bogdana-botez/default.aspx "Bogdana Botez" +[anchor10]: /nav/w/designpatterns/239.rules-of-conduct.aspx "Find the rules here" diff --git a/content/NAVPatterns/4-masked-text/Logo-_2D00_-Masked-Text.png b/content/NAVPatterns/4-masked-text/Logo-_2D00_-Masked-Text.png new file mode 100644 index 00000000..77e74923 Binary files /dev/null and b/content/NAVPatterns/4-masked-text/Logo-_2D00_-Masked-Text.png differ diff --git a/content/NAVPatterns/4-masked-text/Masking-_2D00_-CRM-Connection-Setup-page.PNG b/content/NAVPatterns/4-masked-text/Masking-_2D00_-CRM-Connection-Setup-page.PNG new file mode 100644 index 00000000..d1378d6b Binary files /dev/null and b/content/NAVPatterns/4-masked-text/Masking-_2D00_-CRM-Connection-Setup-page.PNG differ diff --git a/content/NAVPatterns/4-masked-text/index.md b/content/NAVPatterns/4-masked-text/index.md new file mode 100644 index 00000000..85cbdf76 --- /dev/null +++ b/content/NAVPatterns/4-masked-text/index.md @@ -0,0 +1,109 @@ ++++ +title = "4-masked-text.md" +weight = 180 ++++ +## Masked Text + +_By Bogdana Botez at Microsoft Development Center Copenhagen_ + +_[![ ][image0]][anchor0] +_ + +__ + +**Aliases:** Masking out + +**Context**: In the user interface (UI) of a software system, the user enters protected information such as a password, an access key, a credit card number etc. + +**Problem**: The entered information is visible during data entry and whenever any user (the one who entered the data, or a foreign user) opens the UI. + +**** + +**Forces:** + +* **Information disclosure:** sensitive data is visible in the UI. + +**Solution:** Use the "Masked" field property to display dots instead of characters on the sensitive text field in the UI. + +**Usage: **Figure 1 shows how an unmasked and a masked field look in Dynamics NAV. On page Microsoft Dynamics CRM Connection Setup, the first two fields (Dynamics CRM URL and User Name) are not masked. The next field (Password) is masked. As the user types text into the Password field, the characters are one by one replaced with dots. When the user had finished typing and had left the Password field (moved focus to another page element), then a pre-defined number of dots is showed in the field, no matter what the real length of the password is. This is done so that the length of the text is not disclosed. Hence, no matter if the text had 5, 10 or 20 characters, as soon as the user leaves the masked field, 10 dots will be visible. + +[![ ][image1]][anchor1] + +_Figure 1 - The field "Password" is masked._ + +To apply this pattern in Dynamics NAV, the developer has two choices: + +**1\. ****Mask everywhere** + +Mask the field in all pages which expose it or will expose it in the future. In this case, masking needs to be set at the table level, by opening the table in design mode and setting the field's property ExtendedDatatype=Masked. + +**2\. ****Mask only in selected pages** + +Mask the field in only a subset of pages. Open the pages where the field should be masked in design mode, open the property page for the field in question, and set ExtendedDatatype=Masked. This option can be used for example when a field should be hidden from most users (in most usual pages), but still visible to administrators in specific pages. + +**Benefits:** + +* **Information protection**: sensitive data is stored and can be used by the system, but once entered it is not visible in the UI anymore. + +**Drawbacks:** + +* **"Forgotten password":** the text in a masked field is hidden from all users, including users who theoretically have the right to see it. In this case, if the developer wishes to disclose the text only to certain users, they have to write extra code (like a lookup trigger) which will verify the user's permissions and if permitted, show or send the clear-text value to the user who requested it. + +**References** + +\[1\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Separation\_of\_concerns. + +\[2\] + +"GUID Structure," \[Online\]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx. + +\[3\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Binary\_large\_object. + +\[4\] + +E. Wauters, "How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2". + +\[5\] + +Microsoft, "Multitenant Deployment Architecture," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx. + +\[6\] + +B. Botez, "Setup Table design pattern," Microsoft, 2013\. \[Online\]. Available: https://community.dynamics.com/nav/w/designpatterns/76.setup-table. \[Accessed 31 07 2016\]. + +\[7\] + +"Shotgun Surgery," \[Online\]. Available: https://en.wikipedia.org/wiki/Shotgun\_surgery. \[Accessed 31 07 2016\]. + +\[8\] + +M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999\. + +\[9\] + +"Masking out," \[Online\]. Available: https://en.wikipedia.org/wiki/Data\_masking\#Masking\_out. \[Accessed 29 7 2016\]. + +\[10\] + +"Key Vault," Microsoft, \[Online\]. Available: https://azure.microsoft.com/en-us/services/key-vault/. + +\[11\] + +"How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx. \[Accessed 2 8 2016\]. + +\[12\] + +"sniffer," \[Online\]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef\_sniffer.htm. \[Accessed 02 08 2016\]. + + + +[anchor0]: Logo-_2D00_-Masked-Text.png +[anchor1]: Masking-_2D00_-CRM-Connection-Setup-page.PNG + + +[image0]: Logo-_2D00_-Masked-Text.png +[image1]: Masking-_2D00_-CRM-Connection-Setup-page.PNG diff --git a/content/NAVPatterns/5-ssl-in-nav/Logo-_2D00_-SSL.JPG b/content/NAVPatterns/5-ssl-in-nav/Logo-_2D00_-SSL.JPG new file mode 100644 index 00000000..e05a60db Binary files /dev/null and b/content/NAVPatterns/5-ssl-in-nav/Logo-_2D00_-SSL.JPG differ diff --git a/content/NAVPatterns/5-ssl-in-nav/SSL-_2D00_-before-and-after.PNG b/content/NAVPatterns/5-ssl-in-nav/SSL-_2D00_-before-and-after.PNG new file mode 100644 index 00000000..ee9359b9 Binary files /dev/null and b/content/NAVPatterns/5-ssl-in-nav/SSL-_2D00_-before-and-after.PNG differ diff --git a/content/NAVPatterns/5-ssl-in-nav/index.md b/content/NAVPatterns/5-ssl-in-nav/index.md new file mode 100644 index 00000000..9ca4b475 --- /dev/null +++ b/content/NAVPatterns/5-ssl-in-nav/index.md @@ -0,0 +1,106 @@ ++++ +title = "5-ssl-in-nav.md" +weight = 190 ++++ +## SSL in NAV + +_By Bogdana Botez at Microsoft Development Center Copenhagen_ + +_[![ ][image0]][anchor0] +_ + +__ + +**Context**: The security of data transmission is just as important as the security of data storage. When data is transmitted over the web, Secure Sockets Layer (SSL) is available to be used with the web client in Dynamics NAV. Microsoft's NAV cloud solution has SSL enabled by default. However, if a partner company chooses to deploy their own NAV, then they need to handle SSL explicitly. + +**Problem**: Although data is stored securely, before it even gets to be stored, it needs to travel the web on a client-server connection, where it is vulnerable. + +**Forces:** + +* **Insecure communication: **When the user enters a password, if unprotected, a network sniffer \[12\] could catch and read it. A sniffer is either a software program or hardware device which examine network traffic. Years ago, sniffers were tools used exclusively by professional network engineers, but nowadays, they are also popular with Internet hackers and people just curious about networking.****A****public Wi-Fi network could easily be eavesdropped by an unwanted actor. + +By using data storage patterns like **Sensitive Data Encapsulation**, **Encryption, Single Point of Access** or **Azure Key Vault**, the sensitive data is preserved securely in the implementation of Dynamics NAV. But before it gets into a secure store, this data needs to be transmitted from the user, through a user interface, on a client-server connection and all the way to the database. Is the data safe while being transmitted? + +**Solution:** To protect the data before it reaches the server, remember to configure SSL (Secure Sockets Layer) in Dynamics NAV. + +_SSL_ is a web protocol that encrypts data that is transmitted over a network to make the data and the network more secure and reliable. A website that is enabled with SSL uses Hypertext Transfer Protocol Secure (HTTPS) instead of Hypertext Transfer Protocol (HTTP) as a communication protocol. + +Figure 1 shows data communication between the client (where the user enters data) and the server (which connects further to the database). Without encryption (left side), data is available in clear text over the wire. A person equipped with a network sniffer can easily intercept and read it. On the right side of the picture, SSL is used to encrypt the user's data. Sniffing the traffic would capture the encrypted stream, but access to the real content would be impeded by encryption. + +**[![ ][image1]][anchor1]** + +_Figure 1 - Data transmission before (http://...) and after SSL encryption (https://...)._ + +_ +_ + +**Usage**: the latest information about how to configure SSL for the web client in Dynamics NAV is found online at on MSDN at [https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx][anchor2]. + +**Benefits:** + +* **Secure communication**: encryption protects the data transmitted over a network, so the data is safe all the way on its journey from the user to the database. + +**Consequences:** + +* **Awareness:** a NAV system administrator might not be aware that they need to enable SSL when using the web client. +* **Extra work:** there is extra effort to enable SSL on a self-administered NAV system. The good news is that Microsoft's cloud NAV solution has SSL by default and no extra work is required from the developer on that aspect. + +**References** + +\[1\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Separation\_of\_concerns. + +\[2\] + +"GUID Structure," \[Online\]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx. + +\[3\] + +"Wikipedia," \[Online\]. Available: https://en.wikipedia.org/wiki/Binary\_large\_object. + +\[4\] + +E. Wauters, "How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2". + +\[5\] + +Microsoft, "Multitenant Deployment Architecture," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx. + +\[6\] + +B. Botez, "Setup Table design pattern," Microsoft, 2013\. \[Online\]. Available: https://community.dynamics.com/nav/w/designpatterns/76.setup-table. \[Accessed 31 07 2016\]. + +\[7\] + +"Shotgun Surgery," \[Online\]. Available: https://en.wikipedia.org/wiki/Shotgun\_surgery. \[Accessed 31 07 2016\]. + +\[8\] + +M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999\. + +\[9\] + +"Masking out," \[Online\]. Available: https://en.wikipedia.org/wiki/Data\_masking\#Masking\_out. \[Accessed 29 7 2016\]. + +\[10\] + +"Key Vault," Microsoft, \[Online\]. Available: https://azure.microsoft.com/en-us/services/key-vault/. + +\[11\] + +"How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client," Microsoft, \[Online\]. Available: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx. \[Accessed 2 8 2016\]. + +\[12\] + +"sniffer," \[Online\]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef\_sniffer.htm. \[Accessed 02 08 2016\]. + + + +[anchor0]: Logo-_2D00_-SSL.JPG +[anchor1]: SSL-_2D00_-before-and-after.PNG +[anchor2]: https://msdn.microsoft.com/en-us/library/hh167264(v=nav.90).aspx + + +[image0]: Logo-_2D00_-SSL.JPG +[image1]: SSL-_2D00_-before-and-after.PNG diff --git a/content/NAVPatterns/actions-images/index.md b/content/NAVPatterns/actions-images/index.md new file mode 100644 index 00000000..9423e258 --- /dev/null +++ b/content/NAVPatterns/actions-images/index.md @@ -0,0 +1,17 @@ ++++ +title = "actions-images.md" +weight = 200 ++++ +All actions must have an image assigned to them. +Bad code + + { 7 ;1 ;Action ; + CaptionML=ENU=Customer - &Balance; + RunObject=Report 121 } + +Good code + + { 7 ;1 ;Action ; + CaptionML=ENU=Customer - &Balance; + RunObject=Report 121 } + Image=Report } diff --git a/content/NAVPatterns/activity-log/Activity-Log-NAV.jpg b/content/NAVPatterns/activity-log/Activity-Log-NAV.jpg new file mode 100644 index 00000000..3e79a015 Binary files /dev/null and b/content/NAVPatterns/activity-log/Activity-Log-NAV.jpg differ diff --git a/content/NAVPatterns/activity-log/Activity-Log.jpg b/content/NAVPatterns/activity-log/Activity-Log.jpg new file mode 100644 index 00000000..eb67c90e Binary files /dev/null and b/content/NAVPatterns/activity-log/Activity-Log.jpg differ diff --git a/content/NAVPatterns/activity-log/index.md b/content/NAVPatterns/activity-log/index.md new file mode 100644 index 00000000..de9c1cb4 --- /dev/null +++ b/content/NAVPatterns/activity-log/index.md @@ -0,0 +1,112 @@ ++++ +title = "activity-log.md" +weight = 210 ++++ +## _by Ciprian Iordache at Microsoft Development Center Copenhagen_ + +## Activity Log + +**Abstract** + +The Activity Log pattern tracks execution of activities. This is a Dynamics NAV specific implementation of the [Audit Log][anchor0] pattern. + +[![ ][image0]][anchor1] + +**Problem** + +In general, integrating with external systems can be very challenging, due to the complexity of the situation -- connectivity issues, asynchronous operations, user errors, etc. These challenges require sometimes re-trying several times, polling the external system, re-send/re-get data as all these activities can succeed but can very well fail. + +Similar challenges exist in situations where a lengthy, complex task, composed of different steps is to be executed by various people in various timeframes. In case of errors (but sometimes also in case of success) there will be a need to track these activities to see what happened and the actual person which did a specific step. + +In all these cases, we need to be able to troubleshoot. + +A tracking/logging functionality could be implemented for each activity/step separately, but this would lead to code duplication and problems in maintaining the code in future. + +In NAV there is already the Change Log functionality which can record all the data changes that have been done to specific tables, specific fields. However, this functionality is not available for activities. Also, there are few places where separate logging/tracking implementations were done but the current pattern proposes an unified, central way of data recording and enables the user to track all/most of the activities. + +**Solution** + +The Activity Log pattern tracks specific outcome of the activities, in order to be able to assess what went wrong/fine or who performed a specific activity. + +Activity Log pattern + +* records the activity and its outcome (error or success messages) +* assembles all messages in one central view and presents them to the user filtered for the specific activity and ordered in reverse chronological order. + +Figure below illustrates the how the Activity Log manifests in the UI. The figure shows a part of an activity log for a posted document that was sent to the document exchange service and illustrates both successful and failed activities. + +[![ ][image1]][anchor2] + +This functionality is implemented in the following way - Activity Log table (TAB710) contains a simple function that allows you to log the result of a task or activity: + +ActivityLog.LogActivity(ContextRecordID,ActivityLog.Status::Failed,ContextDescription,ActivityDescription,ActivityMessage); + +Similar to TAB700 for Error Messaging, the Activity Log table contains a RECORDID that is a link to the parent/context entity. That permits the Activity Log to be used in a generic way, for any kind of entities (tables) and it also permits filtering the data to a specific related entity only before being presenting to the user. + +The following parameters should be provided to the function: + +* RecordID: The record/context for which the activity is logged +* Status: The task/activity outcome +* Descriptions/Messages: fields that will clearly describe the state and outcome of the task + +To show the log, add a page action, with the caption including the name " Log" and link it to the image named "Log": + + { ;1 ;Action ; + Name=ActivityLog; + CaptionML=ENU=Activity Log; + ToolTipML=ENU=View the status and any errors if the document was sent as an electronic document or OCR file through the document exchange service.; + ApplicationArea=\#Basic,\#Suite; + Image=Log; + OnAction=VAR + ActivityLog@1000 : Record 710; + BEGIN + ActivityLog.ShowEntries(RECORDID); + END; + } + +**NAV usages** + +In Dynamics NAV 2016, there is a new feature for sending documents in electronic format to a document exchange service. In this case, sending documents requires multiple steps as it is an asynchronous activity and as such, in order to keep track of what's happening and when the Activity Log functionality was used. That offers later the possibility to see who sent and when a document was sent, when it was dispatched, if any dispatch errors and how many tries have been made until the document was finally dispatched or rejected. + +So as usages in NAV 2016, we have the document exchange and OCR features plus the related posted documents involved in the document exchange feature. + +* COD1294.TXT +* COD1410.TXT +* PAG1270.TXT +* PAG1275.TXT +* PAG143.TXT +* PAG144.TXT +* PAG189.TXT +* TAB112.TXT +* TAB114.TXT +* TAB130.TXT + +**Ideas for improvement** + +Replace the scattered similar functionality (as mentioned above, we have several places having close functionality or similar requirements) with this new pattern. + +**Consequences** + +* Use with caution, similar to the Change Log functionality, as if the pattern will be used extensively in all the activities/operations within NAV, the table might become large containing many records and might cause some performance issues when presenting the data to the client (filtering on the specific activity). +* Do not log private or confidential information (passwords, amounts, salaries, sensitive data), unless you are ok with this data to be showed to all users (even to users which normally would not have access to this data), thus overriding the permission sets. +* Log only essential information (quality over quantity). Can the logged data be used to analyze the problem, or is it just junk data? + +**NAV Versions** + +Supported from NAV 2016 + +**Related Topics** + +Error Message Processing -- provides a similar view and uses similar concepts: has a generic implementation (uses as link the same RECORDID feature) and uses same filtering functionality when displaying the data to the user. + +Audit Log -- as mentioned in the beginning, this pattern is a NAV specific implementation of the audit log pattern. + + + +[anchor0]: http://martinfowler.com/eaaDev/AuditLog.html +[anchor1]: Activity-Log.jpg +[anchor2]: Activity-Log-NAV.jpg + + +[image0]: Activity-Log.jpg +[image1]: Activity-Log-NAV.jpg diff --git a/content/NAVPatterns/argument-table/0218.Argument-Table-image.png b/content/NAVPatterns/argument-table/0218.Argument-Table-image.png new file mode 100644 index 00000000..a6d14a33 Binary files /dev/null and b/content/NAVPatterns/argument-table/0218.Argument-Table-image.png differ diff --git a/content/NAVPatterns/argument-table/index.md b/content/NAVPatterns/argument-table/index.md new file mode 100644 index 00000000..fcbd0c21 --- /dev/null +++ b/content/NAVPatterns/argument-table/index.md @@ -0,0 +1,122 @@ ++++ +title = "argument-table.md" +weight = 220 ++++ +# Argument table pattern + +_By Nikola Kukrika and Waldo_ + +# Abstract + +The Argument Table pattern is used to provide an extension point for adding new arguments without changing the signature. By grouping multiple arguments into a table the code becomes more readable (function signature and the usage of the function). + +[![ ][image0]][anchor0] + +# Problem + +In CAL overloading function signature is not supported. It is also not possible to provide default values for the function arguments. + +When an argument needs to be added to the function, the existing function needs to be extracted to a new method with an additional argument and the original function will call new method. This will cause an upgrade problem in the future, since the entire body of the method is replaced. + +Second commonly occurring problem is option duplication. In order to pass options often they are duplicated in the signature. + +The last problem that can be solved is high number of arguments. Functions with a high number of arguments are hard to understand. Having arguments grouped within the table with a meaningful name will improve readability and make code easier to understanding. + +Few examples of the bad implementations are as illustrated here: + +## Bad example 1 + + +**PROCEDURE FillInVATReturnData@1200001(VAR DeclarationID@1200000 : Code\[20\];VAR LineID@1200001 :** +**Code\[20\];VAR PeerID@1200002 : Code\[20\]; VAR DocumentNo@1200003 : Code\[20\]; VAR NumberOfCopies@1200007 :** +**Integer; VAR Uploaded@1200004 : Boolean; VAR Correction@1200005 : Boolean; VAR HasValidationErr@1200006 :** +**Boolean);** + +Call + +**FillInVATReturnData(NoSeries, NextLineID, CustomerID, DocumentNo, SingleCopy, ???, ??, ...., ...)** + +In this example the code is hard to read and understand. Adding an additional argument will require refactoring of the existing function. Each time a new argument is added a new function will be created. + +## Bad example 2 + +**LOCAL PROCEDURE GetTableSyncSetupW1@3(** +**OldTableId@1002 : Integer;** +**VAR UpgradeTableId@1001 : Integer;** +**VAR TableUpgradeMode@1000 : 'Check, Copy, Move, Force') : Boolean;** +BEGIN +CASE OldTableId OF +DATABASE::"Sales Header": +SetTableSyncSetup(0,TableUpgradeMode::Check,UpgradeTableId,TableUpgradeMode); +DATABASE::"Posting Exch. Column Def": +SetTableSyncSetup(104025,TableUpgradeMode::Copy,UpgradeTableId,TableUpgradeMode); +DATABASE::"Payment Export Data": +SetTableSyncSetup(0,TableUpgradeMode::Force,UpgradeTableId,TableUpgradeMode); +ELSE +EXIT(FALSE); +END; +EXIT(TRUE); +END; + +In this example each time a new argument is added all function calls will have to be updated. Option is duplicated in the signature, which will cause issues if a new option is defined or the existing options are renamed. + +# Solution + +By grouping the arguments within the table it is possible to add additional argument and reuse it where it is needed without changing the signature. + +Multiple parameters are grouped within the single object with a meaningful name so the code becomes more readable. + +It is possible to assign default values and to have the code validation. + +Argument table should preferably be a temporary table since the implementation is simpler. + +The examples of usages addressing problems shown above are: + +## Good example 1 + +New table +TAB 50003 VAT Return Data +**PROCEDURE FillInVATReturnData@1200001(VAR VATReturnData@1200000 : Record 50003);** + +**** + +VATReturnData.INIT; +VATReturnData.NumberOfCopies := GetDefaultNumberOfCopies; +VATReturnData.Uploaded := FALSE; + +FillInVATReturnData(VATReturnData); + +By introducing an argument table, code is much more readable since there is a single argument for a function. It is easy to see which arguments are passed in and which are modified in a function. + +## Good example 2 + +Good example +**PROCEDURE GetTableSyncSetupW1@3(VAR TableSynchSetup@1000 : Record 2000000135);** +BEGIN +SetTableSyncSetup(DATABASE::"Sales Header",0,TableSynchSetup.Mode::Check); +SetTableSyncSetup(DATABASE::"Posting Exch. Column Def",104025,TableSynchSetup.Mode::Copy); +SetTableSyncSetup(DATABASE::"Payment Export Data",0,TableSynchSetup.Mode::Force); +END; + +Option definition is not encapsulated within the table. Arguments are grouped and we can add additional arguments without the need to change the signature. + +# Downsides + +You need to create one more table + +Complex types can't be embedded as fields in tables (cannot have a record field type etc). + +# NAV Usages + +Upgrade Codeunits + +# Related Patterns + +Posting Routine, Select behavior: Setting fields on existing records in order not to change the signatures. + + + +[anchor0]: 0218.Argument-Table-image.png + + +[image0]: 0218.Argument-Table-image.png diff --git a/content/NAVPatterns/begin-as-an-afterword/index.md b/content/NAVPatterns/begin-as-an-afterword/index.md new file mode 100644 index 00000000..68513b29 --- /dev/null +++ b/content/NAVPatterns/begin-as-an-afterword/index.md @@ -0,0 +1,16 @@ ++++ +title = "begin-as-an-afterword.md" +weight = 230 ++++ +When BEGIN follows THEN, ELSE, DO, it should be on the same line, preceded by one space character. Bad code + + IF ICPartnerRefType = ICPartnerRefType::"Common Item No." THEN + BEGIN + ... + END; + +Good code + + IF ICPartnerRefType = ICPartnerRefType::"Common Item No." THEN BEGIN + ... + END; diff --git a/content/NAVPatterns/begin-end/index.md b/content/NAVPatterns/begin-end/index.md new file mode 100644 index 00000000..138b3273 --- /dev/null +++ b/content/NAVPatterns/begin-end/index.md @@ -0,0 +1,54 @@ ++++ +title = "begin-end.md" +weight = 240 ++++ +Only use BEGIN..END to enclose compound statements. +Bad code + + IF FINDSET THEN BEGIN + REPEAT + ... + UNTIL NEXT = 0; + END; + +Good code + + IF FINDSET THEN + REPEAT + ... + UNTIL NEXT = 0; + +Bad code + + IF IsAssemblyOutputLine THEN BEGIN + TESTFIELD("Order Line No.",0); + END; + +Good code + + IF IsAssemblyOutputLine THEN + TESTFIELD("Order Line No.",0); + +Bad code + + IF FINDSET THEN + REPEAT + BEGIN + ... + END; + UNTIL NEXT = 0; + +Good code + + IF FINDSET THEN + REPEAT + ... + UNTIL NEXT = 0; + +Exception + + // Except for this case + IF X THEN BEGIN + IF Y THEN + DO SOMETHING; + END ELSE (not X) diff --git a/content/NAVPatterns/binary-operator-line-start/index.md b/content/NAVPatterns/binary-operator-line-start/index.md new file mode 100644 index 00000000..97d56153 --- /dev/null +++ b/content/NAVPatterns/binary-operator-line-start/index.md @@ -0,0 +1,15 @@ ++++ +title = "binary-operator-line-start.md" +weight = 250 ++++ +Do not start a line with a binary operator. Bad code + + "Quantity to Ship" := + Quantity + - "Quantity Shipped" + +Good code + + "Quantity to Ship" := + Quantity - + "Quantity Shipped" diff --git a/content/NAVPatterns/blank-lines/index.md b/content/NAVPatterns/blank-lines/index.md new file mode 100644 index 00000000..5f0ca478 --- /dev/null +++ b/content/NAVPatterns/blank-lines/index.md @@ -0,0 +1,31 @@ ++++ +title = "blank-lines.md" +weight = 260 ++++ +Do not use blank lines at the beginning or end of any functions, after BEGIN, before END, or inside multiline expressions. Bad code + + PROCEDURE MATRIX\_OnDrillDown@1133(MATRIX\_ColumnOrdinal : Integer); + BEGIN + SetupDrillDownCol(MATRIX\_ColumnOrdinal); + DrillDown(FALSE,ValueType); + END; + +Good code + + PROCEDURE MATRIX\_OnDrillDown@1133(MATRIX\_ColumnOrdinal : Integer); + BEGIN + SetupDrillDownCol(MATRIX\_ColumnOrdinal); + DrillDown(FALSE,ValueType); + END; + +Bad code + + IF NameIsValid AND + Name2IsValid + THEN + +Good code + + IF NameIsValid AND + Name2IsValid + THEN diff --git a/content/NAVPatterns/blocked-entity/2260.BlockedEntityPattern.png b/content/NAVPatterns/blocked-entity/2260.BlockedEntityPattern.png new file mode 100644 index 00000000..d4b6e853 Binary files /dev/null and b/content/NAVPatterns/blocked-entity/2260.BlockedEntityPattern.png differ diff --git a/content/NAVPatterns/blocked-entity/3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png b/content/NAVPatterns/blocked-entity/3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png new file mode 100644 index 00000000..ffba43d8 Binary files /dev/null and b/content/NAVPatterns/blocked-entity/3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png differ diff --git a/content/NAVPatterns/blocked-entity/8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png b/content/NAVPatterns/blocked-entity/8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png new file mode 100644 index 00000000..817956c4 Binary files /dev/null and b/content/NAVPatterns/blocked-entity/8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png differ diff --git a/content/NAVPatterns/blocked-entity/index.md b/content/NAVPatterns/blocked-entity/index.md new file mode 100644 index 00000000..406040e5 --- /dev/null +++ b/content/NAVPatterns/blocked-entity/index.md @@ -0,0 +1,104 @@ ++++ +title = "blocked-entity.md" +weight = 270 ++++ +_by Abhishek Ghosh at Microsoft Development Center Copenhagen_ + +## Abstract + +The Blocked Entity is used when it is required to stop transactions for an entity (mostly master data), temporarily or permanently. + +[![ ][image0]][anchor0] + +## Description + +To block entities through metadata, read this pattern. To do the same thing through data, read [Data Driven Blocked Entity pattern][anchor1]. + +The business entity holds a state that controls if a given transaction is allowed. The state is used by the logic controlling transactions.****The change of state could either be temporary or permanent. + +An example of a temporary halt is when a retail chain selling items has received lot of complaints about an item, and the company wants to stop all transactions, both purchase and sale, with that item until the dealer has clarified the issue with his supplier and possibly received a replacement for the defective stock. Another common example is during counting the physical inventory using cycle counting where the counting is done in one section of a warehouse at a time, so that the regular operations can continue in the other parts of the warehouse. In these situations, it is necessary to block all transactions, such as picks and put-aways, for a bin while warehouse counting is in progress for that bin. + +In contrast, a permanent halt to transactions could be required when an item has become obsolete (or is about to become obsolete), and the company wants to stop further purchase or sale of the item. However, the company wants to maintain the transaction history of the item and, therefore, does not want to delete the item record. + +A simple design implementation of such requirements in Microsoft Dynamics NAV is to add a Blocked field in the entity table (and on the associated page). The implementation takes this state into the logic and checks for the value of this field in related transactions. For most simple scenarios, it is sufficient to have two states on the Blocked field, specifying whether it is allowed to perform transactions for the entity or not. + +In certain situations, however, there could be different levels of blocking. For example, the company could block all sales to a customer that has overdue payments, and the company does not want to allow transactions with this customer until the payments are received. In other situations, the customer may have raised objections about an invoice, and the company has decided not to generate new invoices for the customer until the issue has been resolved. However, the company does want to continue shipping goods to the customer so as not to impact the customer's operations. In these scenarios, it may be necessary to have multiple states on the Blocked field depending on the level of restriction that is needed. + +## Usage + +As mentioned in the previous section, there are two implementations depending on business requirements: The 2-state Boolean field for simple implementations and the multi-state option field for more complex requirements. The implementation flow is similar for both patterns, except how the validation is implemented. The following discusses the two scenarios one by one. + +### Boolean Implementation + +Add a Boolean field named Blocked in the table. + +In the relevant logic, add a condition to check the status of the Blocked flag. The cheapest way is to use a TESTFIELD: + +_.TESTFIELD(Blocked,FALSE);_ + +Alternatively, you can throw a custom error message. However, you should only do that if the default error message thrown by TESTFIELD is not sufficient. + +### Option-Field Implementation + +Add an option field named Blocked in the table. The option values will reflect the different blocked states required by the company. + +Add this field on the card page (or on the List page if the entity does not have a card). As with the Boolean implementation, the convention is to add this field in the right-hand column in the General FastTab of the card page. + +Implement a function in the table that takes the transaction context as input and evaluates the Blocked field to decide whether the transaction should be allowed or not. Optionally, the function can be responsible for notifying the user and bubble up an error message straight away. + +Note: the option field assumes that only one of the multiple options can be active at a time. In other words, the options should be mutually exclusive. + +How not to use the option field in this case: if we want to block an item from sale and/or purchase, the 4 combined options would be **Block none** | **Block Sales** | **Block Purchases** | **Block Sales and Purchases**. This doesn't scale, because if now we need to block another transaction, the number of option would grow too fast. In this situations, it is better to use two Boolean fields: **Blocked Sale**: **true|false** and **Blocked Purchase: true|false**. + +A good example of usage would be for varying the behavior depending on the chosen option, for example by displaying a different error message depending on the reason an Item is blocked. In this case we can have the item **Not Blocked** | **Blocked due to defect** | **Blocked waiting for approval**, etc. + +## NAV Specific Example + +### Boolean Implementation + +[![ ][image1]][anchor2] + +An example of the Boolean implementation on the Item card. + +In codeunit 22 -- Item Jnl.-Post Line, the following lines of code have implemented a check based on the value of the Blocked field: + + IF NOT CalledFromAdjustment THEN + Item.TESTFIELD(Blocked,FALSE); + +### Option-Field Implementation + +[![ ][image2]][anchor3] + +An example of the option field implementation on the Customer card. + +The CheckBlockedCustOnDocs and CheckBlockedCustOnJnls functions in the Customer table are responsible for validating the Blocked state with respect to the input document type. These functions are invoked in several areas, such as posting routines, where a status check on the Blocked field is required. This is a good practice where the Blocked implementation gets more complex, as this encourages reuse and ensures uniformity of implementation. + +## NAV Usages + +Entities where the Blocked Entity has been implemented include: + +* Item +* G/L Account +* Customer +* Vendor +* Bin + +## Related Topics + +The [Released Entity][anchor4]. + +[watch?v=O2R fTSup1o&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=16][anchor5] + + + +[anchor0]: 2260.BlockedEntityPattern.png +[anchor1]: /nav/w/designpatterns/247.data-driven-blocked-entity/edit +[anchor2]: 8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png +[anchor3]: 3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png +[anchor4]: /nav/w/designpatterns/115.released-entity.aspx +[anchor5]: https://www.youtube.com/watch?v=O2R-fTSup1o&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=16 + + +[image0]: 2260.BlockedEntityPattern.png +[image1]: 8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png +[image2]: 3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png diff --git a/content/NAVPatterns/by-reference-parameters/index.md b/content/NAVPatterns/by-reference-parameters/index.md new file mode 100644 index 00000000..fbfbb578 --- /dev/null +++ b/content/NAVPatterns/by-reference-parameters/index.md @@ -0,0 +1,25 @@ ++++ +title = "by-reference-parameters.md" +weight = 280 ++++ +Do not declare parameters by reference if their values are not intended to be changed. + +Unintentional value changes might propagate. Also, it might lead people to believe that value changes are intended. + +Bad code + + LOCAL PROCEDURE ShowMessage@15(VAR Text@1000 : Text\[250\]); + BEGIN + Text := GetMessageText; + IF (Text <\> '') AND GenJnlLineInserted THEN + MESSAGE(Text); + END; + +Good code + + LOCAL PROCEDURE ShowMessage@15(Text@1000 : Text\[250\]); + BEGIN + Text := GetMessageText; + IF (Text <\> '') AND GenJnlLineInserted THEN + MESSAGE(Text); + END; diff --git a/content/NAVPatterns/cached-web-service-calls/Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png b/content/NAVPatterns/cached-web-service-calls/Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png new file mode 100644 index 00000000..44cb3432 Binary files /dev/null and b/content/NAVPatterns/cached-web-service-calls/Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png differ diff --git a/content/NAVPatterns/cached-web-service-calls/index.md b/content/NAVPatterns/cached-web-service-calls/index.md new file mode 100644 index 00000000..3498b448 --- /dev/null +++ b/content/NAVPatterns/cached-web-service-calls/index.md @@ -0,0 +1,110 @@ ++++ +title = "cached-web-service-calls.md" +weight = 290 ++++ +_by Mostafa Balat, Microsoft Development Center Copenhagen_ + +## Abstract + +In a service-oriented deployment, web services are used to extend NAV's functionality and reach. Depending on how volatile this data is and the corresponding usage scheme, it is expected to be up-to-date within a pre-defined period of time (e.g. once a day). + +## Description + +When NAV is integrated with external services, then the user scenarios become dependent on the data and functions offered by such services. Eventually, there are different approaches through which the external data can be retrieved, stored and used. + +* Dynamic: either exposed by the external service itself or by a separate catalog that NAV can query. + * Advantage: data is always up-to-date + * Disadvantage: it requires constant connection to the data source. +* Static: hard-coded in the database for the user to benefit from. + * Advantage: data is promptly available when needed. + * Disadvantage: if data changes at some point, it will require a maintenance effort, which exposes the business process to a risk of failure. +* Cached: offered through an external service and gets pulled according to a pre-defined refresh rate or manually. + * Advantage: data is 'up-to-date' within the rules acceptable by the business process, without extra load on the network resources or the external service. + * Disadvantage: if data changes while the auto-refresh did not happen yet, the user may not have access to the latest data; however, the user can manually force a refresh of the data, if asked to do so. + +### When to Use It + +Offer data in lookups that were cached from an external service. + +### Diagram + +[![ ][image0]][anchor0] + +## Usage + +Set up an NAV feature to consume the data from an external service. Refresh the data on a pre-defined refresh rate (e.g. once a day) or when enforced by a power user or an admin. Cache the data in a table and offer it in lookups, as applicable. + +## NAV Specific Example + +### Overview + +**PAG1259 Bank Name - Data Conv. List** offers the required functionality to refresh and display the list of bank names needed to specify which file format to convert to. The page can be accessed from **PAG1260 Bank Data Conv. Service Setup** to display all available bank names. It is also used as a lookup on **PAG370 Bank Account Card**, where it offers a filtered view of the cached bank names based on the Country/Region Code field. + +If **PAG1259 Bank Name - Data Conv. List** is being open and the cached data is 'old', it refreshes the cache. The cached data is stored in **TAB1259 Bank Data Conv. Bank**. Meanwhile, the user has the chance to refresh the data using + +### Code Sample + + OnInit=BEGIN + ShortTimeout := 5000; + LongTimeout := 30000; + END; + OnOpenPage=VAR + BankDataConvBank@1002 : Record 1259; + ImpBankListExtDataHndl@1000 : Codeunit 1289; + CountryRegionCode@1004 : Text; + HideErrors@1003 : Boolean; + BEGIN + CountryRegionCode := IdentifyCountryRegionCode(Rec,GETFILTER("Country/Region Code")); + IF BankDataConvBank.ISEMPTY THEN BEGIN + ImpBankListExtDataHndl.GetBankListFromConversionService(HideErrors,CountryRegionCode,ShortTimeout); + EXIT; + END; + RefreshBankNamesOlderThanToday(CountryRegionCode,HideErrors,ShortTimeout); + END; + OnAction=VAR + ImpBankListExtDataHndl@1000 : Codeunit 1289; + FilterNotUsed@1001 : Text; + ShowErrors@1003 : Boolean; + BEGIN + ShowErrors := TRUE; + ImpBankListExtDataHndl.GetBankListFromConversionService(ShowErrors,FilterNotUsed,LongTimeout); + END; + LOCAL PROCEDURE IdentifyCountryRegionCode@1(VAR BankDataConvBank@1002 : Record 1259;Filter@1000 : Text) : Text; + VAR + CompanyInformation@1001 : Record 79; + BlankFilter@1003 : Text; + BEGIN + BlankFilter := ''''''; + IF Filter = BlankFilter THEN BEGIN + CompanyInformation.GET; + BankDataConvBank.SETFILTER("Country/Region Code",CompanyInformation."Country/Region Code"); + EXIT(BankDataConvBank.GETFILTER("Country/Region Code")); + END; + EXIT(Filter); + END; + LOCAL PROCEDURE RefreshBankNamesOlderThanToday@5(CountryRegionCode@1000 : Text;ShowErrors@1002 : Boolean;Timeout@1004 : Integer); + VAR + BankDataConvBank@1001 : Record 1259; + ImpBankListExtDataHndl@1003 : Codeunit 1289; + BEGIN + IF CountryRegionCode <\> '' THEN + BankDataConvBank.SETFILTER("Country/Region Code",CountryRegionCode); + BankDataConvBank.SETFILTER("Last Update Date",'<%1',TODAY); + IF BankDataConvBank.FINDFIRST THEN + ImpBankListExtDataHndl.GetBankListFromConversionService(ShowErrors,CountryRegionCode,Timeout); + END; + +## NAV Usages + +Bank name lookup on the Bank Account card for dynamically identifying the format to use to generate a bank-specific payment file. + +## Ideas for Improvement + +Expose the refresh rate through a setup table to make it easily configurable without changing the code. + + + +[anchor0]: Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png + + +[image0]: Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png diff --git a/content/NAVPatterns/captionml-for-system-tables/index.md b/content/NAVPatterns/captionml-for-system-tables/index.md new file mode 100644 index 00000000..575ee497 --- /dev/null +++ b/content/NAVPatterns/captionml-for-system-tables/index.md @@ -0,0 +1,26 @@ ++++ +title = "captionml-for-system-tables.md" +weight = 300 ++++ +CaptionML should always be specified on a page field for a system table. By default, system tables do not have captions, so if you need to use them in the UI then captions need to be added. + +Bad code + + ... + { 2 ;2 ;Field ; + SourceExpr=Name } + ... + OBJECT Table 2000000000 User + ... + { 2 ; ;Name ;Text50 } + +Good code + + ... + { 2 ;2 ;Field ; + CaptionML=ENU=Name; + SourceExpr=Name } + ... + OBJECT Table 2000000000 User + ... + { 2 ; ;Name ;Text50 } diff --git a/content/NAVPatterns/case-actions/index.md b/content/NAVPatterns/case-actions/index.md new file mode 100644 index 00000000..09050457 --- /dev/null +++ b/content/NAVPatterns/case-actions/index.md @@ -0,0 +1,17 @@ ++++ +title = "case-actions.md" +weight = 310 ++++ +A CASE action should start on a line after the possibility. Bad code + + CASE Letter OF + 'A': Letter2 := '10'; + 'B': Letter2 := '11'; + +Good code + + CASE Letter OF + 'A': + Letter2 := '10'; + 'B': + Letter2 := '11'; diff --git a/content/NAVPatterns/class-coupling/index.md b/content/NAVPatterns/class-coupling/index.md new file mode 100644 index 00000000..5153c96f --- /dev/null +++ b/content/NAVPatterns/class-coupling/index.md @@ -0,0 +1,18 @@ ++++ +title = "class-coupling.md" +weight = 320 ++++ +Do not write functions that have high class coupling. This makes the code hard to maintain. + +Bad code + + Any procedure / trigger that has class coupling of \> 30 + + + +Good code + + Any procedure / trigger that has class coupling of <= 30\. + Class coupling is computed by summing the unique instances of the following in a code block: + - every unique usage of a complex C/AL data type (table, codeunit, etc) as 1\. + - every unique usage of a DotNet type as 1\. diff --git a/content/NAVPatterns/code-of-conduct/index.md b/content/NAVPatterns/code-of-conduct/index.md new file mode 100644 index 00000000..645f6d5b --- /dev/null +++ b/content/NAVPatterns/code-of-conduct/index.md @@ -0,0 +1,12 @@ ++++ +title = "code-of-conduct.md" +weight = 330 ++++ +Find below the rules to be used when disseminating or relating to the NAV Design Patterns. + +1. Only use materials published in text on the NAV Design Patterns Wiki site. If you received from us, any unpublished materials, please observe that they are subject to change and have not been approved for external use. +2. When referencing a NAV Design Pattern, you must remember to also reference its author and company where the author is employed. You will find the author and his/her company at the beginning of each pattern, under the title. +3. When referencing a NAV Design Patterns project, you must make it clear that this is a community project, driven by Microsoft, with multiple developers involved from both Microsoft and the community. +4. When using published text content of NAV Design Patterns, do not alter the text in any way that was published on the Wiki site, unless is has been reviewed by the patterns team and signed off by someone at Microsoft in writing. +5. If you have other materials which have not received explicit signoff in writing from me, where I have specifically stated that they are valid design patterns ready for publishing, please do not name them "NAV Design Patterns" (or anything similar). You are free to use your own content, but do not associate it in any way with NAV Design Patterns unless it is signed off in writing. +6. If you do choose to use your own content, you must make it clear that it is not a NAV Design Pattern. diff --git a/content/NAVPatterns/colon-usage-in-case/index.md b/content/NAVPatterns/colon-usage-in-case/index.md new file mode 100644 index 00000000..e72a8cdd --- /dev/null +++ b/content/NAVPatterns/colon-usage-in-case/index.md @@ -0,0 +1,15 @@ ++++ +title = "colon-usage-in-case.md" +weight = 340 ++++ +The last possibility on a CASE statement must be immediately followed by a colon. Bad code + + CASE DimOption OF + DimOption::"Global Dimension 1" : + DimValue."Dimension Code" := GLSetup."Global Dimension 1 Code"; + +Good code + + CASE DimOption OF + DimOption::"Global Dimension 1": + DimValue."Dimension Code" := GLSetup."Global Dimension 1 Code"; diff --git a/content/NAVPatterns/comments-curly-brackets/index.md b/content/NAVPatterns/comments-curly-brackets/index.md new file mode 100644 index 00000000..4952f27a --- /dev/null +++ b/content/NAVPatterns/comments-curly-brackets/index.md @@ -0,0 +1,39 @@ ++++ +title = "comments-curly-brackets.md" +weight = 350 ++++ +Never use curly bracket comments. During development, the "Block comment" functionality can be used instead. However, in production code, block comments are not recommended. Bad code + + PeriodTxt: {Period} + + + +Good code + + PeriodTxt: // Period + + + +Bad code + + PROCEDURE MATRIX\_OnAfterGetRecord@10(MATRIX\_ColumnOrdinal : Integer); + BEGIN + { + IF ShowColumnName THEN + MatrixHeader := MatrixRecords\[MATRIX\_ColumnOrdinal\].Name + ELSE + MatrixHeader := MatrixRecords\[MATRIX\_ColumnOrdinal\].Code; + } + MatrixRecord := MatrixRecords\[MATRIX\_ColumnOrdinal\]; + AnalysisValue := CalcAmt(ValueType,TRUE); + MATRIX\_CellData\[MATRIX\_ColumnOrdinal\] := AnalysisValue; + END; + +Good code + + PROCEDURE MATRIX\_OnAfterGetRecord@10(MATRIX\_ColumnOrdinal : Integer); + BEGIN + MatrixRecord := MatrixRecords\[MATRIX\_ColumnOrdinal\]; + AnalysisValue := CalcAmt(ValueType,TRUE); + MATRIX\_CellData\[MATRIX\_ColumnOrdinal\] := AnalysisValue; + END; diff --git a/content/NAVPatterns/comments-spacing/index.md b/content/NAVPatterns/comments-spacing/index.md new file mode 100644 index 00000000..8ff92923 --- /dev/null +++ b/content/NAVPatterns/comments-spacing/index.md @@ -0,0 +1,14 @@ ++++ +title = "comments-spacing.md" +weight = 360 ++++ +Always start comments with // followed by one space character. +Bad code + + RowNo += 1000; //Move way below the budget + + + +Good code + + RowNo += 1000; // Move way below the budget diff --git a/content/NAVPatterns/conditional-cascading-update/3124.T18_5F00_Name_5F00_OnValidate.png b/content/NAVPatterns/conditional-cascading-update/3124.T18_5F00_Name_5F00_OnValidate.png new file mode 100644 index 00000000..d6710dd7 Binary files /dev/null and b/content/NAVPatterns/conditional-cascading-update/3124.T18_5F00_Name_5F00_OnValidate.png differ diff --git a/content/NAVPatterns/conditional-cascading-update/index.md b/content/NAVPatterns/conditional-cascading-update/index.md new file mode 100644 index 00000000..ffb79982 --- /dev/null +++ b/content/NAVPatterns/conditional-cascading-update/index.md @@ -0,0 +1,39 @@ ++++ +title = "conditional-cascading-update.md" +weight = 370 ++++ +_by Jan Hoek at IDYN _ + +## **Abstract** + +The Conditional Cascading Update pattern is used to intelligently populate fields whose values depend on other field values. In this pattern description, the field triggering the update will be called "source field", and the depending field will be called "target field". + +## **Description +** + +The value of one table field sometimes depends on the value of another field, typically following an application-defined transformation (note that we're talking about transformations of field values here. This has nothing to do with e.g. form transformation), such as conversion to uppercase, removal of certain characters etc. + +If the target field is non-editable, said transformation is usually the only way for the target field to receive new values, so no irreproducible information can be lost. However, if the target field is editable, the user may have cared enough to override the default (transformed) value, in which case revalidating the source field should not blindly replace the target field's value. + +## **Usage** + +In the OnValidate trigger of the source field, test if the target field value is either blank, or equal to the transformed value of the source field's previous contents. If it is, populate the target field's value with the transformed source field value. If it is not, do nothing (effectively preserving the value set by the user). + +## **NAV Specific Example** + +In the base application, this pattern can be found in Search Name/Search Description fields, which are updated with the uppercase value from the corresponding Name/Description field when the latter is validated, only if the Search Name/Description in question is currently blank, or equal to the (uppercase equivalent) of the previous contents of the Name/Description field. + +[![ ][image0]][anchor0] + +In this particular case, the transformation between source and target fields is implicit and due to the different data types of the fields (text vs. code). Note how the field triggers of the Search Name field itself do not contain any logic linked to this pattern. + +## **Consequences** + +There is a case when this pattern should not be used. If the target field is non-editable, this pattern will not add any value, since there won't be any user-overridden values to protect. + + + +[anchor0]: 3124.T18_5F00_Name_5F00_OnValidate.png + + +[image0]: 3124.T18_5F00_Name_5F00_OnValidate.png diff --git a/content/NAVPatterns/confirm/index.md b/content/NAVPatterns/confirm/index.md new file mode 100644 index 00000000..47d9e789 --- /dev/null +++ b/content/NAVPatterns/confirm/index.md @@ -0,0 +1,16 @@ ++++ +title = "confirm.md" +weight = 380 ++++ +Always end CONFIRM with a question mark. +Bad code + + ChangeAllOpenedEntriesQst@1000 : TextConst 'ENU=Do you want to change all open entries for every customer and vendor that are not blocked'; + ... + IF CONFIRM(ChangeAllOpenedEntriesQst,TRUE) THEN + +Good code + + ChangeAllOpenedEntriesQst@1000 : TextConst 'ENU=Do you want to change all open entries for every customer and vendor that are not blocked?'; + ... + IF CONFIRM(ChangeAllOpenedEntriesQst,TRUE) THEN diff --git a/content/NAVPatterns/copy-document/clip_5F00_image006.jpg b/content/NAVPatterns/copy-document/clip_5F00_image006.jpg new file mode 100644 index 00000000..874cea81 Binary files /dev/null and b/content/NAVPatterns/copy-document/clip_5F00_image006.jpg differ diff --git a/content/NAVPatterns/copy-document/clip_5F00_image008.jpg b/content/NAVPatterns/copy-document/clip_5F00_image008.jpg new file mode 100644 index 00000000..6746d61f Binary files /dev/null and b/content/NAVPatterns/copy-document/clip_5F00_image008.jpg differ diff --git a/content/NAVPatterns/copy-document/clip_5F00_image010.jpg b/content/NAVPatterns/copy-document/clip_5F00_image010.jpg new file mode 100644 index 00000000..7216baff Binary files /dev/null and b/content/NAVPatterns/copy-document/clip_5F00_image010.jpg differ diff --git a/content/NAVPatterns/copy-document/index.md b/content/NAVPatterns/copy-document/index.md new file mode 100644 index 00000000..c4eea72f --- /dev/null +++ b/content/NAVPatterns/copy-document/index.md @@ -0,0 +1,118 @@ ++++ +title = "copy-document.md" +weight = 390 ++++ +_By Bogdan Sturzoiu at Microsoft Development Center Copenhagen_ + +## Abstract + +The goal of the Copy Document pattern is to create a replica of an existing open or closed document (posted or not posted), by moving the lines and, optionally, the header information from the source document to a destination document. + +## Description + +Documents are widely used by most of our customers. Many times, a significant portion of these documents are similar to each other, either by sharing the same customer, vendor, type, or line structure. Being able to re-use a document as a base for creating a new one is therefore an important means of saving time. + +Other business scenarios require that a newly created document is applied to an existing document. For example, in returns management, a return order can be the reversal of an existing order and can therefore be copied from the original order. Other times, there is even a legal requirement to match the document to its source. For example, credit memos need to be applied to the originating Invoice. + +For these reasons, NAV supports the copying of documents as a method to re-use or link documents. + +The Copy Document functionality is used in the following situations: + +* The user wants to create a new open sales document (Quote, Order, Blanket Order, Invoice, Return Order, Credit Memo) based on an existing posted or non-posted sales document (Quote, Blanket Order, Order, Invoice, Return Order, Credit Memo, Posted Shipment, Posted Invoice, Posted Return Receipt, Posted Credit Memo). +* The user wants to create a new open purchase document (Quote, Order, Blanket Order, Invoice, Return Order, Credit Memo) based on an existing posted or non-posted purchase document (Quote, Blanket Order, Order, Invoice, Return Order, Credit Memo, Posted Shipment, Posted Invoice, Posted Return Receipt, Posted Credit Memo). +* The user wants to create a new production order (Simulated, Planned, Firm Planned or Released) based on an existing production order (Simulated, Planned, Firm Planned, Released or Finished). +* The user wants to create a new assembly order based on an existing assembly document (Quote, Blanket Order, Order and Posted Order). +* The user wants to create a new service contract or quote based on an existing service contract or quote. +* The user wants to create all relevant return-related documents. For example, from a sales return order, the user can recreate the involved supply chain documentation, by copying the information upwards to a purchase return order (if the items need to be returned to the vendor), purchase order (if the items need to be reordered), and sales order (if the items need to be re-sent to the customer). + +**Note** + +* Not all to and from combinations are allowed. For example, you can only copy to open document types, since the posted documents are not editable. +* The destination document needs to have the header fully created. For example, a Sales Order will need to have the Sell-To Customer No. populated. + +## Usage + +The Dynamics NAV application developer can take into account using the Copy Document design pattern when they have requirements such as: + +* To provide a quick and efficient way of moving content from a document to another. +* To allow reusing the document history as a template for new documents. +* To allow linking of documents that need to be applied to each other. + +The Copy Document pattern involves the following entities: + +1. Source document tables for document header and line. For example,Sales Header/Line. +2. Destination document tables for document header and line. + +**Note:**The source document header/line and destination document header/line tables do not need to be the same. For example, you can copy a Sales Shipment Header/Lines into a Sales Header/Lines. +3. Copy Document engine: COD6620, Copy Document Mgt. +4. Copy Document report for a specific document type. The report requires the following parameters: + * Source Document Type + * Source Document No. + * Include Header (optional) + * Recalculate Lines (optional) +Example: REP901, Copy Assembly Document + +[![ ][image0]][anchor0] + +## Usage Sequence + +**Precondition**: The user creates a new destination document Header, filling up the required information. + +**Step 1**: The user runs the Copy Document report (element no. 4), filling up the parameters: + +* Source Document Type +* Source Document No. +* Include Header and/or Recalculate Lines (not all Copy Document reports have these). + +**Step 2**: The report copies the information in the source tables (Header and Line) into the destination tables (Header and Line). + +**Post processing**: The user performs additional editing of the destination document. + +The sequence flow of the pattern is described in the following diagram. + +[![ ][image1]][anchor1] + +Example: Copy Sales Document for Credit Memos. + +In the standard version of Microsoft Dynamics NAV, the Copy Document functionality is implemented in the Sales Credit Memo window as shown in the following section. + +\*\*\* + +**Precondition**: The user enters data in PAGE44, Sales Credit Memo. + +[![ ][image2]][anchor2] + +**Step 1**: The user runs REP292, Copy Sales Document from the Sales Credit Memo window, populating the required parameters. The Include Header and Recalculate Lines fields are selected. + +[![ ][image3]][anchor3] + +**Step 2**: The Sales Credit Memo window is populated with information from the source sales document. + +[![ ][image4]][anchor4] + +**Post processing**: The user can now do additional editing of the sales credit memo. + +# NAV Implementations + +1. Copy Sales Document (REP292) +2. Copy Purchase Document (REP492) +3. Copy Service Document (REP5979) +4. Copy Assembly Document (REP901) + +[watch?v=aTiwroXwW0&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=17][anchor5] + + + +[anchor0]: /cfs-file/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image002.gif +[anchor1]: /cfs-file/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image004.gif +[anchor2]: clip_5F00_image006.jpg +[anchor3]: clip_5F00_image008.jpg +[anchor4]: clip_5F00_image010.jpg +[anchor5]: https://www.youtube.com/watch?v=aTiwroXwW_0&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=17 + + +[image0]: /resized-image/__size/750x0/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image002.gif +[image1]: /resized-image/__size/750x0/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image004.gif +[image2]: clip_5F00_image006.jpg +[image3]: clip_5F00_image008.jpg +[image4]: clip_5F00_image010.jpg diff --git a/content/NAVPatterns/create-data-from-templates/2134.Picture6.png b/content/NAVPatterns/create-data-from-templates/2134.Picture6.png new file mode 100644 index 00000000..68676a7a Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/2134.Picture6.png differ diff --git a/content/NAVPatterns/create-data-from-templates/2816.Picture3.png b/content/NAVPatterns/create-data-from-templates/2816.Picture3.png new file mode 100644 index 00000000..7fbf3572 Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/2816.Picture3.png differ diff --git a/content/NAVPatterns/create-data-from-templates/3482.Picture-5.png b/content/NAVPatterns/create-data-from-templates/3482.Picture-5.png new file mode 100644 index 00000000..1e62e630 Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/3482.Picture-5.png differ diff --git a/content/NAVPatterns/create-data-from-templates/4118.Picture1.png b/content/NAVPatterns/create-data-from-templates/4118.Picture1.png new file mode 100644 index 00000000..02767054 Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/4118.Picture1.png differ diff --git a/content/NAVPatterns/create-data-from-templates/4341.Picture4.png b/content/NAVPatterns/create-data-from-templates/4341.Picture4.png new file mode 100644 index 00000000..93d000e2 Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/4341.Picture4.png differ diff --git a/content/NAVPatterns/create-data-from-templates/7271.Picture4.png b/content/NAVPatterns/create-data-from-templates/7271.Picture4.png new file mode 100644 index 00000000..514963fc Binary files /dev/null and b/content/NAVPatterns/create-data-from-templates/7271.Picture4.png differ diff --git a/content/NAVPatterns/create-data-from-templates/index.md b/content/NAVPatterns/create-data-from-templates/index.md new file mode 100644 index 00000000..62b18b1f --- /dev/null +++ b/content/NAVPatterns/create-data-from-templates/index.md @@ -0,0 +1,231 @@ ++++ +title = "create-data-from-templates.md" +weight = 400 ++++ +_by Nikola Kukrika at Microsoft Development Center Copenhagen_ + +## Abstract + +For many records, such as Items, Customers, and Vendors, users have to enter the same sets of data again and again. This is tedious, error-prone (users forget to enter a field or they choose the wrong group), and difficult to learn for some users. + +We can group sets of data as templates to speed up and simplify the process of entering data in Microsoft Dynamics NAV. For example, the process of creating a new customer could be simplified so that users only have to enter information that is specific for every individual customer, e.g. Name and Address/Contact. + +## Description + +This pattern solves the problem of creating new records based on their type. You should use it whenever there is a large set of data that could be grouped in a meaningful way. + +In Microsoft Dynamics NAV 2013 R2, we have extended the Configuration Templates feature so that templates can be used in different languages than the language they were created in. We have also added the ability to set related templates so that related records can be inserted, such as dimensions for customers, items, and vendors. + +The pattern consists of two parts: + +1\. Using templates to create new records or applying templates to existing records + +2\. Defining and updating existing templates + +## Usage + +[![ ][image0]][anchor0] + +Using the patterns involves three steps. + +1) As a first step, we must insert a record. This can be done either through C/AL code or by letting the user create a record using the **New** action. + +2) After the record is created, we must apply the template. This is done by using the **UpdateRecord** function in the **Config. Template Management **codeunit (8612). + +**Config. Template Lines** records reference one **Config. Template Header** record (lines pattern). The lines can be of type: + +* **Field** - Stores a field value that will be applied to the record +* **Related** Template -- References a Config. Template Header record for a related template. + +The **UpdateRecord** function applies values to the record one line at the time. One of the requirements was to be possible to use configuration templates in different language/regional settings than the template was created in. + +To support this scenario, when applying the**Config. Template Line** record, **GLOBALLANGUAGE** is set to the language ID of the field. This is important because the default value is stored as text, so we need to use the same formatting that NAV was running on when the template was created. Otherwise, data types, such as Boolean, Date, etc., will raise validation errors. + +Any updates to a **Config. Template Line** record will automatically update the language ID to the current one. Since lines are applied one by one, it is supported to have lines with different language IDs belonging to the same template. + +3) After we have applied the template to the record, we can insert related templates. For example, when you insert an item, you may want to insert dimensions as well. You must implement the logic to apply or then modify the related templates, since this depends on the logic and the relationship between the records. Lines with **Type = Related Template** are used to reference related templates. + +Code example (Insert a record, apply a template, and insert the related templates): + +**// First insert a record Customer.INSERT(TRUE);** + +**// Apply a template RecRef.GETTABLE(Customer);** + +ConfigTemplateMgt.UpdateRecord(ConfigTemplateHeader,RecRef); + +RecRef.SETTABLE(Customer); + +**// Insert Dimensions -- related templates** + +MiniDimensionsTemplate.InsertDimensionsFromTemplates(ConfigTemplateHeader,Customer."No.",DATABASE::Customer); + +Code to insert related templates (dimensions): + +**FUNCTION InsertDimensionsFromTemplates(ConfigTemplateHeader : Record "Config. Template Header";MasterRecordNo : Code\[20\];TableID : Integer)** + +**// There are multiple records (multiple dimensions per master record)** + +**// We have to set filter****** + +ConfigTemplateLine.SETRANGE(Type,ConfigTemplateLine.Type::"Related Template");**** + +ConfigTemplateLine.SETRANGE("Data Template Code",ConfigTemplateHeader.Code);**** + +**** + +IF ConfigTemplateLine.FINDSET THEN**** + +REPEAT**** + +ConfigTemplateHeader.GET(ConfigTemplateLine."Template Code"); + +**// Ensure that the table where the template belongs to is Dimensions** + +**// We could have other related templates****** + +IF ConfigTemplateHeader."Table ID" = DATABASE::"Default Dimension" THEN**** + +InsertDimensionFromTemplate(ConfigTemplateHeader,MasterRecordNo,TableID);**** + +UNTIL ConfigTemplateLine.NEXT = 0;**** + +**** + +**// Create a new Dimensions Record and link it to the Master Record****** + +**FUNCTION InsertDimensionFromTemplate(ConfigTemplateHeader : Record "Config. Template Header";MasterRecordNo : Code\[20\];TableID : Integer)** + +DefaultDimension.INIT; + +DefaultDimension."No." := MasterRecordNo;**** + +DefaultDimension."Table ID" := TableID;**** + +DefaultDimension."Dimension Code" := GetDefaultDimensionCode(ConfigTemplateHeader);**** + +DefaultDimension.INSERT;**** + +**** + +RecRef.GETTABLE(DefaultDimension);**** + +ConfigTemplateMgt.UpdateRecord(ConfigTemplateHeader,RecRef);**** + +RecRef.SETTABLE(DefaultDimension); + +**To surface the action in the product, you have three options:** + +1. **Recommended** - Implement a separate action called **New from Template**. +2. **Optional** - Implement the apply template function on the document itself. This is especially good in scenarios where users are allowed to change the template. +3. **Alternative** - Remove the new action by configuration or set Insert Allowed to FALSE on the list (this will block the creation of new records from the lookup). Implement an application action named **New** and tie it to your code. + +**Note: ** In Microsoft Dynamics C5 2014, we chose to remove the **New** action with configuration since we wanted to promote the functionality and avoid the confusion in having too many options. However this might be difficult to maintain with a larger set of pages. + +**To view or edit templates, you have two options:** + +1. Use the **Config. Template List** table (8620) and the **Config. Template Header Card **table (8618). + +This is a generic solution that is not very usable and is error-prone (no lookups, checks for length, table relation checks, etc.) The default value is a text field of 250 characters, which might be much more than the field length, and may lead to validation errors when used. Users will most likely not be able to use this page. + +[![ ][image1]][anchor1] + +2\. Implement custom pages resembling the document. + +This is optional if you want to enable the users to create and modify templates. In C5 2014, we created temporary tables with the same fields as the main record. Based on this temporary record, we built a page that resembles a document. + +Example of the **Customer Template** page: + +[![ ][image2]][anchor2] + +The goals of this solution were: + +* To make the setup page resemble a document page so that it is easy to use with basic validation and lookups. +* To have only one place to store templates and maintain only one business logic for applying them, namely in the **Configuration Template Header** table. +* To avoid any lateral effects of doing validation on the temporary master record. Doing validation on fields, even though the record itself is temporary, could permanently modify other data in the database. For example, if you insert a new record in the **Customer** table, even in a temporary table, a Contact record is created, which will not be temporary. +* Testability: It is easy to test through RecordRef that the template table matches the main table. We can compare field lengths, data types, table relations, etc. The test is able to detect that they are out of sync, so it is easy to prevent errors. + +One example in the product is the **Mini Customer Template **table (1300). + +The table itself contains very little code. OnModify, OnInsert, and OnDelete triggers update the **Configuration Header** and **Configuration Lines** tables. The following functions in the **Config. Template Management **codeunit (8612), are used for this: + +* ConfigTemplateManagement.CreateConfigTemplateAndLines +* ConfigTemplateManagement.UpdateConfigTemplateAndLines +* ConfigTemplateManagement.DeleteRelatedTemplates + +The CreateFieldRefArray function is used as an interface function on all the temporary template tables. It builds data to be read/written to the configuration templates. + +To further enhance the usability, we have provided the following additional functionality: + +* Create a template from the existing record: The user opens an existing record and creates a template from that record. All the fields that are defined in the CreateFieldRefArray function are used to create the new template. +* Templates list: This page is used by users to select templates or create new ones. Depending on which templates they are working on, we show different template cards. + +## NAV Specific Example + +In C5 2014, this is the workflow: + +The user opens the **Customers List** window and selects **New** + +**[![ ][image3]][anchor3]** + +**[][anchor3]**From this page, the user can view the template, edit it, or create a new one. Selecting a template will populate the customer card and open a new record. From the existing record, the user has options to save as a template or opening a list of templates to maintain available templates. Selecting a template will populate the customer card and open a new record. From the existing record, the user has options to save as a template or opening a list of templates to maintain available templates. + +[![ ][image4]][anchor4] + +From the **Customer Card Template **window, we can invoke the **Dimensions** action, through which we can define the dimensions that will be inserted together with the template: + +[![ ][image5]][anchor5] + +## NAV Usages + +This pattern is used in Microsoft Dynamics C5 2014 in the following objects: + +* Temporary template tables: + * **Mini Customer Template **table (1300) + * **Mini Item Template **table (1301) + * **Mini Dimensions Template** table(1302) + * **Mini Vendor Template** table (1303) + +* Pages to define templates: + * **Mini Customer Template Card** page (1341) + * **Mini Item Template Card **page (,1342) + * **Mini Dimensions Template List** page (1343) + * **Mini Vendor Template Card** page (1344) + +* Pages that use the templates: + * **Mini Customer List** page (1301) + * **Mini Item List** page ( 1303) + * **Mini Vendor List** page (1331) + +In the standard version of Microsoft Dynamics NAV, we use the **Apply Template** action on the following pages: + +* **Customer Card** page (21) +* **Vendor Card** page (26) +* **Item Card** page (30) +* **Resource Card** page (, 76) +* Other similar cards. + +## Ideas for improvement + +Implement the solution in the standard version of Microsoft Dynamics NAV and extend the Apply Template functionality to insert dimensions. + +It is possible that users end up with a large number of templates if they need many different data combinations. An improvement could be to split templates into smaller groups, grouping only part of the fields that are related, and then apply only these. + +[watch?v=F0CTvoyKSmI&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=20][anchor6] + + + +[anchor0]: 4118.Picture1.png +[anchor1]: 2816.Picture3.png +[anchor2]: 7271.Picture4.png +[anchor3]: 4341.Picture4.png +[anchor4]: 3482.Picture-5.png +[anchor5]: 2134.Picture6.png +[anchor6]: https://www.youtube.com/watch?v=F0CTvoyKSmI&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=20 + + +[image0]: 4118.Picture1.png +[image1]: 2816.Picture3.png +[image2]: 7271.Picture4.png +[image3]: 4341.Picture4.png +[image4]: 3482.Picture-5.png +[image5]: 2134.Picture6.png diff --git a/content/NAVPatterns/create-urls-to-nav-clients/1778.url1.jpg b/content/NAVPatterns/create-urls-to-nav-clients/1778.url1.jpg new file mode 100644 index 00000000..5f99e021 Binary files /dev/null and b/content/NAVPatterns/create-urls-to-nav-clients/1778.url1.jpg differ diff --git a/content/NAVPatterns/create-urls-to-nav-clients/7802.url2.jpg b/content/NAVPatterns/create-urls-to-nav-clients/7802.url2.jpg new file mode 100644 index 00000000..61d080c4 Binary files /dev/null and b/content/NAVPatterns/create-urls-to-nav-clients/7802.url2.jpg differ diff --git a/content/NAVPatterns/create-urls-to-nav-clients/index.md b/content/NAVPatterns/create-urls-to-nav-clients/index.md new file mode 100644 index 00000000..c9e9a338 --- /dev/null +++ b/content/NAVPatterns/create-urls-to-nav-clients/index.md @@ -0,0 +1,298 @@ ++++ +title = "create-urls-to-nav-clients.md" +weight = 410 ++++ +_By Mike Borg Cardona and Bogdana Botez at Microsoft Development Center Copenhagen_ + +## Abstract + +This article illustrates NAV platform functionality to be used by C/AL developers. + +The URL builder function, GETURL, is released in Microsoft Dynamics NAV 2013 R2 to reduce coding time for developers who need to create various URL strings to run application objects in either the win client, the web client, or on web services. In addition, the GETURL function makes multitenancy features more transparent to C/AL developers. + +## Description + +Ever had to construct win client URLs like the one below? + +dynamicsnav://myserver:7046/myInstance/myCompany/runpage?page=26 + +Today, Microsoft Dynamics NAV also provides a web client. This means that you must update your code to construct web client URLs too. What about multitenancy? The URL Builder should know if it is running in a multitenant setup and it should know how to choose the right tenant. What about maintaining this code? + +The good news is that GETURL has been introduced to handle all URL building for you. + +GETURL automatically handles: + +* Multitenancy +* Correct URL format for each client +* Publicly accessible hostnames. + +## Usage + +The format is: + +\[String :=\] GETURL(ClientType\[, Company\]\[, Object Type\]\[, Object Id\]\[, Record\]) + +Where: + +* **Client Type** can be: Current, Default, Windows, Web, SOAP, or OData. This enables a range of scenarios for the C/AL developer, such as moving to the web client without changing code to decide where the URL should point to. This is done either by setting Client Type to Current, and just ensuring that web is used to invoke the link creation, or by setting Client Type to Default and changing its value to Web when it is ready to move to the web platform. +* **Object Type** and **Object ID** define the type of the application object to run (Table, Page, Report, Codeunit, Query, or XMLport) and its ID. +* **Record** specifies the actual data to run the URL on, such as: + +Vendor.GET("Account No."); + +GETURL(CLIENTTYPE:WEB,COMPANYNAME, OBJECTTYPE::Page,27,Vendor) + +**Note**: It is currently not possible to set filters on the record that you sent as a last parameter to the GETURL function. However, it is possible to write your own code to compute and append the filter string to the URL that is created by the GETURL function. + +The server name and instance are extracted automatically by GETURL and do not need to be specified by the C/AL developer. Furthermore, the multitenancy setup is transparent to the C/AL developer. No multitenancy parameters are specified when you call GETURL, because the function knows from the server setup if it is running in a multitenant environment and if so, it will add a string like "&tenant=MyTenant" to the URL. + +## When to Use + +The GETURL function can generally be used every time a URL must be created. The following are some scenarios where the function is particularly useful. + +* Document approvals. For more information, see the "NAV Usage Example" section. +* Reports containing drill-down links. (Beware of the resource cost of adding a new URL element to the Report dataset.) +* When planning to write code for, or migrate to, various display targets (Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV web client, Microsoft Dynamics NAV web services) without having to explicitly specify which client to use. + +## Examples of Usage + +The following are examples of calls to GETURL and their corresponding return value: + +**Command** + +**URL** + +GETURL(CLIENTTYPE::Win) + +dynamicsnav://MyServer:7046/DynamicsNAV71// + +GETURL(CLIENTTYPE::Web) + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient + +GETURL(CLIENTTYPE::OData) + +http://MyServer:7048/DynamicsNAV71/OData + +GETURL(CLIENTTYPE::SOAP) + +http://MyServer:7047/DynamicsNAV71/WS/Services + +GETURL(CLIENTTYPE::Current) ie. When running this code on a Win client session + +dynamicsnav://MyServer:7046/DynamicsNAV71// + +GETURL(CLIENTTYPE::Default) ie. When the Server config key DefaultClient is set to Windows + +dynamicsnav://MyServer:7046/DynamicsNAV71// + +GETURL(CLIENTTYPE::Windows,COMPANYNAME) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/ + +GETURL(CLIENTTYPE::Windows,'') + +dynamicsnav://MyServer:7046/DynamicsNAV71// + +GETURL(CLIENTTYPE::Windows,'NONEXISTING Corp') + +dynamicsnav://MyServer:7046/DynamicsNAV71/NONEXISTING Corp/ + +GETURL(CLIENTTYPE::Web,COMPANYNAME) + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS + +GETURL(CLIENTTYPE::Web,'') + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient + +GETURL(CLIENTTYPE::Web,'NONEXISTING Corp') + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=NONEXISTING Corp + +GETURL(CLIENTTYPE::OData,COMPANYNAME) + +http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS') + +GETURL(CLIENTTYPE::OData,'') + +http://MyServer:7048/DynamicsNAV71/OData + +GETURL(CLIENTTYPE::OData,'NONEXISTING Corp') + +http://MyServer:7048/DynamicsNAV71/OData/Company('NONEXISTING Corp') + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME) + +http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Services + +GETURL(CLIENTTYPE::SOAP,'') + +http://MyServer:7047/DynamicsNAV71/WS/Services + +GETURL(CLIENTTYPE::SOAP,'NONEXISTING Corp') + +http://MyServer:7047/DynamicsNAV71/WS/NONEXISTING Corp/Services + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Table,27) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runtable?table=27 + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,27) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=27 + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Report,6) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runreport?report=6 + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Codeunit,5065) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runcodeunit?codeunit=5065 + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Query,9150) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runquery?query=9150 + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::XmlPort,5150) + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runxmlport?xmlport=5150 + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27) ie. When the Web Service is published + +http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/PAG27Vendors + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Query,9150) ie. When the Web Service is published + +http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/QUE9150MyCustomers + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27)Â ie. When the Web Service is published + +http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Page/PAG27Vendors + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Codeunit,5065) ie. When the Web Service is published + +http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Codeunit/COD5065EmailLogging + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,27,record) List Page + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=27&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw + +GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page + +dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=26&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,27,record) List Page + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=27&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=26&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27,record) + +http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/PAG27Vendors('IC1030') + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,27) + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=27 + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Report,6) + +https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&report=6 + +If the GETURL function is called with invalid parameters, it will return an empty string. In that case, you can find the related error text by calling the GETLASTERRORTEXT function. + +**Function Call** + +**Error Message** + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Table,27) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Codeunit,5065) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Query,9150) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::XmlPort,5150) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Table,27) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27) + +The Page object, 27, that is specified for the GetUrl function has not been published in the Web Services table. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Report,6) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Codeunit,5065) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Query,9150) + +The Query object, 9150, that is specified for the GetUrl function has not been published in the Web Services table. + +GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::XmlPort,5150) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Table,27) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27) + +The Page object, 27, that is specified for the GetUrl function has not been published in the Web Services table. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Report,6) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Codeunit,5065) + +The Codeunit object, 5065, that is specified for the GetUrl function has not been published in the Web Services table. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Query,9150) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::XmlPort,5150) + +The specified object type parameter for the GetUrl function is not valid. + +GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27,record) + +You cannot specify a record parameter for the GetUrl function when the object type is SOAP + +## NAV Specific Example + +The following example shows how to use the GETURL function in codeunit 440 to ensure that the notification mail in Document Approvals can link to both the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV web client: + +[![ ][image0]][anchor0] + +This resulting UI looks as follows. + +[![ ][image1]][anchor1] + +The first link opens the approval document in the Microsoft Dynamics NAV Windows client. The second link (Web view) opens the same document in the Microsoft Dynamics NAV web client. + + + +[anchor0]: 1778.url1.jpg +[anchor1]: 7802.url2.jpg + + +[image0]: 1778.url1.jpg +[image1]: 7802.url2.jpg diff --git a/content/NAVPatterns/creating-custom-charts/0246.Picture6.png b/content/NAVPatterns/creating-custom-charts/0246.Picture6.png new file mode 100644 index 00000000..8a71988e Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/0246.Picture6.png differ diff --git a/content/NAVPatterns/creating-custom-charts/1411.Picture2.png b/content/NAVPatterns/creating-custom-charts/1411.Picture2.png new file mode 100644 index 00000000..c93679c0 Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/1411.Picture2.png differ diff --git a/content/NAVPatterns/creating-custom-charts/1541.Picture7.png b/content/NAVPatterns/creating-custom-charts/1541.Picture7.png new file mode 100644 index 00000000..b05555d8 Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/1541.Picture7.png differ diff --git a/content/NAVPatterns/creating-custom-charts/1781.Picture5.png b/content/NAVPatterns/creating-custom-charts/1781.Picture5.png new file mode 100644 index 00000000..636e0240 Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/1781.Picture5.png differ diff --git a/content/NAVPatterns/creating-custom-charts/1803.Picture7.png b/content/NAVPatterns/creating-custom-charts/1803.Picture7.png new file mode 100644 index 00000000..d6b26d7c Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/1803.Picture7.png differ diff --git a/content/NAVPatterns/creating-custom-charts/2553.Picture8.png b/content/NAVPatterns/creating-custom-charts/2553.Picture8.png new file mode 100644 index 00000000..cec97fe8 Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/2553.Picture8.png differ diff --git a/content/NAVPatterns/creating-custom-charts/5153.Picture1.png b/content/NAVPatterns/creating-custom-charts/5153.Picture1.png new file mode 100644 index 00000000..aa9b7263 Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/5153.Picture1.png differ diff --git a/content/NAVPatterns/creating-custom-charts/5545.Picture9.png b/content/NAVPatterns/creating-custom-charts/5545.Picture9.png new file mode 100644 index 00000000..b9f5764f Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/5545.Picture9.png differ diff --git a/content/NAVPatterns/creating-custom-charts/5582.Picture10.png b/content/NAVPatterns/creating-custom-charts/5582.Picture10.png new file mode 100644 index 00000000..353d5fdf Binary files /dev/null and b/content/NAVPatterns/creating-custom-charts/5582.Picture10.png differ diff --git a/content/NAVPatterns/creating-custom-charts/index.md b/content/NAVPatterns/creating-custom-charts/index.md new file mode 100644 index 00000000..20ae7c16 --- /dev/null +++ b/content/NAVPatterns/creating-custom-charts/index.md @@ -0,0 +1,205 @@ ++++ +title = "creating-custom-charts.md" +weight = 420 ++++ +_by Nikola Kukrika at Microsoft Development Center Copenhagen_ + +## Abstract + +The goal of this solution is to enable you to: + +1. Use charts in the web client. +2. Create charts with custom functionality. + +## Description + +This pattern enables you to implement a business chart (Specific Chart type) in a way that is maintainable and reusable on other pages. This also enables you to provide specific functionality that is not possible with the Generic Chart type and it enables you to show charts in the web client. + +The Business Chart add-in is a special because it is a combination of .NET and Javascript add-ins depending on the display target. In the web client, it renders a JavaScript control, while in the win client, it renders a .Net control. Because of this behavior, you can expect minor differences in how the chart is presented in the win client versus in the web client. Note that this implementation is specific to NAV platform code, because it is not possible to create add-ins that combines .NET and JavaScript by using a framework API. + +[![ ][image0]][anchor0] + +Example of the same chart in the win client: + +[![ ][image1]][anchor1] + +The most obvious differences in chart rendering in the two clients are: Slightly different line heights, slightly different chart height, legends in web-client charts can be used as toggle filters to show/hide groups (this is not possible in the win client). + +### Implementation Overview + +[![ ][image2]][anchor2] + +### Add-in Buffer Table + +This table is used to encapsulate the logic of the Business Chart Add-in. The table handles the following logic: + +* Storing chart values and conversion from .NET to C/AL and vice versa +* Handling of captions: We must use C/AL to provide multilanguage text in add-ins. In addition, the multilanguage text must be encapsulated in a single place, because we pass/read the same dataset from/to the add-in. +* DrillDown logic +* Other helper data related functions, for displaying date, periods, etc.\[Bogdana1\] \[NK2\] \[NK3\] + +**Note:** It is recommended that you reuse the **Business Chart Buffer **table****(485) as a buffer table or extend. It is a generic table which should cover most of the use cases. Implement a new buffer table only if this table does not meet your needs. + +### CardPart page + +The CardPart page hosts the Business Chart add-in and must use the add-in buffer table as a source table. + +On the page, you must implement the following triggers: + +* **AddInReady** -- Executed when the page is done rendering. Used to initialize the add-in. +* **DataPointClicked** -- Single-click on an element on the chart. +* **DataPointDoubleClicked** -- Double-click on an element on the chart + +The CardPart usually contains a StatusText variable to provide more information about the chart or dataset and a set of actions to control the chart. + +The most commonly used actions are: + +* **Select Chart**, **Previous Chart**, **Next Chart** +* **Set Period**, **Work Date** +* Actions to filter the data set +* **Refresh** +* **Chart Information **-- a tooltip with a description of the chart and how data is calculated. + +### Optional: Preserving User Personalization + +One of the most common functionalities is personalization. If the chart can be customized by the user, you should store the settings that the user has entered and apply them the next time the chart is loaded. + +To do this, you need the following: + +* A setup record to store the data. You can use the **Business Chart User Setup** table (487) or create a new setup table if you need to store more information. +* A management codeunit to write/apply the settings to the chart and to encapsulate other logic. Since we should not write code on pages, the code for the actions and other logic that does not apply to the setup record****should go in this codeunit. +* Setup pages where users can customize how the chart is shown and set different settings. + +The relation between the components is visualized in the following diagram\[ + +[![ ][image3]][anchor3] + +### Optional: Show Multiple Charts within a Single CardPart + +This option is useful on a Role Center where you want to show multiple charts using different datasets within a single part. In that case, you need a record to store the last chart selection, the setup records, and code units for separate charts. + +See, for example, the implementation of the **Mini Generic Chart** page (1390), which uses **MiniChartManagment** CodeUnit to manage separate management codeunits for charts and their setup records. The last selected chart is stored in a separate table, **Mini Chart Definition** (1310). + +[![ ][image4]][anchor4] + +## Usage + +To implement the pattern, create a new ChartPart and set the source table to **Business Chart Buffer**. + +Add a field named **BusinessChart** and set the ControlAddIn property to Microsoft.Dynamics.Nav.Client.BusinessChart. + +Then implement the AddInReady event. This event is executed when the page is done rendering. Code within this method must call the Update method from the **Business Chart Buffer** table, Update(CurrPage.BusinessChart) to initialize the chart and assign initial values. + +If you need a setup record and codeunit, then it is a good idea to encapsulate this logic within a method. + +### NAV Specific Example 1 + +Implementation of the **Finance Performance Chart** page (762) + +**BusinessChart::AddInReady()** + +UpdateChart(Period::" "); + +**LOCAL UpdateChart(Period : ',Next,Previous')** + +MoveAndUpdateChart(Period,0); + +**LOCAL MoveAndUpdateChart(Period : ',Next,Previous';Move : Integer)** + +AccSchedChartManagement.GetSetupRecordset(AccountSchedulesChartSetup,AccountSchedulesChartSetup.Name,Move); + +AccSchedChartManagement.UpdateData(Rec,Period,AccountSchedulesChartSetup); + +Update(CurrPage.BusinessChart); + +StatusText := GetCurrentSelectionText("Period Filter Start Date","Period Filter End Date"); + +In the MoveAndUpdateChart method, the AccSchedChartManagement codeunit gets a setup record and updates it if necessary. Then, it initializes the chart with setup data and sets the StatusText to show the period for which data is displayed. The same method is used by the actions to move and update the chart so that there is no code duplication. + +The following code is used to implement **DataPointClicked** + +******BusinessChart::DataPointClicked(point : DotNet "Microsoft.Dynamics.Nav.Client.BusinessChart.BusinessChartDataPoint")** + +SetDrillDownIndexes(point); + +AccSchedChartManagement.DrillDown(Rec,AccountSchedulesChartSetup); + +SetDrillDownindexes is a method from the **Business Chart Buffer** table that maps the DotNet point variable to C/AL data, so it must be used. The next method that you must implement is the action to be performed on Drilldown. + +The **DataPointDoubleClicked **trigger has the same implementation logic as the DataPointClicked trigger. + +### NAV Specific Example 2 + +Implementation of chart part 1390 on the **Small Business Role Center** page (9022) + +[![ ][image5]][anchor5] + +This chart part contains data from multiple charts within a single part. The **Status Text** field shows the name of the chart and the current period. Users can browse through the charts with **Next Chart **and**Previous Chart** or use **Select Chart** to choose from a list of available charts. + +[![ ][image6]][anchor6] + +On this dialog, users can choose if a chart should be enabled or disabled. If the chart is not enabled, it will be skipped on the **Previous Chart **and **Next Chart** actions. Charts used by this part use different codeunits and setup records. If the user changes the selected chart, this option will be saved and applied next time role center is opened. + +Users can also change the period length. + +[![ ][image7]][anchor7] + +Choosing the **Chart Information** button opens a short description of the chart. + +[![ ][image8]][anchor8] + +## NAV Usages + +Implementation of multiple charts within a single part: + +* Page 1390, **Mini Generic Chart** + +Charts that use a setup record and select the chart with **Customize Chart Setup** pages: + +* Page 772, **Inventory Performance** +* Page 771, **Purchase Performance** +* Page 770, **Sales Performance** +* Page 762, **Finance Performance** + +Chart that uses the **Business Chart User Setup** table: + +* Page 768, **Aged Acc. Receivable Chart** + +Other implementations: + +* Page 972, **Time Sheet Chart** +* Page 869, **Cash Flow Chart** +* Page 760, **Trailing Sales Orders Chart** + +## Ideas for improvement + +We should consider making a generic table for the last chart that the user has used. + +We should investigate if we could make generic code for selecting periods and other common functionality by using RecordRefs. + +Add-In improvements -- Different ways to visualize the data and to pick colors for categories. + +As a nice-to-have feature, we could implement functionality to cycle through the charts with a timer. + + + +[anchor0]: 5153.Picture1.png +[anchor1]: 1411.Picture2.png +[anchor2]: 1781.Picture5.png +[anchor3]: 0246.Picture6.png +[anchor4]: 1803.Picture7.png +[anchor5]: 1541.Picture7.png +[anchor6]: 2553.Picture8.png +[anchor7]: 5545.Picture9.png +[anchor8]: 5582.Picture10.png + + +[image0]: 5153.Picture1.png +[image1]: 1411.Picture2.png +[image2]: 1781.Picture5.png +[image3]: 0246.Picture6.png +[image4]: 1803.Picture7.png +[image5]: 1541.Picture7.png +[image6]: 2553.Picture8.png +[image7]: 5545.Picture9.png +[image8]: 5582.Picture10.png diff --git a/content/NAVPatterns/cross-session-events/PubSub.png b/content/NAVPatterns/cross-session-events/PubSub.png new file mode 100644 index 00000000..ff915cd2 Binary files /dev/null and b/content/NAVPatterns/cross-session-events/PubSub.png differ diff --git a/content/NAVPatterns/cross-session-events/index.md b/content/NAVPatterns/cross-session-events/index.md new file mode 100644 index 00000000..26bb194b --- /dev/null +++ b/content/NAVPatterns/cross-session-events/index.md @@ -0,0 +1,153 @@ ++++ +title = "cross-session-events.md" +weight = 430 ++++ +#### _By Nikolai L'Estrange, from TVision Technology Ltd. in the UK__ +_ + +### Abstract + +Track things that happen in other NAV Sessions. + +[![ ][image0]][anchor0] + +### Problem + +In Microsoft Dynamics NAV you can fire a function whenever something changes within your session (and from NAV 2016 this is even easier with the new Event model), however there is not an easy way to know what is happening in other sessions. Sometimes you would like to know what has happened since your last read, without reading everything again, e.g. when you need to pass a large dataset to a Control Add-in. + +A common way of handling this with Ledger Tables is to make note of the last record you read, and continuously poll to see if there are any new records. However this is restricted to strictly sequentially entered tables. + +### Solution + +There is a common pattern in many other languages called [Publish-Subscribe][anchor1] (or PubSub) that solves the same issue. We can implement the same pattern in NAV using a Table as a message queue platform and polling this table. We have named this pattern "Cross Session Events" in order to avoid confusion with the standard NAV Events which use the terms Publisher and Subscriber, and to try and describe more accurately when you would need this pattern. + +The pattern has four components: + +* **Publisher(s)**: These push messages to the Message Broker. +* **Subscriber Records**: Identifies the Subscriber and store filters to say what messages the Subscriber and interested in receiving. +* **Message Broker**: This distributes all messages sent in to all Subscribers that have expressed an interest (i.e. the message is within their filters). +* **Message Queue**: To hold the messages for each Subscriber. Generally once these messages are read, they are deleted. + +### Example + +An example of this would be when we have multiple users looking at the same set of data and we want their screens to update in "real time" whenever one of them makes a change, without doing a full refresh. We will use the [Observer pattern][anchor2] to capture the change (act as the Publisher) and then create a Table to hold Subscribers and Filters (Change Observer), a Table to be the Message Queue (Change Notification), and a Codeunit to be the Message Broker and help with the polling (ObserverMgt). + +Below are the table definitions: + + **Change Observer: + **"Table ID" Integer "Observable Table" + "Server ID" Integer + "Session ID" Integer + + **Change Notification: + **"Table ID" Integer "Observable Table" + "Server ID" Integer + "Session ID" Integer + "Entry No." Integer AutoIncrement + "Type of Change" Option Insert,Modify,Delete,Rename + "Record ID" RecordID + ... (other fields to indicate what has changed) + + +The Change Observer table identifies the Subscriber using Server ID and Session ID, and then in this example there is only one filter, which is the Table ID we want to listen to any changes. In this case all three fields are in the Primary Key. + +The Change Notification table then has the same three fields plus an Entry No. as its Primary Key, and in this example borrows heavily from the Change Log code to fill in the rest of the message. + +_**Note:** _Other examples of the pattern could have very different fields to identify the Subscriber, Filters and then whatever fields needed for content of the Message. + +Our Message Broker Codeunit will also serve as a central place to create Subscribers (Listen and StopListening functions) and a place to Poll for Messages. Note that the Poll function deletes the Messages as it reads them. + + **Listen(TableID : Integer)** + WITH Observer DO BEGIN + "Table ID" := TableID; + "Server ID" := SERVICEINSTANCEID; + "Session ID" := SESSIONID; + INSERT(TRUE); + COMMIT; + END; + **StopListening(TableID : Integer) + **WITH Observer DO BEGIN + RESET; + SETRANGE("Server ID",SERVICEINSTANCEID); + SETRANGE("Session ID",SESSIONID); + SETRANGE("Table ID",TableID); + DELETEALL(TRUE); + COMMIT; + END; + **NotifyAll(ChangeNotification : Record "Change Notification")** + WITH Observer DO BEGIN + RESET; + SETRANGE("Table ID",ChangeNotification."Table ID"); + IF FINDSET THEN REPEAT + Notify(Observer,ChangeNotification); + UNTIL NEXT = 0; + END; + **Notify(Observer : Record "Change Observer";ChangeNotification : Record "Change Notification")** + WITH ChangeNotification DO BEGIN + "Server ID" := Observer."Server ID"; + "Session ID" := Observer."Session ID"; + "Entry No." := 0; + INSERT; + END; + **Poll(TableID : Integer;VAR TempChangeNotification : TEMPORARY Record "Change Notification")** + WITH ChangeNotification DO BEGIN + TempChangeNotification.RESET; + TempChangeNotification.DELETEALL; + RESET; + SETRANGE("Table ID",TableID); + SETRANGE("Server ID",SERVICEINSTANCEID); + SETRANGE("Session ID",SESSIONID); + IF FINDSET THEN REPEAT + TempChangeNotification := ChangeNotification; + TempChangeNotification.INSERT; + MARK(TRUE); + UNTIL NEXT = 0; + MARKEDONLY(TRUE); + DELETEALL; + END; + +**__**The final part of this example is an object that calls the functions above. In this example we will use a Page with a PingPong Timer Control to do the polling in (almost) real time. These are the functions on the page: + + **OnQueryClosePage(CloseAction : Action None) : Boolean** + ObserverMgt.StopListening(DATABASE::"NAV Whiteboard Booking"); + **Timer::AddInReady()** + IF ObserverMgt.Listen(DATABASE::"NAV Whiteboard Booking") THEN + CurrPage.Timer.Ping(1000); + **Timer::Pong()** + CallUpdate; + CurrPage.Timer.Ping(1000); + **LOCAL CallUpdate()** + ObserverMgt.Poll(DATABASE::"NAV Whiteboard Booking",TempChangeNotification); + WITH TempChangeNotification DO BEGIN + IF FINDSET THEN REPEAT + IF "Type of Change" = "Type of Change"::Delete THEN BEGIN + ... + END ELSE IF RecRef.GET("Record ID") THEN BEGIN + ... + END; + UNTIL NEXT = 0; + END; + +### Consequences + +The PingPong control is only available on the Windows Client, so if you want to use another client you will need to use another solution to Poll for Messages. Therefore this pattern is not always going to be "real time". + +### Related Topics + +This pattern was originally described in the following blog: + +[https://geeknikolai.wordpress.com/2015/10/30/pubsub-pattern-in-dynamics-nav-2016/][anchor3] + +Below is the Wikipedia link to the PubSub pattern + +[https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe\_pattern][anchor1] + + + +[anchor0]: PubSub.png +[anchor1]: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern +[anchor2]: /nav/w/designpatterns/248.observer +[anchor3]: https://geeknikolai.wordpress.com/2015/10/30/pubsub-pattern-in-dynamics-nav-2016/ + + +[image0]: PubSub.png diff --git a/content/NAVPatterns/cue-table/Cue-Table-Figure-1.JPG b/content/NAVPatterns/cue-table/Cue-Table-Figure-1.JPG new file mode 100644 index 00000000..15a3dfab Binary files /dev/null and b/content/NAVPatterns/cue-table/Cue-Table-Figure-1.JPG differ diff --git a/content/NAVPatterns/cue-table/Cue-Table.png b/content/NAVPatterns/cue-table/Cue-Table.png new file mode 100644 index 00000000..44f81deb Binary files /dev/null and b/content/NAVPatterns/cue-table/Cue-Table.png differ diff --git a/content/NAVPatterns/cue-table/index.md b/content/NAVPatterns/cue-table/index.md new file mode 100644 index 00000000..39efe7d5 --- /dev/null +++ b/content/NAVPatterns/cue-table/index.md @@ -0,0 +1,141 @@ ++++ +title = "cue-table.md" +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 diff --git a/content/NAVPatterns/currently-active-record/6545.Table.png b/content/NAVPatterns/currently-active-record/6545.Table.png new file mode 100644 index 00000000..84f5db39 Binary files /dev/null and b/content/NAVPatterns/currently-active-record/6545.Table.png differ diff --git a/content/NAVPatterns/currently-active-record/index.md b/content/NAVPatterns/currently-active-record/index.md new file mode 100644 index 00000000..77cf92dd --- /dev/null +++ b/content/NAVPatterns/currently-active-record/index.md @@ -0,0 +1,166 @@ ++++ +title = "currently-active-record.md" +weight = 450 ++++ +Authors: Henrik Langbak and Kim Ginnerup, Bording Data + +## Abstract + +Date controlled data is expensive to find in the database. This pattern describes how using a view with a sub-select and a linked table object will minimize the returned dataset. +A side effect is reduced and simplified code, increased performance and a more scalable solution that is almost independent of the amount of records in the table. + +## Description + +There is no way in NAV to get a set of records from the database, which all have the newest starting date, that is less than or equal to today's date. Having an ending date on the record will help, but it introduces some other problems. In Dynamics NAV this is normally done by reading too many records, either at the SQL Server level or in the middle tier and throw away the ones you do not need. That is a waste of resources: + +< --\[if supportLists\]--\>\* < --\[endif\]--\>The SQL Server is reading too many records + +< --\[if supportLists\]--\>\* < --\[endif\]--\>There would be too much data sent over the network. +(If the SQL Server and the NAV Service tier are on different machines.) + +< --\[if supportLists\]--\>\* < --\[endif\]--\>The NAV Service Tier receives and throws away data. + +### Ending Date Problem + +Ending Date may introduce some problems of its own. + +If your design requires to have one and only one active record per key in a dataset, then Ending Date introduces the possibility for overlapping or holes in the timeline. +Ending Date creates a dependency between two records. Changing a Starting Date, requires you to update the previous record. Changing the Ending Date requires you to update the next record. +If you add a record in between you will have to update both the before and the after record. + +The pattern we describe here will work whether there is an Ending Date or Not. + +The pattern is also relevant for other types than date. The pattern is usable whenever you have dependencies between rows in a table. + +Use the pattern whenever you read a set of data containing a Starting Date and you need to implement a loop to throw away unwanted records. An example could be Codeunit 7000 "Sales Price Calc. Mgt.". In this codeunit there are many loop constructs to find prices and discounts. + +## Usage + +In the following example, we have a fictive table containing: Code, Starting Date and Price. The Primary Key consist of Code, Starting Date. The Database is the Demo Database, and the Company is Cronus. + +< --\[if supportLineBreakNewLine\]--\>[![ ][image0]][anchor0] +< --\[endif\]--\> + +### 1\. Create the view + +You will need to create the view before you define the Table Object. +You will need to create a view for every company in the database. + +CREATE VIEW \[dbo\].\[CRONUS$PriceView\] +AS +SELECT \[Code\], \[Starting Date\], \[Price\] +FROM dbo.\[CRONUS$Price\] AS A +WHERE \[Starting Date\] = +(SELECT MAX(\[Starting Date\]) +FROM dbo.\[CRONUS$Price\] AS B +WHERE B.\[Code\] = A.\[Code\] AND +B.\[Starting Date\] <= GETDATE()) + +Test the view to ensure that you get the correct result. It is much easier to test now than later. + +### 2\. Create the Table object + +Remember to set the link table property before you save it. + +### 3\. Implement the code + +IF PriceView.FINDSET THEN // You have them + +### 4\. Create a deployment codeunit + +Create a SQL Deployment codeunit to manage your views. +The codeunit needs to Create or Alter the views for all companies. +To see an example of how to talk to SQL Server using .NET see Waldo's blog here: +[http://dynamicsuser.net/blogs/waldo/archive/2011/07/19/net-interop-calling-stored-procedures-on-sql-server-example-1.aspx][anchor1] +< --\[if supportLineBreakNewLine\]--\> +< --\[endif\]--\> + +### 5\. Deployment + +You need to deploy in three steps: + +< --\[if supportLists\]--\>1\. < --\[endif\]--\>Delete the table objects referencing the views + +< --\[if supportLists\]--\>2\. < --\[endif\]--\>Deploy and run the deployment codeunit + +< --\[if supportLists\]--\>3\. < --\[endif\]--\>Deploy the new table objects that reference the views + +### General precaution + +If you later want to change the view, you need to follow these rules: + +< --\[if supportLists\]--\>\* < --\[endif\]--\>If you add columns, you need to add them to the view first and then add them to the Table Object. + +< --\[if supportLists\]--\>\* < --\[endif\]--\>If you want to remove columns from the view, you need to delete the Table Object, then change the view and last recreate the Table Object without the new columns. + +### Code example that accomplish the same but without using the pattern + +This following example will give you the same result but the performance will deteriorate as time goes by and you get more and more old data. + +Price.SETCURRENTKEY(Code,"Starting Date"); + +Price.SETFILTER("Starting Date",'..%1', TODAY + +IF Price.FINDSET THEN BEGIN +REPEAT + +Price.SETRANGE(Code, Price.Code); + +Price.FINDLAST; + +Price.SETRANGE(Code); + +PriceTemp := Price; + +PriceTemp.INSERT; + +UNTIL Price.NEXT = 0; + +END; +// PriceTemp will contain the Prices + +### Comparison + +The above NAV example is for a very simple date controlled solution and is provided to give an idea of what the pattern changes seen from a NAV development point of view. But consider the following: + +< --\[if supportLists\]--\>\* < --\[endif\]--\>The table has a more complex key. +This will require setting and clearing more filters + +< --\[if supportLists\]--\>\* < --\[endif\]--\>You need to read from more than one table. +Say you need to apply discount from a separate table. +This may give several lines in PriceTemp. + +< --\[if supportLists\]--\>\* < --\[endif\]--\>If the Code field is controlled by a Type field. +The Code field reference keys in different tables + +All three examples above can be implemented directly in the view. By using the pattern, it will still only require a single line of NAV code. + +Using the pattern will only issue one SQL call and thereby one trip to the server. +The NAV Example will require an unknown number of SQL calls and thereby an unknown number of trips to the server. The number of SQL calls is dependent on the number of distinct Code values. +The NAV example will require SQL Server to read all data older than or equal to TODAY, but only return one row per Code. Over time, as old data piles up in the system, the NAV code will perform slower because the SQL statements will be slower. +The Pattern makes a scalable solution with a predictable performance. The performance will not deteriorate at the same rate as the NAV code example. + +## NAV Usages + +The pattern does not exist in NAV (yet J). We have used it several times in our code for an Add-On. + +## Ideas for improvement + + +Query Object should be able to handle sub-selects and Unions. A simple solution could be to allow the NAV developer to specify the actual Select statement inside the query Object in clear text. Opening up for writing your own queries and map the projection to the Query-defined fields will make the query Object very versatile and remove the pressure from Microsoft trying to create all the different permutations that a select statement can have. Microsoft and others have all tried to create wizards that can create SQL select statement. They all end up having a clear text option. + +An alternative would be better support for linked table objects, specifically views. The current implementation is very fragile. + +The pattern only supports fetching data for a given date (normally today). This is because you cannot control the where-clause of the sub-select. + +## Related Topics + +The idea of having a linked table object pointing to a view could be a pattern of its own. + + + +[anchor0]: 6545.Table.png +[anchor1]: http://dynamicsuser.net/blogs/waldo/archive/2011/07/19/net-interop-calling-stored-procedures-on-sql-server-example-1.aspx + + +[image0]: 6545.Table.png diff --git a/content/NAVPatterns/cyclomatic-complexity/index.md b/content/NAVPatterns/cyclomatic-complexity/index.md new file mode 100644 index 00000000..764ca70a --- /dev/null +++ b/content/NAVPatterns/cyclomatic-complexity/index.md @@ -0,0 +1,22 @@ ++++ +title = "cyclomatic-complexity.md" +weight = 460 ++++ +Do not write functions that have high cyclomatic complexity. This makes the code hard to maintain. + +Bad code + + Any procedure / trigger that has a cyclomatic complexity \> 25, using the CC3 version mentioned in [this article][anchor0]. + + + +Good code + + Any procedure / trigger that has a cyclomatic complexity <= 25, using the CC3 version. + The CC3 version is computed by summing the following in a code block: + - each IF statement as 1\. + - each entire CASE as 1\. + + + +[anchor0]: http://www.aivosto.com/project/help/pm-complexity.html diff --git a/content/NAVPatterns/data-driven-blocked-entity/attention.jpg b/content/NAVPatterns/data-driven-blocked-entity/attention.jpg new file mode 100644 index 00000000..bd5f1a88 Binary files /dev/null and b/content/NAVPatterns/data-driven-blocked-entity/attention.jpg differ diff --git a/content/NAVPatterns/data-driven-blocked-entity/index.md b/content/NAVPatterns/data-driven-blocked-entity/index.md new file mode 100644 index 00000000..15de1e92 --- /dev/null +++ b/content/NAVPatterns/data-driven-blocked-entity/index.md @@ -0,0 +1,107 @@ ++++ +title = "data-driven-blocked-entity.md" +weight = 470 ++++ +_Written by Bogdan Andrei Sturzoiu, at Microsoft Development Center Copenhagen_ + +******Abstract** + +This pattern implements a generic mechanism for dynamically restricting and allowing usage of a record by the business process administrator. + +[![ ][image0]][anchor0] + +**Problem** + +A NAV record can be used in a number of functionalities across the app. There are situations, however, when the administrator wants to restrict the consumption of such a record, as well as lift the restriction when it is no longer relevant. + +For example, a new customer record should not be used for posting documents until it is approved by the relevant approver. + +We could solve this by using the [Blocked Entity pattern][anchor1], but it requires database schema changes, which have an upgrade impact. + +The blocked entity pattern involves: + +1. Adding a "blocked" status field on the record (either a Boolean or in the more advanced cases, an option field refining the usage). +2. Adding specific code for the record in every place where the restriction needs to be enforced. + +In contrast, the Data-driven Blocked Entity pattern involves adding a new record (data change) to mark the restriction, instead of adding a new field (metadata change). + +**Solution** + +This pattern describes a generic mechanism of adding and lifting restrictions for any type of record. + +The restriction mechanism has the following elements: + +1. Adding a restriction record for a specific reason (e.g. the record requires approval), which will act as a surrogate key (unique identifier) for the restricted record. This can be implemented through a workflow response, or directly, by calling the Restriction Management codeunit function. +2. Lifting the restriction when it is no longer necessary. Again, this can be done using a workflow response or directly by calling the dedicated function. +3. Consuming the restriction in the places of interest for a specific purpose. This is an application feature that requires a call to the Restriction Management codeunit to check for restrictions. + +Currently, the restrictions are record-based and type-less. They act as simple tokens, and they have: + +* A reason (e.g. the record requires approval) +* A purpose (e.g. the record cannot be posted). + +You must make sure to differentiate between the reason and the purpose. That is because the restriction can only be added once per record, but consumed in multiple places. + +******Example** + +For example, we want to restrict posting Gen. Journal Lines if a customer has not been added in Account No. field. + +For this, the following components are needed: + +1. When a Gen. Journal Line is inserted, call RestrictRecordUsage in COD1550, either directly in the trigger or using an event subscriber. +2. When you validate a Customer No. as Account no. and Customer as Account Type, lift the restrictions by calling AllowRecordUsage in COD1550\. +3. The consumption of the restriction at posting is already implemented as an event in TAB81, OnCheckGenJournalLinePostRestrictions. No further action necessary. + +**NAV Usage** + +All the approval workflows include a response that restricts usage of a record, and then, at the end of an approval loop, a response that allows the usage again by lifting the restriction. See responses "Add record restriction" and "Remove record restriction" implemented in COD1521\.[ +][anchor2] + +The code behind the "Add record restriction" workflow response: + + RecRef.GETTABLE(Variant); + Workflow.GET(WorkflowStepInstance."Workflow Code"); + RecordRestrictionMgt.RestrictRecordUsage(RecRef.RECORDID,STRSUBSTNO(RestrictUsageDetailsTxt,Workflow.Code,Workflow.Description)); + + +The code behind the "Remove record restriction" response: + + RecRef.GETTABLE(Variant); + CASE RecRef.NUMBER OF + DATABASE::"Approval Entry": + BEGIN + RecordRestrictionMgt.AllowRecordUsage(RecRef.RECORDID); + RecRef.SETTABLE(ApprovalEntry); + RecRef.GET(ApprovalEntry."Record ID to Approve"); + AllowRecordUsage(RecRef); + END; + DATABASE::"Gen. Journal Batch": + BEGIN + RecRef.SETTABLE(GenJournalBatch); + RecordRestrictionMgt.AllowGenJournalBatchUsage(GenJournalBatch); + END + ELSE + RecordRestrictionMgt.AllowRecordUsage(RecRef.RECORDID); + END; + + +Notice****how lifting a restriction for a Gen. Journal Batch involves lifting all the restrictions for the individual journal lines in the batch (hence the special branching of the code). + +******Consequences** + +Currently, there can only be one restriction per record. There are no restriction types. + +In the future, a type field should be added to the restriction table, to allow adding restrictions for different purposes, and to refine their consumption. For example, a posting restriction might only be enforced for restrictions originating from approvals. + +**NAV** **Versions** + +This pattern has been introduced in Dynamics NAV 2016\. + + + +[anchor0]: attention.jpg +[anchor1]: /nav/w/designpatterns/79.blocked-entity +[anchor2]: https://microsoft.sharepoint.com/teams/DynamicsNAV/Wiki/Nav%20Wiki%20Documents/NAV%20App%20Patterns/NAV%20App%20Patterns%20for%20Review/Data-Driven%20Blocked%20Entity.docx#_msocom_2 + + +[image0]: attention.jpg diff --git a/content/NAVPatterns/data-migration-facade/8308.logo.png b/content/NAVPatterns/data-migration-facade/8308.logo.png new file mode 100644 index 00000000..443a891f Binary files /dev/null and b/content/NAVPatterns/data-migration-facade/8308.logo.png differ diff --git a/content/NAVPatterns/data-migration-facade/NoStagingTableNew2.png b/content/NAVPatterns/data-migration-facade/NoStagingTableNew2.png new file mode 100644 index 00000000..67784877 Binary files /dev/null and b/content/NAVPatterns/data-migration-facade/NoStagingTableNew2.png differ diff --git a/content/NAVPatterns/data-migration-facade/StagingTableNew2.png b/content/NAVPatterns/data-migration-facade/StagingTableNew2.png new file mode 100644 index 00000000..78061079 Binary files /dev/null and b/content/NAVPatterns/data-migration-facade/StagingTableNew2.png differ diff --git a/content/NAVPatterns/data-migration-facade/errorhandling1.png b/content/NAVPatterns/data-migration-facade/errorhandling1.png new file mode 100644 index 00000000..3f649988 Binary files /dev/null and b/content/NAVPatterns/data-migration-facade/errorhandling1.png differ diff --git a/content/NAVPatterns/data-migration-facade/errorhandling2.png b/content/NAVPatterns/data-migration-facade/errorhandling2.png new file mode 100644 index 00000000..c6922a1a Binary files /dev/null and b/content/NAVPatterns/data-migration-facade/errorhandling2.png differ diff --git a/content/NAVPatterns/data-migration-facade/index.md b/content/NAVPatterns/data-migration-facade/index.md new file mode 100644 index 00000000..e12752a7 --- /dev/null +++ b/content/NAVPatterns/data-migration-facade/index.md @@ -0,0 +1,284 @@ ++++ +title = "data-migration-facade.md" +weight = 480 ++++ +# **Data Migration Façade** + +_By David Bastide and Soumya Dutta at Microsoft Development Center Copenhagen_ + +[![ ][image0]][anchor0] + +## **Context:** + +This pattern is describing how you can migrate data using the Data Migration Façade. + +## **Problem:** + +Writing migration code from an external source, such as a product from a competitor, can be time consuming, as you need to tackle the problems of what to migrate, in which order, exception handling... and can result in code that is fragile due to deep dependencies on the NAV data model (high coupling). Any change to the NAV data model can easily break this code. **** + +## **Solution:** + +The idea of the Data Migration Façade is to provide an API that creates and updates master data and related entities (including transactions) without referencing NAV tables. + +Additionally, the framework around the Data Migration Façade provides tools for error handling, and a way to integrate the migration in the Data Migration Overview page (page 1799). + +The façade framework has the following components: + +* Two management codeunits: + * **Data Migration Façade** (codeunit 6100): Integrates the extension to the Data Migration Wizard. Starts a migration, or restarts a migration that failed for some records. + * **Data Migration Status Facade** (codeunit 6101): Initializes and updates the status of the migration. The status displays in the **Data Migration Overview** page (page 1799). + +* Several master data migration façade codeunits that create and update entities. Each codeunit also contains events that help ensure that data is created in the correct order: + * **GL Acc. Data Migration Façade** (codeunit 6110) + * **Vendor Data Migration Façade** (codeunit 6111) + * **Customer Data Migration Façade** (codeunit 6112) + * **Item Data Migration Façade** (codeunit 6113) + * If you want to migrate other entities, it is possible to define your own codeunit that will contain your custom code (see 'Usage' below). + +* A page where you can view the status and progress of the migration. It shows one line for each master data entity (item, customer, vendor, general ledger account) that was chosen for migration. You can also stop a migration by choosing the **Stop Migration** action. + +* * **Data Migration Overview** (page 1799) + +## **Usage:** + +There are the following use cases: + +* Migration with staging tables, where data from another product is exported to a file or set of files, and the exported data is then imported to buffer tables, before running the migration logic. In this case, the migration is implemented in your extension codeunits, and it is called through events, one record at a time. + +* Migration without staging tables, for example, when you migrate data by importing it from an external tool such as external APIs and webservices. In this case, the migration is also implemented in your extension codeunits but it will be called through the OnRun procedure. You will be responsible for looping on the records to migrate, and you must migrate all records in this unique OnRun call for a given entity. + +To initialize and start the data migration, you must call the following procedures: + +* **"Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,0,Codeunit::"My extension Item migration codeunit") ** +This deletes existing status lines for migrating Items for 'My Migration Type', and initializes a new status line with 0 records migrated out of 42000\. + +**"Data Migration Façade".StartMigration('My Migration Type',false) ** +This starts the migration. False means this is not a retry. A re-try is when you migrate one or more records from the **Show Errors** page, which is described later in this document. Retry = true is only used by the **Show Errors** page and should not be used from extensions. + +### **Usage without staging tables:** + +The overall workflow is: + +1. Integrate your extension in the **Data Migration Wizard** by subscribing to the events exposed by the **Data Migration Façade**. +2. From there, initialize the status of the migration so it can be displayed in the Data Migration Overview. When initializing the status lines, you provide the codeunit ID that will be called for each entity: **"Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,0,Codeunit::"My extension Item migration codeunit")**. +3. Launch the migration: **"Data Migration Façade".StartMigration('My Migration Type',false).** +4. Your migration codeunits are called one at a time (**OnRun**) in the following order: + 1. G/L accounts (first, because customer/vendor posting groups refer to G/L accounts) + 2. Customers + 3. Vendors + 4. Items (because discounts may refer to customer groups) + 5. Others +5. Loop on all of the records to migrate. You can update the increment of the amount of records migrated: **"Data Migration Status Facade".IncrementStatusLine('My Migration Type',Database::Item,42).** + +[![ ][image1]][anchor1] + +_Figure 1: sequence diagram of the data migration without staging tables _ + +The following example shows how to migrate items without staging tables: + + trigger OnRun(); + var + ItemDataMigrationFacade: Codeunit "Item Data Migration Facade"; + ItemNumber: Integer; + ItemJson: Text; + begin + // loop on items retrieved through a web service for example + for ItemNumber := 1 to ExternalWebService.GetItemCount do begin + ExternalWebService.GetItem(ItemNumber,ItemJson); + // create item using the facade + if not ItemDataMigrationFacade.CreateItemIfNeeded(ItemJson.ItemNumber,ItemJson.ItemName1, + ItemJson.ItemName2,ConvertItemType(ItemJson.ItemType)) then + exit; // item already exists + // set some fields using the facade + ItemDataMigrationFacade.SetVendorItemNo(ItemJson.VendItemNumber); + ItemDataMigrationFacade.SetUnitVolume(ItemJson.Volume); + ItemDataMigrationFacade.SetAlternativeItemNo(ItemJson.AltItemNumber); + if ItemJson.PrimaryVendor <\> '' then + ItemDataMigrationFacade.SetVendorNo(ItemJson.PrimaryVendor); + // migrate dependencies + MigrateItemUnitOfMeasure(ItemDataMigrationFacade,ItemJson); + // modify the item (+run trigger) to save the changes made by setters + ItemDataMigrationFacade.ModifyItem(true); + // update the status in the migration dashboard + DataMigrationStatusFacade.IncrementMigratedRecordCount('My Migration Type', + Database::Item,1); + end; + end; + procedure MigrateItemUnitOfMeasure(ItemDataMigrationFacade : Codeunit "Item Data Migration Facade"; + ItemJson : Text); + var + MyUnitCodeStagingTable: Record "My Unit Code Staging Table"; + DataMigrationStatusFacade: Codeunit "Data Migration Status Facade"; + DescriptionToSet: Text\[10\]; + UnitCodeJson: Text; + begin + if ItemJson.UnitCode = '' then + // log an error using the Data migration façade + DataMigrationStatusFacade.RegisterErrorNoStagingTablesCase( + 'My Migration Type',Database::Item,'Unit of measure is empty.'); + if ExternalWebService.GetUnitCode(ItemJson.UnitCode,UnitCodeJson) then + DescriptionToSet := UnitCodeJson.Description; + ItemDataMigrationFacade.CreateUnitOfMeasureIfNeeded(ItemJson.UnitCode, DescriptionToSet); + // set the unit of measure on the item + ItemDataMigrationFacade.SetBaseUnitOfMeasure(ItemJson.UnitCode); + end; + + +_Figure 2: Example of Item and Item Unit of Measure migration without staging tables _ + +### **Usage with staging tables:** + +The overall workflow is: + +* Integrate your extension in the Data Migration Wizard by subscribing to the events exposed by the **Data Migration Façade**. + +* From there, initialize the status of the migration so it can be displayed in the **Data Migration Overview: "Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,Database::"My extension Staging table for items",0)**. +* You can either fill the staging tables from the wizard events, or in a subscriber to the event dedicated to filling staging tables (**'OnFillStagingTables'** in codeunit 6100): in this case, the import of data from the files to the staging tables will be done in the background. +* Launch the migration: **"Data Migration Façade".StartMigration('My Migration Type',false)**. +* Subscribe to the events to migrate entities and their dependencies. +* From the event subscribers, call the façade procedures to create entities and set their field values: + +* * **"Item Data Migration Façade".CreateItemIfNeeded('ITEM042','My Item Description';'My Item Description 2';ItemTypeToSet::Inventory)** + * +**"Item Data Migration Façade".SetBaseUnitOfMeasure('BOX')** + * +**"Item Data Migration Façade".ModifyItem(true)** + +[![ ][image2]][anchor2] + +_Figure 3: Simplified sequence diagram of the data migration with staging tables _ + +Below is a simplified example showing how to create an item: + + \[EventSubscriber(ObjectType::Codeunit, Codeunit::"Item Data Migration Facade", 'OnMigrateItem', '', true, true)\] + procedure OnMigrateItem(VAR Sender : Codeunit "Item Data Migration Facade";RecordIdToMigrate : RecordId); + var + MyItemStagingTable : Record "My Item Staging Table"; + begin + // handle the event if it targets this extension's staging table + if RecordIdToMigrate.TableNo <\> Database::"My Item Staging Table" then + exit; + MyItemStagingTable.Get(RecordIdToMigrate); + // create item using the facade + if not Sender.CreateItemIfNeeded(MyItemStagingTable.ItemNumber,MyItemStagingTable.ItemName1, + MyItemStagingTable.ItemName2,ConvertItemType(MyItemStagingTable.ItemType)) then + exit; // item already exists + // set some fields using the facade + Sender.SetVendorItemNo(MyItemStagingTable.VendItemNumber); + Sender.SetUnitVolume(MyItemStagingTable.Volume); + Sender.SetAlternativeItemNo(MyItemStagingTable.AltItemNumber); + if MyItemStagingTable.PrimaryVendor <\> '' then + Sender.SetVendorNo(MyItemStagingTable.PrimaryVendor); + // modify the item (+run trigger) to save the changes made by setters + Sender.ModifyItem(true); + end; + + +_Figure 4: Example of event subscriber for Item migration _ + +__ + +Below is another example showing how to use additional events to set fields that reference other tables, here the unit of measure: + + \[EventSubscriber(ObjectType::Codeunit, Codeunit::"Item Data Migration Facade", 'OnMigrateItemUnitOfMeasure', '', true, true)\] + procedure OnMigrateItemUnitOfMeasure(VAR Sender : Codeunit "Item Data Migration Facade";RecordIdToMigrate : RecordId); + var + MyItemStagingTable : Record "My Item Staging Table"; + MyUnitCodeStagingTable : Record "My Unit Code Staging Table"; + DescriptionToSet: Text\[10\]; + begin + // handle the event if it targets this extension's staging table + if RecordIdToMigrate.TableNo <\> Database::"My Item Staging Table" then + exit; + MyItemStagingTable.Get(RecordIdToMigrate); + if MyItemStagingTable.UnitCode = '' then + error('Unit of measure is empty.'); + MyUnitCodeStagingTable.SetRange(UnitCode,MyItemStagingTable.UnitCode); + if MyUnitCodeStagingTable.FindFirst then + DescriptionToSet := MyUnitCodeStagingTable.Description; + // create the unit of measure through the facade + Sender.CreateUnitOfMeasureIfNeeded(MyItemStagingTable.UnitCode, DescriptionToSet); + // set the unit of measure on the item + Sender.SetBaseUnitOfMeasure(MyItemStagingTable.UnitCode); + // modify the item to save the changes made by setter + Sender.ModifyItem(false); + end; + +_Figure 5: Example of event subscriber for Item Unit of Measure migration _ + +### **Combining both approaches:** + +If you want to migrate additional entities, the **Data Migration **framework lets you initialize the migration with entities other than master data. In this case, the **Data Migration Overview** page will show additional lines. Item, vendor, customer, an general ledger accounts are migrated with an event driven approach, and the additional entities are migrated by calling an extension codeunit **OnRun** method. + +## **Error handling with staging tables:** + +The migration starts by calling **RUN** on the façade codeunit. Errors thrown during the call are captured by **GETLASTERRORTEXT** and displayed when you choose the **Show Errors** action on the **Data Migration Overview** page. + +[![ ][image3]][anchor3] + +_Figure 6: List of errors shown when clicking **Show Errors** on the **Data Migration Overview** page _ + +__ + +The **Edit Record** action opens a view of the staging table, where you can edit fields to fix errors. Figure 4 shows an example of a page for the vendor staging table in a migration from C5\. + +[![ ][image4]][anchor4] + +_Figure 7: Edit a staging table record _ + +__ + +The **Staging Table ID** determines the page to open, so it is important that the page ID is equal to the **Staging Table ID**, at least for the master data staging tables, for example, for**G/L Accounts, Items, Customers** and **Vendor**. You should ensure that pages to edit related entities are linked on this page by means of new actions. For example, Figure 4 uses the **C5 Purchaser** action. + +After you fix the staging table record, you can choose the **Migrate** action to mark the selected records as records to retry, and then run **StartMigration** with the **Retry** flag set to true. This is the only place where the retry flag should be set to true in the **StartMigration** procedure. + +Error handling without staging tables + +When migrating data without staging tables, errors can be registered manually by the extension using **DataMigrationStatusFacade.RegisterErrorNoStagingTablesCase**. Otherwise they can be registered automatically if the codeunits fail when called on their **OnRun** procedure. + +Errors will be displayed in the error list, but you cannot open and edit records because there is no staging table. The Edit action will not be available. + +## **Limitations:** + +* Data migration will fail if there are customers, vendors, items in the database and if these entities are selected for migration. For example, if you choose to migrate items and your company already contains items, you will get an error. This should not be an issue if you migrate your data from another tool to NAV, in which case you will most likely start on a fresh empty company. However, if you just want to import additional items to a company with existing items, then it is not supported by the framework. however, you can still use the different functions provided by the different codeunits (such as **Item Data Migration Facade**) to create the entities without strong coupling on the NAV data model. +* **G/L entries** are deleted automatically. + +* There is no automated rollback in case of failure: data that is successfully migrated will be commited, and data that is not successfully migrated with be shown in the errors list. The retry feature (in case of staging tables) then makes it possible for you to retry individual entities or ignore them. + +## **Usages in NAV:** + +The Data Migration Façade is available starting from version 2018\. + +The following Façade codeunits for data migration management are available: + +* COD6100 (**Data Migration Facade**) + +* COD6101 (**Data Migration Status Facade**) + +The following Entity data migration façade codeunits are available: + +* COD6110 (**GL Acc. Data Migration Facade**) +* COD6111 (**Vendor Data Migration Facade**) +* COD6112 (**Customer Data Migration Facade**) + +* COD6113 (**Item Data Migration Facade**) +* COD6114 (**Ex. Rate Data Migration Facade**) + +## **References:** + +Façade pattern on Wikipedia: https://en.wikipedia.org/wiki/Facade\_pattern + + + +[anchor0]: 8308.logo.png +[anchor1]: NoStagingTableNew2.png +[anchor2]: StagingTableNew2.png +[anchor3]: errorhandling1.png +[anchor4]: errorhandling2.png + + +[image0]: 8308.logo.png +[image1]: NoStagingTableNew2.png +[image2]: StagingTableNew2.png +[image3]: errorhandling1.png +[image4]: errorhandling2.png diff --git a/content/NAVPatterns/design/index.md b/content/NAVPatterns/design/index.md new file mode 100644 index 00000000..301e1e6d --- /dev/null +++ b/content/NAVPatterns/design/index.md @@ -0,0 +1,11 @@ ++++ +title = "design.md" +weight = 490 ++++ +## C/AL Coding Guidelines + +## **Design** + +### + +Find the C/AL guidelines by expanding the menu in the left. diff --git a/content/NAVPatterns/discovery-event/Pic2.jpg b/content/NAVPatterns/discovery-event/Pic2.jpg new file mode 100644 index 00000000..31139410 Binary files /dev/null and b/content/NAVPatterns/discovery-event/Pic2.jpg differ diff --git a/content/NAVPatterns/discovery-event/Pic2b.jpg b/content/NAVPatterns/discovery-event/Pic2b.jpg new file mode 100644 index 00000000..00ad1fc3 Binary files /dev/null and b/content/NAVPatterns/discovery-event/Pic2b.jpg differ diff --git a/content/NAVPatterns/discovery-event/Pic3.jpg b/content/NAVPatterns/discovery-event/Pic3.jpg new file mode 100644 index 00000000..f5c02e12 Binary files /dev/null and b/content/NAVPatterns/discovery-event/Pic3.jpg differ diff --git a/content/NAVPatterns/discovery-event/Pic4.jpg b/content/NAVPatterns/discovery-event/Pic4.jpg new file mode 100644 index 00000000..0d3a1677 Binary files /dev/null and b/content/NAVPatterns/discovery-event/Pic4.jpg differ diff --git a/content/NAVPatterns/discovery-event/ServiceConnections.jpg b/content/NAVPatterns/discovery-event/ServiceConnections.jpg new file mode 100644 index 00000000..4819bdef Binary files /dev/null and b/content/NAVPatterns/discovery-event/ServiceConnections.jpg differ diff --git a/content/NAVPatterns/discovery-event/index.md b/content/NAVPatterns/discovery-event/index.md new file mode 100644 index 00000000..e27b2048 --- /dev/null +++ b/content/NAVPatterns/discovery-event/index.md @@ -0,0 +1,85 @@ ++++ +title = "discovery-event.md" +weight = 500 ++++ +by waldo + +# Abstract + +The "Discovery Event" pattern is a way for a generic functionality, to call out to other functionalities that want to make use of it, by raising an event, so that they have an event to subscribe to. This is usually done to set itself up within the generic app. + +# The problem + +Let's suppose you have a generic piece of functionality, that hooks into lots of places (modules) in your application. To set this up, you might have to hook into all these parts of the application. Well, this pattern turns this setup around: let all the different modules set itself up in the generic app by raising a "discovery event". + +# Usage + +The pattern is most easily described when you look at an example. This example is an actual usage of the pattern within the application, in page **Service Connections.** + +[![ ][image0]][anchor0] + +The goal of this functionality is to: +• List all the different connections to external services, +• Have a central place to navigate to the corresponding setup of the service. + +The functionality (**Service Connections**) itself, is not aware of the state nor setup nor any context of all the different services in the list. All it does is: +• It raises an event as an opportunity for all services within the NAV application to subscribe to, +• It has a public function **InsertServiceConnection** that the subscribers can use to register itself at the Service Connection. + +The event **OnRegisterServiceConnection** is raised when the page (1279 - **Service Connections**) is opened. + +One example of a subscription is the SMTP setup. In Codeunit 400 you'll find the subscriber function **HandleSMTPRegisterServiceConnection** which subscribes to this discovery event, and calls the **InsertServiceConnection** to register itself. + +# Description + +The main idea of this pattern is: "Discover the settings, the context, the records, ... which I need for my functionality" or "Discover the configuration for my functionality". In any case, "discover" is the main idea. It's a pattern where using both publishers and subscribers in one application makes a lot of sense. +Let's break down to the steps that are needed to implement the pattern. + +## Step 1: Publish the event + +In the below example, I create a table **Module Status** with a published event **OnDiscoverModuleStatuses**. + +[![ ][image1]][anchor1] + +You see that I also include the sender. This way, I will be able to access the methods on my table (which I use as a class). Obviously, other patterns can be applied here as well, like the Argument Table pattern. + +## Step 2: Raise the event on the right place + +When you publish an event, it should obviously be raised somewhere in the code as well. In the below example, I want to raise the event simply by a method which I want to call from a page. So I create a global function where I raise the event: + +[![ ][image2]][anchor2] + +## Step 3: Create one or more global functions, so that your subscriber can call into your functionality to configure, set up, or do whatever it needs to do to make itself discoverable + +The generic functionality that I want to call, should be part of the main class - in this case the**Module Discovery** class, or better, the table (**Module Status**). In this table, I create this global function, because I want to make it available for the subscribers: + +[![ ][image3]][anchor3] +The business logic doesn't really matter for this pattern. This is obviously dependent on the functionality where you would like to implement the pattern. + +## Step 4: subscribe from the places in the app to this event, use the global function(s) + +This could be anywhere. Any module within your vertical, of within the main application, can subscribe to the event. In the example below, I create the subscriber in Codeunit80, as I was interested in the status of the Sales-module in default NAV. +The exact place of the subscriber is up to you. The main message is that it's part of the module that wants to subscribe, and not part of the **Module Status** module in the application. +Here is the subscriber (and one small helper function): + +[![ ][image4]][anchor4] +You see I can use the "sender" as a normal Record-variable. I access the previously created global function to "register" this sales-module. + +# Microsoft Dynamics NAV Versions + +This pattern only works with Microsoft Dynamics **NAV 2016 and up.** + + + +[anchor0]: ServiceConnections.jpg +[anchor1]: Pic2.jpg +[anchor2]: Pic2b.jpg +[anchor3]: Pic3.jpg +[anchor4]: Pic4.jpg + + +[image0]: ServiceConnections.jpg +[image1]: Pic2.jpg +[image2]: Pic2b.jpg +[image3]: Pic3.jpg +[image4]: Pic4.jpg diff --git a/content/NAVPatterns/document/0005.Document-Pattern-UML-Class-Diagram.jpg b/content/NAVPatterns/document/0005.Document-Pattern-UML-Class-Diagram.jpg new file mode 100644 index 00000000..8a6bf1f0 Binary files /dev/null and b/content/NAVPatterns/document/0005.Document-Pattern-UML-Class-Diagram.jpg differ diff --git a/content/NAVPatterns/document/2086.Design-Pattern-Document-SubPage-Properties.png b/content/NAVPatterns/document/2086.Design-Pattern-Document-SubPage-Properties.png new file mode 100644 index 00000000..aaa2c9a9 Binary files /dev/null and b/content/NAVPatterns/document/2086.Design-Pattern-Document-SubPage-Properties.png differ diff --git a/content/NAVPatterns/document/index.md b/content/NAVPatterns/document/index.md new file mode 100644 index 00000000..fe278501 --- /dev/null +++ b/content/NAVPatterns/document/index.md @@ -0,0 +1,112 @@ ++++ +title = "document.md" +weight = 510 ++++ +_By Xavier Garonnat, knk Ingénierie (France), xgaronnat@knk.fr_ + +## Abstract + +A document structure contains a header and a set of lines. Each line is linked to the header and could have common data with header. + +## Description + +This pattern should be used as a basis to build any document, showing a header and multiple lines in the same page. Basically, a document is at least composed of two tables and three pages, as shown below: + +[![ ][image0]][anchor0] + +## Usage + +You should use it any time you have to capture and store a document. + +## Example + +To build this example from scratch, you will need: + +* Two tables, one for the header (called "Document Header"), and one for the document lines (called "Document Line"). Each document will be composed of "1 to N" line(s). +* Three pages, one for the header, one for the subpage (lines), and the last for the document list obviously.Table "Document Header" + +**Table "Document Header" **: Is the "header" table of your document (like Sales Header, Purchase Header, Transfer Header ...) + +* Add a field "No." (Code 20): Should be the first field and primary key of your documents, to be driven by Serial No. (See corresponding design pattern) + +For this sample, I just added a "Sell-to Customer No." to this table. Don't forget to manage deletion of lines with trigger OnDelete(). + +**Table "Document Line"**: will store the lines of the document + +* Add a field "Document No." (Code 20): Should be the first field and is related to table "Document Header": set TableRelation to your "Document Header" table +* Add a field "Line No." (Integer): this field will be populated automatically by the subpage Page (see AutoSplitKey) + +First (Primary) Key must be "Document No.,Line No.". On table properties, set PasteIsValid to No (to avoid copying/pasting lines, will be implemented by "Copy document", another pattern). + +For my sample, I just add a couple of fields: "Item No." and "Quantity" to this table (just copy/paste standard fields from "Sales Line" table and delete trigger code, this will insure that each field will be well designed) + +**Page "Document Subpage"**: will display the lines in the main form, and will be in charge of assigning line number automatically. + +Create the page for table "Document Line" with the wizard by selecting the ListPart template, add all yours fields except the primary key ("Document No." and "Line No."). + +Then edit the properties: + +* Set AutoSplitKey, DelayedInsert and MultipleNewLines to Yes: this combination will make your subpage work as required. +* AutoSplitKey is used to set NAV calculate the last field of the key ("Line No.") with proper numbers (10000, 20000...). + +Set caption to "Lines". Save your page, we will use it on the next step. + +**Page "Document"**: will display the document, and the lines with subpage. + +Create the page for "Document Header" Table with the wizard by selecting the Document template: + +* Add a General FastTab +* Add all the revelant fields for the user (or at least "No.") +* Click Finish to close the wizard + +Then simply add your subpage as new line in the designer, and adjust the property "SubFormPerLink" with "Document No.=FIELD(No.)" to link header and lines : + +**[![ ][image1]][anchor1]** + +**Page "Document List": **Use the Page wizard to create a List page based on the Document table and add fields, FactBox (RecordLinks, Notes...), etc. + +Once created: + +* Set Editable to No on the List +* CardPageID to Page "Document" to enable New/Edit/... Pane actions. + +Save our page and add it to the Role Page "Order Processor Role Center" for example. + +Now, observe how "Line No." is calculated on the first line, and when inserting a new line between the first and second one. + +Code sample (copy link to your browser) : https://knk1fr-my.sharepoint.com/personal/xgaronnat\_knk\_fr/\_layouts/15/guestaccess.aspx?guestaccesstoken=hL0P%2fyQ1ZreY5KlSPc%2b8dHrO4zjUkqQbg8DnGSbgd1Y%3d&docid=02b3cb93e1ff1459380891795fb8441fc + +## NAV Usages + +So many: Sales Order, Purchase Order, Transfer Order, Assembly Order... + +For posted document, it's quite similar, but you don't have to setup subpage properties like AutoSplitKey, used for data entry purpose only (and your pages content should be mainly read-only / non editable). + +## Ideas for improvement + +* A new property like "AutoSplitStartNumber", enabled if AutoSplitKey=Yes, default value with <10000\>. Allow to change the numbers of created line. +* Be able to copy/paste header AND lines or import header and line from an Excel file. + +## When it should not be used + +This pattern is mainly used for Documents, and may not be used directly for Master data or any other table (Setup, Supplemental, etc...). + +## Related Topics + +Use Series No. Pattern for your documents, and Copy Document to implement document duplication. + +## References + +Walkthrough: Creating a Document Page : [http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx][anchor2] +[][anchor2][watch?v=S9cRD2D4c0&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=27][anchor3] + + + +[anchor0]: 0005.Document-Pattern-UML-Class-Diagram.jpg +[anchor1]: 2086.Design-Pattern-Document-SubPage-Properties.png +[anchor2]: http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx "http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx" +[anchor3]: https://www.youtube.com/watch?v=S9cRD2D4c_0&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=27 + + +[image0]: 0005.Document-Pattern-UML-Class-Diagram.jpg +[image1]: 2086.Design-Pattern-Document-SubPage-Properties.png diff --git a/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/0654.easy-update-1.png b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/0654.easy-update-1.png new file mode 100644 index 00000000..9813a3cb Binary files /dev/null and b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/0654.easy-update-1.png differ diff --git a/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/4024.easy-update-2.png b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/4024.easy-update-2.png new file mode 100644 index 00000000..02b417a5 Binary files /dev/null and b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/4024.easy-update-2.png differ diff --git a/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/index.md b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/index.md new file mode 100644 index 00000000..982ed322 --- /dev/null +++ b/content/NAVPatterns/easy-update-of-setup-or-supplementary-information/index.md @@ -0,0 +1,95 @@ ++++ +title = "easy-update-of-setup-or-supplementary-information.md" +weight = 520 ++++ +_by Anders Larsen at Microsoft Development Center Copenhagen_ + +## Abstract + +Users or the administrator must regularly update setup or supplementary information in the day-to-day business, such as setting up a new type of customer. This setup task often arrives when their focus is on registration and execution instead of setup. + +The navigation experience around these extra steps is often quite troublesome and time-consuming. To enable users to easily perform the needed update, a guide often gives the best support. + +To guide users, we can prompt them with a dialog on which they can update the setup or supplementary information instantly and easily, so that they can proceed with the business task without being side-tracked. + +## Usage + +Define two functions in the setup or supplementary table: One for verifying if the needed information is available, and another for exposing the page that contains the fields that the user must update. + +Call the code. For example: + +Local IsXAvailable : Boolean +If field X <\> '' then +Exit(True) +Exit(false) + +VerifyAndSetX +If IsXAvailable then +Exit; +If Confirm('Field X is missing a value. Do you want to update it now?') then +Open the card page in edit mode + +If not IsXAvailable then +Error(Field X is missing a value. Please correct it.) + +The calling code + +.. + +SetupTable.VerifyAndSetX + +.. + +## NAV Specific Example + +**** + +In the **Sales & Receivables Setup** table (311) for the DK version, the following procedures have been added: + +Local Procedure IsOIOUBLPathAvailable(...) + +Procedure VerifyAndSetOIOUBLPath(...) + +The code in the **Sales & Receivables Setup** table can now be called directly from the related processing codeunit, such as the **Sales-Post + Print** codeunit (82). + +Were the code is called: + +IF ("EAN No." <\> '') THEN + +SalesSetup.VerifyAndSetOIOUBLPathSetup(SalesHeader."Document Type"); + +If the setup is not updated properly, the user is prompted to update it as follows. + +[![ ][image0]][anchor0] + +Choosing **Yes** opens the related setup page. + +[![ ][image1]][anchor1] + +## NAV Usages + +* Report 206, **Sales invoice** +* Table 79, **Company Information** +* In OIOUBL fields (DK version) during posting/printing of a sales invoice. + +## Ideas for Improvement + +Make a more generic platform implementation that launches the corresponding card page for Rec on Rec.testfield with an asterisk mark for the field that needs a proper value. + +## Related Topics + +The anti-pattern is to do a testfield on a field that is not in the table that you are currently updating. + +The test field message can often be confusing because the pages are often named differently than the tables, which can lead to misunderstanding and context-switching. + +[watch?v=oeASJN zqTo&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=18][anchor2] + + + +[anchor0]: 0654.easy-update-1.png +[anchor1]: 4024.easy-update-2.png +[anchor2]: https://www.youtube.com/watch?v=oeASJN-zqTo&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=18 + + +[image0]: 0654.easy-update-1.png +[image1]: 4024.easy-update-2.png diff --git a/content/NAVPatterns/encapsulate-local-functionality/index.md b/content/NAVPatterns/encapsulate-local-functionality/index.md new file mode 100644 index 00000000..4c8cace3 --- /dev/null +++ b/content/NAVPatterns/encapsulate-local-functionality/index.md @@ -0,0 +1,5 @@ ++++ +title = "encapsulate-local-functionality.md" +weight = 530 ++++ +Any function used local must be defined as local. diff --git a/content/NAVPatterns/end-else-pair/index.md b/content/NAVPatterns/end-else-pair/index.md new file mode 100644 index 00000000..118a7e2c --- /dev/null +++ b/content/NAVPatterns/end-else-pair/index.md @@ -0,0 +1,21 @@ ++++ +title = "end-else-pair.md" +weight = 540 ++++ +The END ELSE pair should always appear on the same line. +Bad code + + IF OppEntry.FIND('-') THEN + IF SalesCycleStage.FIND('-') THEN BEGIN + ... + END + ELSE + ... + +Good code + + IF OppEntry.FIND('-') THEN + IF SalesCycleStage.FIND('-') THEN BEGIN + ... + END ELSE + ... diff --git a/content/NAVPatterns/error-message-processing/image001.png b/content/NAVPatterns/error-message-processing/image001.png new file mode 100644 index 00000000..82c8cfd9 Binary files /dev/null and b/content/NAVPatterns/error-message-processing/image001.png differ diff --git a/content/NAVPatterns/error-message-processing/image003.png b/content/NAVPatterns/error-message-processing/image003.png new file mode 100644 index 00000000..bfebcaf8 Binary files /dev/null and b/content/NAVPatterns/error-message-processing/image003.png differ diff --git a/content/NAVPatterns/error-message-processing/index.md b/content/NAVPatterns/error-message-processing/index.md new file mode 100644 index 00000000..33a0cd3d --- /dev/null +++ b/content/NAVPatterns/error-message-processing/index.md @@ -0,0 +1,103 @@ ++++ +title = "error-message-processing.md" +weight = 550 ++++ +_By Jesper Schulz at Microsoft Development Center Copenhagen_ + +Note: This pattern describes new functionality which makes it possible to generalize the [Journal Error Processing][anchor0] pattern. + +## Abstract + +Missing, invalid or incomplete data is a common issue during data processing in NAV. This article describes how to collect all error messages during processing using the error message component and present them to the user in a unified way, which enables the user to correct the errors efficiently. By leveraging the integrated error message logging functions, you can log a message with a single line of code and present it to the user with another one-liner. + +## Description + +This article describes how to use the Error Message component in NAV, which in short gives you the possibility to: + +1\. Link an error mesesage to the page which enables you to resolve the problem. +2\. Assemble all error messages in one central view instead of having to encounter them one by one. + +Validating data is a common task during data processing in NAV. Unfortunately, validation is often done using NAV's integrated ERROR and TESTFIELD functions, which halt execution of the process. The user will then have to locate the invalid / missing data, correct it and reinitiate the process, possibly running into the next error, making the cycle repeat itself. This can be a very tedious, time-consuming and frustrating process. The error message component aims at improving this experience by providing a lightweight framework for error message logging and this article will explain how to leverage this functionality in your code. By doing so, all error messages are gathered during (pre-)processing and are finally presented to the user. The user then has the possibility to click on the error message, which will open the record where the invalid / missing data is located, thereby enabling the user to correct all mistakes efficiently, from one central place and in one go. + +The example below comes from a Mexican localization, where the user has to export financial balances and transactions into an XML file for government audit purposes. In order to generate valid files, some mandatory data needs to be entered in the system. By leveraging the error message component, the user will be presented with the following page, if missing or invalid data was discovered: + +[![ ][image0]][anchor1] + +By clicking on the error message, the user will be presented with the entity, where the invalid / missing data should be corrected / added. This is done by applying the related pattern [Easy Update of Setup or Supplementary Information][anchor2]. + +[![ ][image1]][anchor3] + +## Usage + +In the processing function, define a temporary record of type "Error Message". Use the functions on that record to populate the record with error message, a few of them being: + +* **LogIfEmpty****** +* **LogIfLengthExceeded****** +* **LogIfInvalidCharacters****** +* **LogIfOutsideRange****** +* **LogIfGreaterThan****** +* **LogIfEqualTo****** +* **LogMessage****** + +The following parameters must be provided to these functions: + +* **Record:** The record which you want to check +* **Field Number:** The field number of the field you want to verify the value of +* **Condition:** The condition the field must meet (e.g. length, range, valid characters) +* **Message Type:** The type of message, which can be Error, Warning or Message + +When the processing is complete, you can check if any error messages of type "Error" were logged by calling the **HasErrors** function and you can show the list or error messages by calling the **ShowErrorMessages** function. You can also integrate the error messages list as a FactBox, but that is not part of this example. + +## NAV Specific Example + +The code below is an example of how the error message component was used in one part of the before mentioned Mexican feature. This code iterates over all G/L Accounts and pipes information out into an XML file. While doing so, it is validated that all mandatory fields have values and meet certain conditions. And only if that is the case, is the XML document actually exported. Also notice, that an error message is logged, in case no G/L Accounts are found given the provided filters. That way, the user can be guided to setup the system correctly. + + PROCEDURE ExportChartOfAccounts@1(Year@1000 : Integer;Month@1001 : Integer); + VAR + **TempErrorMessage@1003 : TEMPORARY Record 700; + **BEGIN + **TempErrorMessage.ClearLog;** // only necessary if variable is global + ... + CreateXMLHeader(Document,RootNode,CatalogoNodeTxt,Namespace,Year,Month,'1.1'); + IF GLAccount.FINDSET THEN BEGIN + REPEAT + **TempErrorMessage.LogIfEmpty (GLAccount,GLAccount.FIELDNO(Name),TempErrorMessage."Message Type"::Error); + ** + XMLDOMManagement.AddElement(RootNode,'Ctas','',Namespace,Node); + XMLDOMManagement.AddAttribute(Node,'CodAgrup',GLAccount."SAT Account Code"); + ... + CASE GLAccount."Debit/Credit" OF + GLAccount."Debit/Credit"::Debit: + XMLDOMManagement.AddAttribute(Node,'Natur','D'); + GLAccount."Debit/Credit"::Credit: + XMLDOMManagement.AddAttribute(Node,'Natur','A'); + ELSE + **TempErrorMessage.LogMessage( + GLAccount,GLAccount.FIELDNO("Debit/Credit"),TempErrorMessage."Message Type"::Error, + STRSUBSTNO(GLAccountTypeErr,GLAccount."Debit/Credit",GLAccount.RECORDID)); + ** END; + UNTIL GLAccount.NEXT = 0; + END ELSE + **TempErrorMessage.LogSimpleMessage(TempErrorMessage."Message Type"::Error,NoSATAccountDefinedErr); + ** + **IF NOT TempErrorMessage.HasErrors(TRUE) THEN + ** SaveXMLToClient(Document,Year,Month,'CT'); + **TempErrorMessage.ShowErrorMessages(FALSE); + **END; + +One could also do pre-processing in a function of its own, and only if the pre-processing results in no error messages of type "Error" would the processing continue. + +## Ideas for improvement + +By using this easy to use component, we have the possibility to extend this functionality going forward. A nice addition to the error message component would be the possibility to log the error messages persistently in a grouped manner, thereby allowing 3rd parties to see the issues the users bump into the most, or allowing 3rd parties to get an detailed insight into what happened, thereby enabling them to provide better support. + + + +[anchor0]: /nav/w/designpatterns/124.journal-error-processing.aspx +[anchor1]: image001.png +[anchor2]: /nav/w/designpatterns/104.easy-update-of-setup-or-supplementary-information.aspx +[anchor3]: image003.png + + +[image0]: image001.png +[image1]: image003.png diff --git a/content/NAVPatterns/extending-the-role-center-headlines/0724.Headline-sequence-diagram-v2.png b/content/NAVPatterns/extending-the-role-center-headlines/0724.Headline-sequence-diagram-v2.png new file mode 100644 index 00000000..d6442002 Binary files /dev/null and b/content/NAVPatterns/extending-the-role-center-headlines/0724.Headline-sequence-diagram-v2.png differ diff --git a/content/NAVPatterns/extending-the-role-center-headlines/3733.logo.png b/content/NAVPatterns/extending-the-role-center-headlines/3733.logo.png new file mode 100644 index 00000000..9ebb1d36 Binary files /dev/null and b/content/NAVPatterns/extending-the-role-center-headlines/3733.logo.png differ diff --git a/content/NAVPatterns/extending-the-role-center-headlines/Headline.png b/content/NAVPatterns/extending-the-role-center-headlines/Headline.png new file mode 100644 index 00000000..56b3cd2c Binary files /dev/null and b/content/NAVPatterns/extending-the-role-center-headlines/Headline.png differ diff --git a/content/NAVPatterns/extending-the-role-center-headlines/index.md b/content/NAVPatterns/extending-the-role-center-headlines/index.md new file mode 100644 index 00000000..6436f811 --- /dev/null +++ b/content/NAVPatterns/extending-the-role-center-headlines/index.md @@ -0,0 +1,170 @@ ++++ +title = "extending-the-role-center-headlines.md" +weight = 560 ++++ +_By David Bastide at Microsoft Development Center Copenhagen_ + +_[![ ][image0]][anchor0]_ + +__ + +## Context + + +Headlines are designed as a page of type HeadlinePart containing at least one text field. The part is added to the top of Role Center pages. +This document provides an elegant and extensible pattern about how to extend the Role Center headlines to add your own business headlines based on your data, and display them only if relevant. + +## Description + + +The Dynamics 365 Business Central release (April 2018) introduces a new HeadlinePart page type. This page type defines a page that rotates a display of several headlines after another, in the web client. A user can also click to switch to another headline. Headlines can also include a drilldown action that will be invoked when the user clicks the headline Text of the payload can be emphasized. +Headlines are divided in 2 parts: the qualifier, and the payload as you can see in the figure below. +_ +_ + +[![ ][image1]][anchor1] + +< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 10\]\> +< \[endif\]--\> + +_Figure 1: Qualifier, Payload and emphasized text. +_ + +## Usage + +A page part has been added to each major Role Center: + +* Page 9006 Order Processor Role Center, contains Page 1441 Headline RC Order Processor +* Page 9015 Job Project Manager RC, contains Page 1443 Headline RC Project Manager +* Page 9022 Business Manager Role Center, contains Page 1440 Headline RC Business Manager +* Page 9024 Security Admin Role Center, contains Page 1445 Headline RC Administrator +* Page 9026 Sales & Relationship Mgr. RC, contains Page 1444 Headline RC Relationship Mgt. +* Page 9027 Accountant Role Center, contains Page 1442 Headline RC Accountant +* Page 9028 Team Member Role Center, contains Page 1446 Headline RC Team Member +* Page 9010 Production Planner Role Center, contains Page 1447 Headline RC Prod. Planner +* Page 9016 Service Dispatcher Role Center, contains Page 1448 Headline RC Serv. Dispatcher + +You can create extensions that extend these pages to add your own headlines. +If no headline is added on these pages, fallback headlines will be displayed. + +The process to extend the headlines of a Role Center is simple: + +1. In a V2 extension, extend the pages (PAG1440 to 1446) with one or more fields you want to add as headlines. The field and its visibility should be variables that are populated in OnAfterGetRecord. +2. Subscribe to the OnComputeHeadlines event from the codeunits associated with the page (same ID and name as the page). Here you can compute your headlines. You should store the result in a table in your extension, so you can quickly get the results in step 3\. The computation is done in a background task, not to decrease the performance of the role center pages. +3. Subscribe to the OnIsAnyExtensionHeadlineVisible event from the page. This event is used to determine if any extension has visible headlines, and if so, hide the fallback headlines. You should set the ExtensionHeadlinesVisible variable to true if your extension has headlines to display at the time of the event. Otherwise, do nothing. +4. In the page, in the OnAfterGetRecord trigger, get the headline text and visibility values and copy them to your added fields. + +To format headlines, you should use Codeunit 1439 Headline Management functions: + +* Truncate: to truncate a text gracefully when possible with "...". For example, HeadlineManagement.Truncate('the text',6) returns "the...". +* Emphasize: to emphasize part of the headline payload. Emphasized text is shown with a different style. +* GetHeadlineText: to build the headline text. You provide the headline qualifier and payload, and you get the headline in a format that will be interpreted and formatted correctly by the client. It returns false if the qualifier exceeds its maximum length (50 characters) or payload exceeds its maximum length (75 characters). In that case it will not return the headline. If the qualifier you specify is empty, the default text "HEADLINE" will be displayed in the qualifier area. The payload must not be empty. + +### Examples: + +#### 1\. Extending the page with a new headline: + + group(LargestSale) + { + Visible = LargestSaleVisible; + ShowCaption=false; + Editable=false; + + field(LargestSaleText;LargestSaleText) + { + ApplicationArea = Basic, Suite; + DrillDown=true; + + trigger OnDrillDown() + var + EssentialBusHeadlineMgt: Codeunit "Essential Bus. Headline Mgt."; + begin + EssentialBusHeadlineMgt.OnDrillDownLargestSale(); + end; + } + } + + +#### + +#### 2\. Subscribing to the OnComputeHeadlines event, and computing headlines + + \[EventSubscriber(ObjectType::Codeunit, Codeunit::"Headline RC Business Manager", 'OnComputeHeadlines', '', true, true)\] + procedure OnComputeHeadlinesBusinessManager() + begin + // \[...\] compute headline, and init the EssentialBusinessHeadline record + if not ShowHeadline then + exit; // not enough data to compute headline + if not HeadlineManagement.GetHeadlineText( + 'Insight from last week', + StrSubstNo('The largest posted sales invoice was for %1', + HeadlineManagement.Emphasize(Format(CustomerLedgerEntry.Amount, 0, TypeHelper.GetAmountFormatWithUserLocale('$')))) + EssentialBusinessHeadline."Headline Text") + then + exit; + EssentialBusinessHeadline.Validate("Headline Visible", true); + EssentialBusinessHeadline.Modify(); + end; + + +#### + +#### 3\. Subscribing to the OnIsAnyExtensionHeadlineVisible event + + \[EventSubscriber(ObjectType::Page, Page::"Headline RC Business Manager", 'OnIsAnyExtensionHeadlineVisible', '', true, true)\] + procedure OnIsAnyExtensionHeadlineVisible(var ExtensionHeadlinesVisible: Boolean) + var + EssentialBusinessHeadline: Record "Essential Business Headline"; + AtLeastOneHeadlineVisible: Boolean; + begin + EssentialBusinessHeadline.SetRange("Headline Visible", true); + EssentialBusinessHeadline.SetFilter("Headline Name",'%1|%2|%3|%4|%5', + EssentialBusinessHeadline."Headline Name"::LargestOrder, + EssentialBusinessHeadline."Headline Name"::LargestSale, + EssentialBusinessHeadline."Headline Name"::BusiestResource, + EssentialBusinessHeadline."Headline Name"::MostPopularItem, + EssentialBusinessHeadline."Headline Name"::SalesIncrease, + EssentialBusinessHeadline."Headline Name"::TopCustomer); + AtLeastOneHeadlineVisible := not EssentialBusinessHeadline.IsEmpty(); + // only modify the var if this extension is making some headlines visible, setting to false could overrride some other extensions setting the value to true + if AtLeastOneHeadlineVisible then + ExtensionHeadlinesVisible := true; + end; + +#### + +#### 4\. Setting the headline text on the page + + trigger OnAfterGetRecord() + begin + EssentialBusinessHeadline.GetHeadline(EssentialBusinessHeadline."Headline Name"::LargestSale); + LargestSaleVisible := EssentialBusinessHeadline."Headline Visible"; + LargestSaleText := EssentialBusinessHeadline."Headline Text"; + end; + + + + +[![ ][image2]][anchor2] + +_Figure 2: Sequence diagram of headline usage_ + +## +Usages in NAV: + +* Essential Business Headlines extension_ +_ + +< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if supportAnnotations\]--\>< --\[endif\]--\>< --\[if gte mso 10\]\> +< \[endif\]--\> + + + +[anchor0]: 3733.logo.png +[anchor1]: Headline.png +[anchor2]: 0724.Headline-sequence-diagram-v2.png + + +[image0]: 3733.logo.png +[image1]: Headline.png +[image2]: 0724.Headline-sequence-diagram-v2.png diff --git a/content/NAVPatterns/feature-localization-for-data-structures/3058.Feature-localization-for-data-structures-3.png b/content/NAVPatterns/feature-localization-for-data-structures/3058.Feature-localization-for-data-structures-3.png new file mode 100644 index 00000000..8da249fe Binary files /dev/null and b/content/NAVPatterns/feature-localization-for-data-structures/3058.Feature-localization-for-data-structures-3.png differ diff --git a/content/NAVPatterns/feature-localization-for-data-structures/5123.Feature-localization-for-data-structures-1.png b/content/NAVPatterns/feature-localization-for-data-structures/5123.Feature-localization-for-data-structures-1.png new file mode 100644 index 00000000..c63ae3f4 Binary files /dev/null and b/content/NAVPatterns/feature-localization-for-data-structures/5123.Feature-localization-for-data-structures-1.png differ diff --git a/content/NAVPatterns/feature-localization-for-data-structures/6052.Feature-localization-for-data-structures-2.png b/content/NAVPatterns/feature-localization-for-data-structures/6052.Feature-localization-for-data-structures-2.png new file mode 100644 index 00000000..7fca9371 Binary files /dev/null and b/content/NAVPatterns/feature-localization-for-data-structures/6052.Feature-localization-for-data-structures-2.png differ diff --git a/content/NAVPatterns/feature-localization-for-data-structures/index.md b/content/NAVPatterns/feature-localization-for-data-structures/index.md new file mode 100644 index 00000000..effc2267 --- /dev/null +++ b/content/NAVPatterns/feature-localization-for-data-structures/index.md @@ -0,0 +1,258 @@ ++++ +title = "feature-localization-for-data-structures.md" +weight = 570 ++++ +_by Bogdan Sturzoiu at Microsoft Development Center Copenhagen_ + +## Abstract + +This pattern shows a solution for integrating W1 features to pre-existing country features that use different tables to achieve similar functionality. + +## Description + +It sometimes happens that certain features are requested in a NAV-supported country, but they are not initially considered generic enough to be included in the W1 build. This is how local features, such as Subcontracting in Italy and India, were created or specific banking and payments functionality in Italy, France, Spain, and others. + +Then, at some point in time, a decision is made to create a W1 feature that is closely related to the local functionality but uses a completely different set of tables, pages, etc. The developers now face the following problem: How to enable the newly-developed W1 feature into a country, such that the customers who are accustomed to their local structures can seamlessly continue working without completely (or immediately) switching to the W1 objects. + +This was the issue that was tackled in the NAV 2013 R2, in relation to the SEPA Credit Transfers functionality. + +### Using a Proxy + +The generic Proxy pattern is "a class functioning as an interface to something else" ([Wikipedia][anchor0]). + +[![ ][image0]][anchor1] + +Figure 1\. Proxy in UML + +### Pattern Elements + +The NAV data model translation of the proxy pattern can be used as explained below. + +The RealSubject is the NAV data model. Variations in table structures, relationships, and numbers are particular to each country. The W1 model is the base for the country-localized data models. However, some countries have heavy localizations which cannot be directly processed by the W1 core objects. + +The proxy is a codeunit that gathers data from wherever it is stored and transforms it to fit into a standard table, which is later used across all localizations. + +The interface is the fixed form in which the data is presented to be consumed by the client. + +The client can be an XML port that is fed from the common data interface. It can also be any other data processor (a codeunit fed to another table, etc.) or data display object (page or report). + +### Pattern Steps + +1. The user creates records in the local tables. +2. The user invokes an action that must be processed using the W1 feature code. + +1. The proxy codeunit moves the data from the local tables to the W1 tables, either into a temporary or persistent set of records, as needed. + +1. The W1 code now performs the action on the W1 table data. + +## Usage + +In NAV 2013 R2, we released the SEPA Credit Transfer functionality. It involves exporting vendor payments to an XML file that is subsequently processed by the customer's bank. The payments are exported from the Payment Journal page through a configurable XMLport. Therefore, the data source for these payment lines is the Gen. Journal Line table (81). + +In various countries, we already had payment export functionality, usually into flat bank files. However, the files are generated from different tables than in W1\. For example, in Italy, vendor payments are handled through the Vendor Bill Header table (12181) and the Vendor Bill Line table (12182). They are the RealSubject. + +The W1 feature flow is as follows: + +[![ ][image1]][anchor2] + +Figure 2\. W1 object call sequence + +**Note:** CT = Credit Transfers, pain = payments initiation (the XML format used for SEPA Credit Transfers and SEPA Direct Debit). + +The key question is: Where to tap into this flow when using a local data structure. For this purpose, a proxy codeunit has been added in W1, called 1222 -- SEPA CT-Prepare Source. This codeunit feeds the client (XML1000) data in a standard format (the interface is the Gen. Journal Line table (81)). + +In W1, the codeunit simply outputs the same set of general journal lines that it receives as an input: + +OnRun(VAR Rec : Record "Gen. Journal Line") + +GenJnlLine.COPYFILTERS(Rec); + +CopyJnlLines(GenJnlLine,Rec); + +LOCAL CopyJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line") + +IF FromGenJnlLine.FINDSET THEN BEGIN + +GenJnlBatch.GET(FromGenJnlLine."Journal Template Name",FromGenJnlLine."Journal Batch Name"); + +REPEAT + +TempGenJnlLine := FromGenJnlLine; + +TempGenJnlLine.INSERT; + +UNTIL FromGenJnlLine.NEXT = 0 + +END ELSE + +CreateTempJnlLines(FromGenJnlLine,TempGenJnlLine); + +LOCAL CreateTempJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line") + +// To fill TempGenJnlLine from the source identified by filters set on FromGenJnlLine + +TempGenJnlLine := FromGenJnlLine; + +In a country, such as Italy, the codeunit will have the following functions: + +1. Gets an empty set of general journal lines that carry the local payment document key as a filter on the Document No. field (as opposed to W1 that gets the real set of records to be exported). This is done so that the local data can be extracted at runtime. + +1. Selects the local payment data, for example in Italy, in the Vendor Bill Header and Vendor Bill Lines tables. + +1. Transforms the local payment data into temporary records of the Gen. Journal Line table. + +1. Outputs the temporary general journal lines that will be further processed and exported, exactly as in W1\. + +OnRun(VAR Rec : Record "Gen. Journal Line") + +GenJnlLine.COPYFILTERS(Rec); + +CopyJnlLines(GenJnlLine,Rec); + +LOCAL CopyJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line") + +IF FromGenJnlLine.FINDSET THEN BEGIN + +GenJnlBatch.GET(FromGenJnlLine."Journal Template Name",FromGenJnlLine."Journal Batch Name"); + +REPEAT + +TempGenJnlLine := FromGenJnlLine; + +TempGenJnlLine.INSERT; + +UNTIL FromGenJnlLine.NEXT = 0 + +END ELSE + +CreateTempJnlLines(FromGenJnlLine,TempGenJnlLine); + +LOCAL CreateTempJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line") + +PaymentDocNo := FromGenJnlLine.GETFILTER("Document No."); + +VendorBillHeader.GET(PaymentDocNo); + +VendorBillLine.RESET; + +VendorBillLine.SETCURRENTKEY("Vendor Bill List No.","Vendor No.","Due Date","Vendor Bank Acc. No.","Cumulative Transfers"); + +VendorBillLine.SETRANGE("Vendor Bill List No.",VendorBillHeader."No."); + +VendorBillLine.SETRANGE("Cumulative Transfers",TRUE); + +IF VendorBillLine.FINDSET THEN BEGIN + +CumulativeAmount := 0; + +PrevVendorBillLine := VendorBillLine; + +REPEAT + +VendorBillLine.TESTFIELD("Document Type",VendorBillLine."Document Type"::Invoice); + +IF ((VendorBillLine."Vendor No." <\> PrevVendorBillLine."Vendor No.") OR (VendorBillLine."Vendor Bank Acc. No." <\> PrevVendorBillLine."Vendor Bank Acc. No.")) THEN BEGIN InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount); + +CumulativeAmount := VendorBillLine."Amount to Pay"; + +END ELSE + +CumulativeAmount += VendorBillLine."Amount to Pay"; + +PrevVendorBillLine := VendorBillLine; + +UNTIL VendorBillLine.NEXT = 0; InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount); + +END; + +VendorBillLine.SETRANGE("Cumulative Transfers",FALSE); + +IF VendorBillLine.FINDSET THEN + +REPEAT + +VendorBillLine.TESTFIELD("Document Type",VendorBillLine."Document Type"::Invoice); InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,VendorBillLine,VendorBillLine."Amount to Pay"); + +UNTIL VendorBillLine.NEXT = 0; + +LOCAL InsertTempGenJnlLine(VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line";VendorBillHeader : Record "Vendor Bill Header";VendorBillLine : Record "Vendor Bill Line";AmountToPay : Decimal) + +WITH TempGenJnlLine DO BEGIN + +INIT; + +"Journal Template Name" := ''; + +"Journal Batch Name" := ''; + +"Document Type" := "Document Type"::Payment; + +"Document No." := VendorBillLine."Vendor Bill List No."; + +"Line No." := VendorBillLine."Line No."; + +"Account No." := VendorBillLine."Vendor No."; + +"Account Type" := TempGenJnlLine."Account Type"::Vendor; + +"Bal. Account Type" := TempGenJnlLine."Bal. Account Type"::"Bank Account"; + +"Bal. Account No." := VendorBillHeader."Bank Account No."; + +"Applies-to Ext. Doc. No." := VendorBillLine."External Document No."; + +Amount := AmountToPay; + +"Applies-to Doc. Type" := VendorBillLine."Document Type"; + +"Applies-to Doc. No." := VendorBillLine."Document No."; + +"Currency Code" := VendorBillHeader."Currency Code"; + +"Due Date" := VendorBillLine."Due Date"; + +"Posting Date" := VendorBillHeader."Posting Date"; + +"Recipient Bank Account" := VendorBillLine."Vendor Bank Acc. No."; + +Description := VendorBillLine.Description; + +"Message to Recipient" := VendorBillLine."Description 2"; + +INSERT; + +END; + +The derived local feature flow is as follows: + +[![ ][image2]][anchor3] + +Figure 3\. The local country object flow + +As we can see from the diagram, this solution allows integration of the local and W1 features with a minimum amount of changes in W1 code. The only two differences are: + +1. The entry point of the flow is the local table/page. + +1. Codeunit 1222 is overloaded to prepare general journal lines from the local records. + +## NAV Usages + +The data mapping technique has been used for the SEPA Credit Transfer feature, and will be used in subsequent local integration projects. + +## Ideas for improvement + +A weak point for this pattern is the need to set a filter on the empty journal line in order to retrieve the local data when exporting from a local page. This can cause problems if the size of the local table document number is larger than the Document No. field (ID 20) in the Gen. Journal line table (81). + +Also, there is a strong need for thorough testing when using this pattern, because there might be differences in the behavior of the local table and table 81\. Whatever is acceptable for the local table may not be acceptable for the W1 table. A deep functional analysis is needed to see if the local export feature uses the same constraints as the W1 feature. + + + +[anchor0]: http://en.wikipedia.org/wiki/Proxy_pattern +[anchor1]: 5123.Feature-localization-for-data-structures-1.png +[anchor2]: 6052.Feature-localization-for-data-structures-2.png +[anchor3]: 3058.Feature-localization-for-data-structures-3.png + + +[image0]: 5123.Feature-localization-for-data-structures-1.png +[image1]: 6052.Feature-localization-for-data-structures-2.png +[image2]: 3058.Feature-localization-for-data-structures-3.png diff --git a/content/NAVPatterns/fieldcaption-and-tablecaption/index.md b/content/NAVPatterns/fieldcaption-and-tablecaption/index.md new file mode 100644 index 00000000..5a520b78 --- /dev/null +++ b/content/NAVPatterns/fieldcaption-and-tablecaption/index.md @@ -0,0 +1,18 @@ ++++ +title = "fieldcaption-and-tablecaption.md" +weight = 580 ++++ +For user messages, errors etc., use FIELDCAPTION not FIELDNAME and TABLECAPTION not TABLENAME. + +Reason: + +1. The correct translation will be automatically used. +2. If the caption/name changes, then there will be a single point of change needed. + +Bad code + + IF NOT CONFIRM(UpdateLocationQst,TRUE,FIELDNAME("Location Code"),...) + +Good code + + IF NOT CONFIRM(UpdateLocationQst,TRUE,FIELDCAPTION("Location Code"),...) diff --git a/content/NAVPatterns/fielderror/index.md b/content/NAVPatterns/fielderror/index.md new file mode 100644 index 00000000..0550cae9 --- /dev/null +++ b/content/NAVPatterns/fielderror/index.md @@ -0,0 +1,16 @@ ++++ +title = "fielderror.md" +weight = 590 ++++ +Never use FIELDERROR with a period as it is automatically inserted. +Bad code + + InvalidValue@1025 : TextConst 'ENU=is invalid.'; + ... + Cust.FIELDERROR("No.",InvalidValue); + +Good code + + InvalidValue@1025 : TextConst 'ENU=is invalid'; + ... + Cust.FIELDERROR("No.",InvalidValue); diff --git a/content/NAVPatterns/findset-findfirst-findlast/index.md b/content/NAVPatterns/findset-findfirst-findlast/index.md new file mode 100644 index 00000000..c3b07d22 --- /dev/null +++ b/content/NAVPatterns/findset-findfirst-findlast/index.md @@ -0,0 +1,29 @@ ++++ +title = "findset-findfirst-findlast.md" +weight = 600 ++++ +FINDSET, FIND('+') or FIND('-') should only be used when NEXT is used and vice versa. + +Bad code + + IF Cust.FIND('-') THEN + ERROR(CustIsBlockErr) + +Good code + + IF Cust.FINDFIRST THEN + ERROR(CustIsBlockErr) + +Bad code + + IF Cust.FINDFIRST THEN + REPEAT + ... + UNTIL Cust.NEXT = 0; + +Good code + + IF Cust.FINDSET THEN + REPEAT + ... + UNTIL Cust.NEXT = 0; diff --git a/content/NAVPatterns/global-text-constants/index.md b/content/NAVPatterns/global-text-constants/index.md new file mode 100644 index 00000000..5508cf74 --- /dev/null +++ b/content/NAVPatterns/global-text-constants/index.md @@ -0,0 +1,20 @@ ++++ +title = "global-text-constants.md" +weight = 610 ++++ +Declare Text Constant as global variables. + +Bad code + + PROCEDURE GetRequirementText@6(...) : Text\[50\]; + VAR + RequirementOptionsTxt@1002 : TextConst 'ENU=Shipment,Receive,Pick,Put-Away'; + BEGIN + +Good code + + VAR + RequirementOptionsTxt@1002 : TextConst 'ENU=Shipment,Receive,Pick,Put-Away'; + ... + PROCEDURE GetRequirementText@6(...) : Text\[50\]; + BEGIN diff --git a/content/NAVPatterns/hooks/5383.HookPattern1.png b/content/NAVPatterns/hooks/5383.HookPattern1.png new file mode 100644 index 00000000..7e48236c Binary files /dev/null and b/content/NAVPatterns/hooks/5383.HookPattern1.png differ diff --git a/content/NAVPatterns/hooks/6378.HookPattern2.png b/content/NAVPatterns/hooks/6378.HookPattern2.png new file mode 100644 index 00000000..333aced2 Binary files /dev/null and b/content/NAVPatterns/hooks/6378.HookPattern2.png differ diff --git a/content/NAVPatterns/hooks/8156.HookPattern3.png b/content/NAVPatterns/hooks/8156.HookPattern3.png new file mode 100644 index 00000000..acb15838 Binary files /dev/null and b/content/NAVPatterns/hooks/8156.HookPattern3.png differ diff --git a/content/NAVPatterns/hooks/8875.HookPattern4.png b/content/NAVPatterns/hooks/8875.HookPattern4.png new file mode 100644 index 00000000..4f14a725 Binary files /dev/null and b/content/NAVPatterns/hooks/8875.HookPattern4.png differ diff --git a/content/NAVPatterns/hooks/index.md b/content/NAVPatterns/hooks/index.md new file mode 100644 index 00000000..8d9376b8 --- /dev/null +++ b/content/NAVPatterns/hooks/index.md @@ -0,0 +1,102 @@ ++++ +title = "hooks.md" +weight = 620 ++++ +_By Eric Wauters ([waldo][anchor0]), Partner-Ready-Software_ + +## Abstract + +As a partner, adding new code to NAV means interfering with code shipped by Microsoft. Minimize your footprint of changes in Microsoft code, so that, when a new NAV version is shipped, you avoid conflicts and upgrade impact. The core NAV code is the "danger zone" - the less you touch it, the happier your upgrade will be. + +Description + +When doing development over years, by different developers with different mindsets, the standard codebase gets changed a lot, adding multiple lines of code, adding local and global variants, adding or changing keys, changing existing business logic, ... . In other terms, the standard text objects are being changed all over the place.. . + +After years, it's not clear why a change was done, and what was the place where the change was intended to be done. And the latter is quite important in an upgrade process, when code in the base product is being refactored: if the exact place of the posting of the Customer Entry is being redesigned to a separate number, the first thing I need to know, is that I did a certain change at the place: "where the posting of the Customer Entry starts". The definition of that place, we call a "Hook". + +By minimizing the code in already existing application objects, you will make the upgrade process much easier, and all customization business logic will be grouped in new objects. When using atomic coding, it will be very readable what is being customized on a certain place in an existing part of the application. + +To minimize the impact of customizations, the idea of hooks is: + +* First of all, name the places in the already existing code where customization is needed; +* Second, place your business logic completely outside the already existing application code. + +I recommend to use this concept on: + +* All objects of the default applications that need to be changed +* On objects that should not hold any business logic (like tables, pages, XMLPorts) + +## Usage + +Step 1 - if it doesn't exist yet - you create your Hook Codeunit. As the name assumes .. this is always a codeunit. We apply the following rules to it: + +* One Hook always hooks into one object. Which basically means that I will only declare this new codeunit in one other object (which is its parent object) +* The naming convention is: "The\_Original\_Object\_Name Hook". Naming conventions are important, just to find your mapped object, and also to be able to group the Hooks. + +Step 2, you create the hook, which is basically a method (function) in your codeunit. The naming is important: + +* The naming of the hook should NOT describe what it is going to do (So, examples like "CheckMandatoryFields", "FillCustomFields" should not be used as a hook) +* The naming of the hook should describe WHERE the hook is placed, not what the hook will be doing (as nobody is able to look into the future .. :-)) +* To help with the naming, it is a good convention to use the "On"-prefix for these triggers. This way, it's very clear what are hooks, and what aren't.. + +Step 3, it's time to hook it to its corresponding object and right place in the business logic of that object. You do this by declaring your codeunit as a global in your object, and using the created hook function on its place in the business logic. This way, these one-liners apply: + +* A Hook Codeunit is only used once in one object only (its corresponding object) +* A Hook (function) is used only once in that object. As a consequence, changing the parameters has no consequence: you only need to change one function-call +* The codeunit is declared as a global. That exact global is the only custom declaration in the existing object .. Everything else is pushed to the hook-codeunit. + +Step 4, implement your business logic in the hook. Do this in the most atomic way, as there is a good chance that this same hook is going to be used for other business logic as well. Best is to use a one-line-function-call to business logic, so that the Hook Function itself stays readable. + +## Example + +Suppose, we want to add business logic just before posting a sales document. In that case, we have to look for the most relevant place, which is somewhere in the "Sales-Post" codeunit. So: + +Step 1: create codeunit "Sales-Post Hook" + +[![ ][image0]][anchor1] + +Step 2: create the hook function "OnBeforePostDocument" + +[![ ][image1]][anchor2] + +Step 3: declare a global in the "Sales-Post"-codeunit, called "SalesPostHook". Then, call the Hook Function that you created in Step 2 in the right place. + +[![ ][image2]][anchor3] + +Step 4: implement the business logic, by calling out to a new function. And implement the test-codeunit. + +[![ ][image3]][anchor4] + +## Consequences + +This pattern can be used in all cases to put busines logic. But I see three possible approaches + +1. You only declare the most important and most used hooks + * This way, you limit the amount of objects and hooks to only a few in the default product + * For example, only the OnBeforePostSalesHeader, OnBeforeReleaseSalesDocument, .. And no field validation or such... +2. Only at objects of the default application which you are customizing. + * This way, you don't want to create hooks for your own objects, only default existing objects. +3. (recommended) You create hooks on all places you don't want to write business logic, and on all existing objects which you would like to customize. + * This is a very consistent way of working, as in any case, your business logic ends up in either a hook, or in its corresponding objects from a specific design pattern. But you know that the entry point is always a hook. + * You know what to expect in any case, both changed business logic in existing code and business logic in newly created code is entered from a hook. + +## Related Topics + +Atomic coding: It's important that the hook function is readable in the most extreme way. For this, we recommend to use the "Atomic Coding" concept. + +See here a comparison / extension of hooks : [http://www.waldo.be/2016/02/29/nav-2016-hooks-or-events/][anchor5] + + + +[anchor0]: http://www.waldo.be "waldo's blog" +[anchor1]: 5383.HookPattern1.png +[anchor2]: 6378.HookPattern2.png +[anchor3]: 8156.HookPattern3.png +[anchor4]: 8875.HookPattern4.png +[anchor5]: http://www.waldo.be/2016/02/29/nav-2016-hooks-or-events/ + + +[image0]: 5383.HookPattern1.png +[image1]: 6378.HookPattern2.png +[image2]: 8156.HookPattern3.png +[image3]: 8875.HookPattern4.png diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0333.Figure-3.PNG b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0333.Figure-3.PNG new file mode 100644 index 00000000..a5b92cbe Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0333.Figure-3.PNG differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0458.Figure-1.PNG b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0458.Figure-1.PNG new file mode 100644 index 00000000..ef41da07 Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0458.Figure-1.PNG differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0552.Example-Figure-5.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0552.Example-Figure-5.png new file mode 100644 index 00000000..4f23c91a Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0552.Example-Figure-5.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0638.Figure-2.PNG b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0638.Figure-2.PNG new file mode 100644 index 00000000..d32b76a3 Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/0638.Figure-2.PNG differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1488.Example-Figure-1.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1488.Example-Figure-1.png new file mode 100644 index 00000000..1b9271de Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1488.Example-Figure-1.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1884.Example-Figure-7.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1884.Example-Figure-7.png new file mode 100644 index 00000000..d03541ac Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/1884.Example-Figure-7.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/2068.Example-Figure-4.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/2068.Example-Figure-4.png new file mode 100644 index 00000000..023a947f Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/2068.Example-Figure-4.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4477.Example-Figure-6.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4477.Example-Figure-6.png new file mode 100644 index 00000000..a32c6b86 Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4477.Example-Figure-6.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4532.Example-Figure-3.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4532.Example-Figure-3.png new file mode 100644 index 00000000..463d2358 Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4532.Example-Figure-3.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4682.Example-Figure-2.png b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4682.Example-Figure-2.png new file mode 100644 index 00000000..4a95a938 Binary files /dev/null and b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/4682.Example-Figure-2.png differ diff --git a/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/index.md b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/index.md new file mode 100644 index 00000000..f64fc8e6 --- /dev/null +++ b/content/NAVPatterns/implementation-of-surrogate-keys-using-autoincrement-pattern/index.md @@ -0,0 +1,180 @@ ++++ +title = "implementation-of-surrogate-keys-using-autoincrement-pattern.md" +weight = 630 ++++ +_By [Soren Klemmensen][anchor0], [_Partner-Ready-Software_ ][anchor1]& [360 Visibility][anchor2]_ + +## **Abstract** + +This Pattern is meant to create generic & reusable links between tables. The goal is to have an easy generic way to link a generically designed sub table to a record on a main table which can be used for other links too. + +To minimize the impact of customizations and to keep modules as generic and reusable as possible the idea of the Implementation of surrogate keys using AutoIncrement pattern is: + +* To create a generic and reusable auto generated link (A Surrogate Key), Immune to natural key data & requirement changes, on a main table with minimum impact on the table. +* To create generic and reusable sub tables that effortless can be reused anywhere in the application. + +## **Description** + +Over years of development many things are repeated across different implementation and even inside the same application. A typical example could be adding comments to an area just as it is done in Microsoft Dynamics NAV multiple times. There can be reasons for doing this again and again, but not only does this need to be maintained and upgraded over the years, but all the implementations of comments also needs to be tested separately. If a standard and generic comment could be developed and a generic way of connecting it to a main table this could be resolved. This is exactly what this pattern is trying accomplish. + +[![ ][image0]][anchor3] + +_Figure 1: Table structure for linking a Document Header and Line Table with a Document Comment Table._ + +__ + +_[![ ][image1]][anchor4]_ + +_Figure 2: Table Structure for linking a Master Data Table with a Master Data Comment Table_ + +__ + +A typical way of linking a table to master data or to a document has been to use the primary key of the table being linked to. This causes some issues as the linked table now is designed specifically for the main table and it functionality cannot be reused. In case of renames the linked table needs to be renamed too which is costly in processing. Code also needs to be added on the delete trigger of the table to ensure that the attached records get removed if needed which increases the over all footprint of any change. + +_[![ ][image2]][anchor5]_ + +_Figure 3: A Generic Way of creating a Comment table and linking it in a generic way to the main table no matter what this table might be. The Unique Record Identifier on the main tables is an Integer with AutoIncrement set to yes._ + +__ + +It is recommended using this pattern in all tables which need sub tables unless specific reasons exists for not doing this. + +## **Usage** + +**Step 1**: Create a generic Unique Record Identifier in the main table + +The Pattern is implemented by adding a Field (I have called it Unique Record Identifier for this article) in a table (the main Table) where links are needed to be established to. Set the Property Data Type to Integer, Editable to No & AutoIncrement to Yes. + +**Step 2**: Create a generic link-able sub table. + +Create a new table (Sub Table) which you would like to be reusable with a primary key containing + +* Table No. of Data Type Integer +* Unique Record Identifier of Data Type Integer +* A 3 field for allowing multiple entries to exist per record in the main table if so needed. This could be a Line No. of Data Type Integer or a Code field of Data Type Code(10) and so on. + +The important part here is that the 2 or 3 first fields in the tables primary key is the Table No. and the Unique Record Identifier. If a 3rd field was added to allow for multiple entries to exist per record in the main table this should also be included in the primary key. + +Make sure to also add any other fields containing the information you wish to store as needed to the table. + +The sub table will be immune to renames from the main table as the main tables primary key is not used in the primary key of the sub table. The Insert, Modify and Rename triggers are not causing any issues and only the delete trigger will need to be considered. This can be dealt with generically from the OnDatabaseDelete trigger in Codeunit 1\. I would recommend to use a Hook Pattern for this. + +**Step 3**: Create a page showing the sub table information. + +Now create a page showing the data in the sub table. + +**Step 4**: Add an Action or factbox. + +Create an action or factbox on the pages showing the main table data linking to the subpage with Table ID filtered to a constant of the Table No. of the main table and the Unique Record Identifier of the sub table filtering to the Unique Record Identifier of the main table. + +**Step 5**: Create a Hook for Function OnDatabaseDelete in Codeunit 1 ApplicationManagement if one doesn't already exist. See the Hook pattern. + +**Step 6**: Create a code to delete records in the Sub table if a main table record is deleted if this is required. This function needs to be called from the Hook created in Step 5\. + +## **NAV Specific Example** + +Let's assume we would like to create comment for a larger number of very different tables in the system. + +**Update the Customer table (Step 1)**: Go to table 18 Customer and add Field 50000 Unique Record Identifier. Set the Property Data Type to Integer, Editable to No & AutoIncrement to Yes. Save the changes. + +_[![ ][image3]][anchor6]_ + +__ + +_[![ ][image4]][anchor7]_ + +__ + +**Create Comment table (Step 2)**: Create a new table called Comment. Add 3 fields Table No., Unique Record Identifier & Line No. all of Data Type Integer. Make these 3 fields into the primary key for the table. Add a 4 field called Comment with Data Type Text(80). Save the changes. + +[![ ][image5]][anchor8] + +**Create the Comments page (Step 3)**: Start the page wizard and create a Page based on table comment created above as a List only showing the Comment field. Set AutoSplitKey property to Yes on the page. + +__ + +_[![ ][image6]][anchor9]_ + +__ + +**Update the Customer Card (Step 4)**: Add an action to the Customer Card to open the Comments. Go to Actions and create an action called Smart Comment. Populate the properties RunObject, RunPageView and RunPageLink as see in the picture below. + +[![ ][image7]][anchor10] + +__ + +**Create a hook OnDatabaseDelete (Step 5)**: + +Create a codeunit 50000 called "ApplicationManagement Hook" with one function called OnAfterOnDatabaseDelete taking the parameter RecRef of Data Type RecordRef. Add it as a global variable to Codeunit 1 ApplicationManagement and call the function as the last line in OnDatabaseDelete. Please read about the hook pattern before implementing it. + +[![ ][image8]][anchor11] + +__ + +**Create the code needed to delete comments linked to a deleted record (Step6)**: + +Create a DeleteComments function taking the RecRef of Data Type RecordRef and add the code as shown blow. + +[![ ][image9]][anchor12] + +__ + +It is assumed in this example for simplicity that the Field 50000 is reserved across the entire application for the Unique Record Identifier as defined in Step 1\. + +The comments are now fully working if we look away from the fact that we did not deal with a few things specific to Sales orders like RecreateSalesLines function, Archiving and Copy Document. All of which can easily be dealt with. + +These comments are now completely reusable everywhere else in the system. Sales Document is a perfect example as the primary keys of the Sales Header and the Sales line are both different from the customer and normally we would not be able to use the comments header or the line. All that needs to be done is adding the Field 50000 Unique Record Identifier to the Sales Header & Sales Line (Disregarding the posted documents in this example) and creating the actions on the Page Actions with the needed filters. Deletion is already handled of comments no matter what the main table might be. + +Looking at the main table the Unique Record Identifier is also completely reusable for any other linking needed. + +Other ideas for use of this pattern could be. An Error table, Tags, Dynamically defined fields and Generic fact boxes. Only the imagination sets limits for its use. + +Upgrade wise there can be an impact if data is moved out of tables to be reinserted again because of a change to a database structure. This will cause the Unique Record Identifier to change, unless steps are taken to avoid this, and the links will need to be reestablished. + +Other risks could be if Transfer Fields are used and data is being copied unintentionally. + +## **NAV Usages** + +This is a new pattern not currently used in Microsoft Dynamics NAV. + +## **Ideas for improvement ****** + +The reason for doing it this way is that you now can reuse your code again and again with only creating the same link on other tables instead of building it from scratch each time reducing testing needed and improving the quality of the overall product. + +## **Consequences (When it should not be used)** + +This can be used on any table when linking anything to it that can be considered a generic module which can be reused. That said it should not be used in cases where there is a risk of tables growing so much that performance could be impacted. There are ways to reduce performance impact when using high volume tables, but that is outside the scope of this pattern. + +## **Related Topics** + +This is related to the hook pattern as far as they both try to reduce the footprint changes have on the standard application, by creating reusable ways to interact with the standard code. That said the hook pattern is more about hooking the functionality to existing while this pattern is more about creating reusable ways of creating functionality. + +__ + + + +[anchor0]: http://mvp.microsoft.com/en-us/mvp/Soren%20Klemmensen-5001002 "Soren Klemmensen" +[anchor1]: http://partner-ready-software.com/ "Partner-Ready-Software" +[anchor2]: http://www.360visibility.com/ "360 Visibility" +[anchor3]: 0458.Figure-1.PNG +[anchor4]: 0638.Figure-2.PNG +[anchor5]: 0333.Figure-3.PNG +[anchor6]: 1488.Example-Figure-1.png +[anchor7]: 4682.Example-Figure-2.png +[anchor8]: 4532.Example-Figure-3.png +[anchor9]: 2068.Example-Figure-4.png +[anchor10]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/0552.Example-Figure-5.png +[anchor11]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/4477.Example-Figure-6.png +[anchor12]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/1884.Example-Figure-7.png + + +[image0]: 0458.Figure-1.PNG +[image1]: 0638.Figure-2.PNG +[image2]: 0333.Figure-3.PNG +[image3]: 1488.Example-Figure-1.png +[image4]: 4682.Example-Figure-2.png +[image5]: 4532.Example-Figure-3.png +[image6]: 2068.Example-Figure-4.png +[image7]: 0552.Example-Figure-5.png +[image8]: 4477.Example-Figure-6.png +[image9]: 1884.Example-Figure-7.png diff --git a/content/NAVPatterns/in-context-notifications/2514.Fig4.png b/content/NAVPatterns/in-context-notifications/2514.Fig4.png new file mode 100644 index 00000000..ff09925b Binary files /dev/null and b/content/NAVPatterns/in-context-notifications/2514.Fig4.png differ diff --git a/content/NAVPatterns/in-context-notifications/2526.Fig11.png b/content/NAVPatterns/in-context-notifications/2526.Fig11.png new file mode 100644 index 00000000..cc4a7869 Binary files /dev/null and b/content/NAVPatterns/in-context-notifications/2526.Fig11.png differ diff --git a/content/NAVPatterns/in-context-notifications/6646.Fig9.png b/content/NAVPatterns/in-context-notifications/6646.Fig9.png new file mode 100644 index 00000000..ec3b5ead Binary files /dev/null and b/content/NAVPatterns/in-context-notifications/6646.Fig9.png differ diff --git a/content/NAVPatterns/in-context-notifications/6724.Fig2.png b/content/NAVPatterns/in-context-notifications/6724.Fig2.png new file mode 100644 index 00000000..3d3c9b8d Binary files /dev/null and b/content/NAVPatterns/in-context-notifications/6724.Fig2.png differ diff --git a/content/NAVPatterns/in-context-notifications/7701.Fig1.png b/content/NAVPatterns/in-context-notifications/7701.Fig1.png new file mode 100644 index 00000000..84fd9867 Binary files /dev/null and b/content/NAVPatterns/in-context-notifications/7701.Fig1.png differ diff --git a/content/NAVPatterns/in-context-notifications/index.md b/content/NAVPatterns/in-context-notifications/index.md new file mode 100644 index 00000000..bf40a100 --- /dev/null +++ b/content/NAVPatterns/in-context-notifications/index.md @@ -0,0 +1,242 @@ ++++ +title = "in-context-notifications.md" +weight = 640 ++++ +___By Soumya Dutta at Microsoft Development Center Copenhagen_ + +## Context + +Application developers need to raise a notification on events that are not blocking but do require attention from users. Notifications alert users to issues or information, and let them decide whether to react immediately or finish what they're doing first. + +## Problem + +Application developers have started to use system calls like CONFIRM or MESSAGE to alert or inform users about a condition. These calls interrupt users by displaying a window in the middle of the screen and forcing an immediate response. + +## Solution + +Notifications display a message in a blue bar at the top of the workspace, as shown in Figure 1\. + +[![ ][image0]][anchor0] + +Figure 1 - Example of a notification + +Notifications alert users to something they probably should act on, but can choose to ignore. For example, a notification might alert someone who is about to invoice a customer for inventory that isn't available, as shown in Figure 1, but allow them to post the invoice anyway. This is different from an error that prevents someone from posting an invoice without specifying a required field. + +In this example, if you choose **Details** a page opens to show the status of the inventory, as shown in Figure 2\. + +[![ ][image1]][anchor1] + +Figure 2 - Clicking an action in a notification + +## Raising a notification + +The code in Figure 3 raises the notification in Figure 1\. + +**COD 311: Item-Check Avail.** + +**CreateAndSendNotification** + +AvailabilityCheckNotification.ID(GetItemAvailabilityNotificationId); + +AvailabilityCheckNotification.MESSAGE(STRSUBSTNO(NotificationMsg,ItemNo)); + +AvailabilityCheckNotification.SCOPE(NOTIFICATIONSCOPE::LocalScope); + +AvailabilityCheckNotification.ADDACTION(DetailsTxt,CODEUNIT::"Item-Check Avail.",'ShowNotificationDetails'); + +ItemAvailabilityCheck.PopulateDataOnNotification(AvailabilityCheckNotification,ItemNo,UnitOfMeasureCode + +,InventoryQty,GrossReq,ReservedReq,SchedRcpt,ReservedRcpt,CurrentQuantity,CurrentReservedQty, + +TotalQuantity,EarliestAvailDate); + +AvailabilityCheckNotification.SEND; + +... + +Figure 3 - Raising a notification + +The first thing to note is that a new Notification DataType object has been introduced to C/SIDE. + +[![ ][image2]][anchor2] + +Figure 4\. Notification is a new data type + +In the code sample in Figure 3, the first line defines the scope. Currently , only the LocalScope is supported. + +### Identifying a notification + +The ID is an optional parameter for the notification object that tracks the object in communications between the client and the server. Notifications have unique IDs that can be hard coded as GUIDs, as shown in Figure 5\. A GUID can be generated using [the CREATEGUID system function][anchor3]. + +**COD 311: Item-Check Avail.** + +**GetItemAvailabilityNotificationId** + +EXIT('2712AD06-C48B-4C20-820E-347A60C9AD00');**** + +Figure 5\. Uniquely identifying a notification + +If the call to set ID is skipped, sending the notification creates a new notification with an ID that is generated at run-time instead of updating a notification that is already displayed (if present) with the ID. + +### Including messages notifications + +Notifications should display a message. This message is set by an assignment call to the **MESSAGE** parameter of the notification object. + +### Invoking actions on notifications + +Notifications can display action buttons, as shown in Figure 2 where a button named **Details** opens the inventory status for the item. To do that, when the button is clicked the **ADDACTION** method is invoked on the notification object using the following parameters: + +* The text for the button. +* The code unit number that hosts the method to call. +* The name of the invoked method in the above code unit to call. + +Figure shows the method that is called when the action is invoked- ShowNotificationDetails. + +**COD 311: Item-Check Avail.** + +**ShowNotificationDetails** + +ItemAvailabilityCheck.InitializeFromNotification(AvailabilityCheckNotification); + +ItemAvailabilityCheck.SetHeading(AvailabilityCheckNotification.MESSAGE); + +ItemAvailabilityCheck.RUNMODAL;**** + +Figure 6 - Invoking an action + +To show the inventory status using the Availability check page, certain parameters must be initialized. For example, the item number, the unit of measure code, and so on. This is done in the call to InitializeFromNotification method on the page. Figure 7 shows the code for this call. + +**Page 1872: Item Availability Check** + +**InitializeFromNotification** + +GET(AvailabilityCheckNotification.GETDATA('ItemNo')); + +SETRANGE("No.",AvailabilityCheckNotification.GETDATA('ItemNo')); + +EVALUATE(TotalQuantity,AvailabilityCheckNotification.GETDATA('TotalQuantity')); + +EVALUATE(InventoryQty,AvailabilityCheckNotification.GETDATA('InventoryQty')); + +CurrPage.AvailabilityCheckDetails.PAGE.SetUnitOfMeasureCode( + +AvailabilityCheckNotification.GETDATA('UnitOfMeasureCode')); + +Figure 7 - Fetching parameters from a notification object + +Note how **GETDATA** uses a key to fetch values from the notification object, and how those values are used to initialize the page. + +Notifications can include zero, one, or more than one action buttons. More than one action buttons result in multiple **ADDACTION** calls to the notification object. + +### Populating parameters on notifications + +Actions use the values set on the notification objects. As shown in Figure 3 and Figure 7, the line that calls the method PopulateDataOnNotification does that. The result is shown in Figure 8\. + +**Page 1872: Item Availability Check** + +**PopulateDataOnNotification** + +AvailabilityCheckNotification.SETDATA('ItemNo',ItemNo); + +AvailabilityCheckNotification.SETDATA('UnitOfMeasureCode',UnitOfMeasureCode); + +AvailabilityCheckNotification.SETDATA('GrossReq',FORMAT(GrossReq)); + +... + +Figure 8 - Populating parameters on notifications + +The invoked method must be stateless. Therefore, the context for creating the notification should be reproducible by using data that could be a part of the notification object. In this example, the SETDATA method on the notification object passes values for the item number, unit of measure code, and so on, as key value pairs. + +### Displaying the notification to the user + +The last line in Figure 3 calls **SEND** to display the notification. If you know the ID of the notification, you can also call **RECALL** to hide it. However, avoid updating a displayed notification, for example by changing the message, by calling both **RECALL** and **SEND**. This makes two server--client calls. Instead, call only **SEND**. Calling **SEND** for a notification that is already displayed updates the notification. + +## Turning notifications on or off, and controlling when they are sent + +By default, all notifications are turned on. However, you can specify the notifications you want to receive, and turn on or turn off some or all of them. For example, if you don't want to be disturbed or are willing to accept the consequences of ignoring the message. This is unique to notifications. + +[![ ][image3]][anchor4] + +Figure 9 - The My Notifications page + +Additionally, some notifications let you specify the conditions under which they are sent. For example, if you want to be notified when inventory is running low, but only for items you buy from a certain vendor. + +1. In the top right corner, choose the Search for Page or Report icon, enter my notifications, and then choose the related link. +2. To turn on or turn off a notification, select or clear the Enabled check box. +3. To specify conditions that trigger a notification, choose View filter details, and then fill in the fields. + +The **MyNotifications** object determines whether notifications are turned on or off. Notifications are isolated from each other by the hard-coded GUID, as discussed in the section titled Identifying a notification. A fixed ID is essential to turning off a notification. The following are ways to achieve this. + +1. **OnInitializingNotificationWithDefaultState** is a published method on the **MyNotifications** page that is called when the enabled state of all the notifications is initialized. + +**Codeunit 311: Item-Check Avail.** + +**OnInitializingNotificationWithDefaultState** + +MyNotifications.InsertDefaultWithTableNum(GetItemAvailabilityNotificationId, + +ItemAvailabilityNotificationTxt, + +ItemAvailabilityNotificationDescriptionTxt, + +DATABASE::Item); + +Figure 10 - Adding a notification to the My Notifications page + +You must subscribe to this method and call either **InsertDefault** or **InsertDefaultWithTableNum** on the **MyNotifications** table. Both of these take the ID of the notification, a short description of the notification, and text that provides details about the conditions for the notification. The difference is that the **InsertDefaultWithTableNum** method takes an additional argument representing the table number if there is specific criteria for when to turn on a notification for a certain table. In this case, the notification can be enabled only for items that the criteria specified in the FilterPage. The FIlterPage is opened from the **MyNotifications** page. + +[![ ][image4]][anchor5] + +Figure 11 - Defining filter criteria to turn on a notification + +1. **IsEnabled** or **IsEnabledForRecord** are used to query if the notification is turned on. It may make sense to call this as early as possible in the condition checks, so you don't make calculations that will not yield much if the notification is turned off. The second method takes the additional parameter that represents the record for which the enabled state is to be determined. In Figure 12, the check is for an item. + +**Codeunit 311: Item-Check Avail.** + +**IsItemAvailabilityNotificationEnabled** + +**EXIT**(MyNotifications.IsEnabledForRecord(GetItemAvailabilityNotificationId,Item)); + +Figure 12 - Checking whether notifications are turned on + +You may check that the call to this function is made almost as the first step in checking for availability. + +1. **OnStateChanged** event should be subscribed to if the developer needs to do something additional when changing the state of a notification, such as turn on another notification. + +The ability to turn notifications on or off is not required. If skipped, the notification is always shown when the condition that triggers it is met, and a user cannot turn it off. + +# NAV specific usages + +For examples of how these objects are used in Dynamics NAV, look at the code for the following objects: + +1. Codeunit 1802 Data Migration Notifier +2. Codeunit 311 Item-Check Avail. +3. Codeunit 312 Cust-Check Cr. Limit +4. Codeunit 1854 Item Sales Forecast Notifier (in SalesAndInventoryForecast extension) +5. Codeunit 1852 Item Sales Forecast Scheduler (in SalesAndInventoryForecast extension) + +# Best practices + +The following list summarizes best practices for creating notifications: + +1. Do not set data on the notification that you will not use in the method invoked from the action button. +2. Ensure that the **MyNotifications** table is accessed only as described above, and that the correct pairs of calls are made. For example, **InsertDefault**...**IsEnabled** and **InsertDefaultWithTableNum** ...**IsEnabledForRecord**. +3. Do not call **RECALL** before **SEND** in a server call-back if you need to update a notification that is already displayed. Instead, call only **SEND** to update the notification. This reduces traffic on the network. +4. Ensure that the method specified on the **ADDACTION** method for the notification is (a) exists, (b) is global and (c) follows the signature described above. + + + +[anchor0]: 7701.Fig1.png +[anchor1]: 6724.Fig2.png +[anchor2]: 2514.Fig4.png +[anchor3]: https://msdn.microsoft.com/en-us/library/dd339033.aspx +[anchor4]: 6646.Fig9.png +[anchor5]: 2526.Fig11.png + + +[image0]: 7701.Fig1.png +[image1]: 6724.Fig2.png +[image2]: 2514.Fig4.png +[image3]: 6646.Fig9.png +[image4]: 2526.Fig11.png diff --git a/content/NAVPatterns/indentation/index.md b/content/NAVPatterns/indentation/index.md new file mode 100644 index 00000000..064c1c1d --- /dev/null +++ b/content/NAVPatterns/indentation/index.md @@ -0,0 +1,84 @@ ++++ +title = "indentation.md" +weight = 650 ++++ +In general, use an indentation of two space characters. Logical expressions in the IF, WHILE, and UNTIL parts are indented at least 3, 6, and 6 spaces respectively. +Bad code + + IF GLSetup."Unrealized VAT" OR + (GLSetup."Prepayment Unrealized VAT" AND NewCVLedgEntryBuf.Prepayment) + +Good code + + IF GLSetup."Unrealized VAT" OR + (GLSetup."Prepayment Unrealized VAT" AND NewCVLedgEntryBuf.Prepayment) + +Bad code + + IF GenJnlLine."Account No." <\> ICPartner.Code THEN + ICPartner.GET("Account No."); + IF GenJnlLine.Amount \> 0 THEN BEGIN + ... + +Good code + + IF GenJnlLine."Account No." <\> ICPartner.Code THEN + ICPartner.GET("Account No."); + IF GenJnlLine.Amount \> 0 THEN BEGIN + ... + +Bad code + + Dialog.OPEN(WindowTxt + + '@1@@@@@@@@@@@@@@@@@@@@@@@'); + +Good code + + Dialog.OPEN( + WindowTxt + + '@1@@@@@@@@@@@@@@@@@@@@@@@'); + +Bad code + + TempOldCustLedgEntry.DELETE; + // Find the next old entry for application of the new entry + +Good code + + TempOldCustLedgEntry.DELETE; + // Find the next old entry for application of the new entry + + +Bad code + + IF NOT ("Applies-to Doc. Type" IN + \["Applies-to Doc. Type"::Receipt, + "Applies-to Doc. Type"::"Return Shipment"\]) + +Good code + + IF NOT ("Applies-to Doc. Type" IN + \["Applies-to Doc. Type"::Receipt, + "Applies-to Doc. Type"::"Return Shipment"\]) + +Bad code + + WHILE (RemAmt \> 0) OR + (RemAmtLCY \> 0) + DO + +Good code + + WHILE (RemAmt \> 0) OR + (RemAmtLCY \> 0) + DO + +Bad code + + UNTIL (RemAmt \> 0) AND + (RemAmtLCY \> 0); + +Good code + + UNTIL (RemAmt \> 0) AND + (RemAmtLCY \> 0) diff --git a/content/NAVPatterns/initialized-variables/index.md b/content/NAVPatterns/initialized-variables/index.md new file mode 100644 index 00000000..7f9f47d4 --- /dev/null +++ b/content/NAVPatterns/initialized-variables/index.md @@ -0,0 +1,49 @@ ++++ +title = "initialized-variables.md" +weight = 660 ++++ +Variables should always be set to a specific value, before they are used. + +Bad code + + PROCEDURE SetPurchLine@22(VAR CurrentPurchLine@1000 : Record 39); + VAR + Pegging@1001 : Boolean; + BEGIN + IF Pegging THEN + CurrQuantity := CurrentPurchLine."Quantity (Base)" + ELSE + CurrQuantity := CurrentPurchLine."Outstanding Qty. (Base)"; + END; + +Good code + + PROCEDURE SetPurchLine@22(VAR CurrentPurchLine@1000 : Record 39); + VAR + Pegging@1001 : Boolean; + BEGIN + Pegging := IsPegging(CurrentPurchLine); + IF Pegging THEN + CurrQuantity := CurrentPurchLine."Quantity (Base)" + ELSE + CurrQuantity := CurrentPurchLine."Outstanding Qty. (Base)"; + END; + +Bad code + + // In the example below, the function will always return FALSE. + PROCEDURE GetItemsToPlan@22() : Boolean; + BEGIN + SETRANGE("Document Type","Document Type"::Order); + ... + FINDSET + END; + +Good code + + PROCEDURE GetItemsToPlan@22() : Boolean; + BEGIN + SETRANGE("Document Type","Document Type"::Order); + ... + EXIT(FINDSET) + END; diff --git a/content/NAVPatterns/instructions-in-the-ui/2804.Picture-2.png b/content/NAVPatterns/instructions-in-the-ui/2804.Picture-2.png new file mode 100644 index 00000000..d6df77d4 Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/2804.Picture-2.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/5707.Picture-4.png b/content/NAVPatterns/instructions-in-the-ui/5707.Picture-4.png new file mode 100644 index 00000000..5976b18c Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/5707.Picture-4.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/6215.picture-1.png b/content/NAVPatterns/instructions-in-the-ui/6215.picture-1.png new file mode 100644 index 00000000..cf794efa Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/6215.picture-1.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/6685.picture-3.png b/content/NAVPatterns/instructions-in-the-ui/6685.picture-3.png new file mode 100644 index 00000000..f75ce0c1 Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/6685.picture-3.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/7217.picture-1.png b/content/NAVPatterns/instructions-in-the-ui/7217.picture-1.png new file mode 100644 index 00000000..9f15bb4e Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/7217.picture-1.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/7245.Picture-2.png b/content/NAVPatterns/instructions-in-the-ui/7245.Picture-2.png new file mode 100644 index 00000000..d0184198 Binary files /dev/null and b/content/NAVPatterns/instructions-in-the-ui/7245.Picture-2.png differ diff --git a/content/NAVPatterns/instructions-in-the-ui/index.md b/content/NAVPatterns/instructions-in-the-ui/index.md new file mode 100644 index 00000000..7e2ef45f --- /dev/null +++ b/content/NAVPatterns/instructions-in-the-ui/index.md @@ -0,0 +1,157 @@ ++++ +title = "instructions-in-the-ui.md" +weight = 670 ++++ +_by Nikola Kukrika at Microsoft Development Center Copenhagen_ + +## Abstract + +To mitigate usability problems with learnability or discoverability of NAV functionality, it is possible to embed instructions in the UI in connection with the task that the user is performing. The goal is to explain how to use the product or feature without impairing the user's productivity after user has learned how to use a feature. + +## Description + +Users must often go through a few days of training to learn how to use NAV, and even then, many users rely on super users to help them mitigate difficulties using NAV. In addition, because of low discoverability and learnability, many useful features are not being used at all. + +Users' expectations are changing. They expect the software to be usable out-of-the-box because this is the trend in software generally. + +One of the cheapest and most effective methods to solve usability issues is to embed instructional messages in the product. From a user-experience point of view, **this should be used as a last resort**. UI should be self-explanatory, efficient, and simple to use. Accordingly, you should only implement this pattern if simplifying and improving a scenario is not possible or is too expensive. + +In this connection, the most important requirement is not to impair productivity of the users. One of the biggest and most common UX mistakes that developers make is to "optimize for new users". After the user has learned how to use the product, all the instruction texts and dialogs that we added to the UI will clutter the page and make information less visible. Instructional dialogs on routine tasks will become annoying. Therefore, we must make all instructions dismissible. + +In the Mini App solution we have used following elements: + +1. Dismissible dialogs +2. FastTabs with instructional text +3. Help tiles on a Role Center +4. Tooltips on actions and fields +5. Task-oriented page Help + +## Usage + +The following pattern applies to dismissible parts in the UI. + +We have a table that stores the instructional code ID and the UserID, so that we can track which user has turned off which instruction. All the logic handling is done from a codeunit. It is the responsibility of the codeunit to show/hide dialogs if needed. + +[![ ][image0]][anchor0] + +## Dismissible Dialogs + +Dismissible dialogs show the instructional message about the functionality, with the user option to select "Don't show this again". This is a good solution to problems where users enter text in the wrong place, or to explain behavior of a somewhat hidden feature. + +[![ ][image1]][anchor1] + +On a recent usability study of the **Description** field on sales or purchase lines, most users ignored the **No.** field and started entering text in the description field before proceeded to enter a quantity. In the solution in question, text only is treated as a line comment if the **No.** field is blank. The fix was to update the field name to **Description/Comment** and to provide a message that typing in the field creates a comment only. Users that often use comments can then choose "Do not show again" to get rid of the instructional text. + +**When to use: **Recommendation is to use only when many users are entering data in the wrong way and modifying the code is costly. This is an interrupting dialog, but the benefits are that it is very hard to overlook this dialog. + +## FastTabs with Instructional Text + +Instructional text on FastTabs is ideal for showing larger amounts of text in the UI. + +[![ ][image2]][anchor2] + +When a user changes a filter in the **Navigate** page, we blank the grid. This may confuse the users as to how to proceed. The **Notification** FastTab provides information on what has happened and gives instructions on how to proceed. + +Similar implementation is to have the FastTab always visible with the **Do not show again** check box present, so that users can dismiss it after they have read the message. This is less intrusive than using a dialog, and it has the benefit of being always visible compared to the dialog. The drawback is that users may not read it or may not dismiss it. + +## Information Tiles on Role Centers + +On the **Small Business Role Center** page (9022), we have implemented a **Getting Started** group containing action tiles. Clicking on the first two tiles will play instructional videos. Clicking on the third tile launches a dedicated help topic. Since these tiles will get in the way of the experienced users, an option to hide the entire group is provided. + +[![ ][image3]][anchor3] + +**Note**: in NAV 2013 R2, actions appear as tiles in the web client only. In the win client, they appear as links. In the web client, the actions only appear if they are in a group for themselves (without Stack Queues -- empty group with only actins defined). + +### To implement tiles for instructional videos + +1. Upload a video to a video hosting service (check if licensing is allowing you to use if for this usage. Examples of video hosting services are: YouTube, Vimeo, Yahoo Video.) +2. Get the code to embed the video (select option embed). +3. You can reuse the code on the **Mini Video Player Page** page (1395) or implement a custom one. + +Important parts: +**VideoPlayerAddIn.SetFrameAttribute** function is used to set an attribute to the iframe that will be playing the video. + + +Example of the embed code: + +