alguidelines/offline-search-index.6d13347581f2cdfa89e23f0c68949bc2.json
2022-02-21 14:46:29 +00:00

1 line
No EOL
496 KiB
JSON
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[{"body":"Business Central Design Patterns Why are Design Patterns important? Blah Blah Blah\n","categories":"","description":"AL Code Design Patterns\n","excerpt":"AL Code Design Patterns\n","ref":"/docs/patterns/","tags":"","title":"Patterns"},{"body":"Business Central Best Practices This section will be cover things that arent as simple as Design Patterns, but will help make sure your development is:\n high-performance complies with good designs has high maintainability Readability Generally, all readability rules are Microsoft style choices only. You can use them to keep consistency with the existing code.\nPerformance Some guidelines are simply better for performance considerations rather than readability or anything else. In this section, lets look into some..\n","categories":"","description":"AL Code Best Practices\n","excerpt":"AL Code Best Practices\n","ref":"/docs/bestpractices/","tags":"","title":"Best Practices"},{"body":"Business Central Design Patterns \u0026 Best Practices This site is meant to house some of the communitys knowledge about Microsoft Dynamics 365 Business Central AL Development best practices, particularly around hosting Design Patterns.\nWhat are Design Patterns? To quote the original NAV Team blog post about the NAV Design Patterns:\n A team of people interested in NAV application design has come together to work on naming and surfacing design solutions to common NAV business needs. When those solutions are generic enough to be applied in various places of the NAV application, with slight variations on implementation but mainly respecting the same base concepts, we can describe them as NAV design patterns.\n A design pattern is a repeatable template of how to solve a common development challenge.\nWhat are Development Best Practices? (more text coming soon)\nHistory of “NAV Design Patterns” In 2013, Microsoft NAV Dev Team and prominent members of the community collaborated on a Community and Microsoft collection of commonly needed / used Design Patterns.\nFor some history on this, waldos posts Code is Poetry and Design is Philosophy are a great read.\nBehind This Project This project is a Microsoft Business Central Community initiative with support from the Microsoft Business Central team. The founding community members are\n waldo (Twitter, Blog, GitHub) Arend-Jan Kauffmann (Twitter, Blog, GitHub) Henrik Helgesen (Twitter, Blog, GitHub) Jeremy Vyska (Twitter,Blog, GitHub) Contributing To find out more about contributing, read up here: Contributing\n","categories":"","description":"Patterns and Best Practices for AL Develolpment\n","excerpt":"Patterns and Best Practices for AL Develolpment\n","ref":"/docs/","tags":"","title":"AL Guidelines"},{"body":"About the archive This section of the site is a careful reproduction of the content of the Original Microsoft Community NAV Design Patterns project, created with permission.\nReading the archive Bear in mind, many of the style and formatting guidelines in this section have been brought forward into:\n The automatic formatting provided by the AL Extension The Code Analyzers Additionally, a variety of topics around the Windows Client and DotNet are outdated, and should only be used for either reference or if working in older environments.\n","categories":"","description":"","excerpt":"About the archive This section of the site is a careful reproduction …","ref":"/docs/navpatterns/","tags":"","title":"NAV Patterns Archive"},{"body":"First off, were glad you want to help! The project team is kind and helpful, so if youre not sure if you have a good first contribution, make a Discussion about it or even just create your first try. Youll get feedback and we will be happy to help refine it, if it even needs it.\nCode of Conduct This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.\nThis project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.\nSteps to Contribute Guide to Fork \u0026 PR Templates: For patterns For guidelines Understanding the Approval Process Here are some tips and tricks in terms of working with Markdown and Hugo.\n","categories":"","description":"","excerpt":"First off, were glad you want to help! The project team is kind and …","ref":"/docs/contributing/","tags":"","title":"Contributing"},{"body":"Tips and tricks in terms of working with MarkDown and Hugo Markdown Cheat Sheet Here you can find a rather interesting Cheat Sheet regarding markdown: https://www.markdownguide.org/cheat-sheet\nCode Fences / Syntax highlighting The syntax to use codefences is with backticks. If you provide the language after the first block of backticks, github will automatically put that in decent syntax highlighting. So, A simple code fence with AL code, can simply be done by:\n```AL procedure ALGuidelinesRock() var Customer: Record Customer; begin Customer.Get('10000'); Customer.Name := 'waldo'; Customer.Modify(true); end; ``` Results in:\nprocedureALGuidelinesRock() varCustomer:RecordCustomer;beginCustomer.Get('10000');Customer.Name:='waldo';Customer.Modify(true);end;Hugo Shortcodes Since were using “Hugo”, we can use its shortcode. Here is a reference: https://gohugo.io/content-management/shortcodes/\nIt basically means we are able to use easy notations to do cool things. Lets point out some useful shortcodes:\nTwitter {{\u003c tweet user=\"waldo1001\" id=\"1458787011024805892\" \u003e}} makes: \"Code is Poetry!\"#msdyn365bc\n— waldo (@waldo1001) November 11, 2021 YouTube {{\u003c youtube QVOMCYitLEc \u003e}} makes: Figure {{\u003c figure src=\"http://www.waldo.be/wp-content/uploads/2021/11/business-central-logo.png\" title=\"Business Central\" \u003e}} makes: Business Central ","categories":"","description":"","excerpt":"Tips and tricks in terms of working with MarkDown and Hugo Markdown …","ref":"/docs/contributing/formattingtips/","tags":"","title":"Formatting tips"},{"body":"Abstract AL Guidelines is a community project, and as such YOU are encouraged to submit corrections and new ideas. In order to get your content included, you must submit a pull request to the GitHub Repository (Located here: https://github.com/microsoft/alguidelines). All Pull Requests are subject to approval by a minimum of three admins.\nIf You are toying with an idea, but You arent ready to create a document just yet, you are encouraged to create a project discussion thread here: https://github.com/microsoft/alguidelines/discussions\nWarning This is a warning. If You havent worked in collaboration with “external” GitHub repositories before, please familiarize yourself with that process by visiting:\nhttps://docs.github.com/en/pull-requests/collaborating-with-pull-requests\n Steps Now that You have decided that You are ready to contribute, these are the steps to take. Note You can read more about this process here:\nhttps://docs.github.com/en/get-started/quickstart/contributing-to-projects\n Step 1: Fork In order to work on the repository, You must Fork the repository.\nBy forking the repository, You essentially create a copy into Your own account.\nStart by going to the GitHub Repository (https://github.com/microsoft/alguidelines), and press the Fork Once You have successfully forked the repository, go to your own GitHub repository : You are now able to clone your own repository to your local pc and start editing using your favorite editor. Visual Studio Code is perfectly fine for this task.\nNote You can read more about forking here:\nhttps://docs.github.com/en/get-started/quickstart/fork-a-repo\n Step 2: Branch While not necessarily a must, it is always good practice to create a branch off of your forked repository. That will allow you to work on multiple contributions at the same time and wont have to wait for pull requests to be approved before you can continue on your next contribution.\nNote You can read more about Branches here:\nhttps://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-branches\n Step 3: Pull Request Once you are happy with your contribution, its time to create a pull request to propose changes into the main project! This is the final step in producing a fork of someone elses project, and arguably the most important. If youve made a change that you feel would benefit the community as a whole, you should definitely consider contributing back.\nTo do so, head on over to the repository on GitHub where your project lives. For this example, it would be at https://www.github.com/\u003cyour_username\u003e/alguidelines. Youll see a banner indicating that your branch is one commit ahead of microsoft:main. Click Contribute and then Open a pull request.\nGitHub will bring you to a page that shows the differences between your fork and the microsoft/alguidelines repository. Click Create pull request.\nGitHub will bring you to a page where you can enter a title and a description of your changes. Its important to provide as much useful information and a rationale for why youre making this pull request in the first place. The project owners needs to be able to determine whether your change is as useful to everyone as you think it is. Finally, click Create pull request.\n","categories":"","description":"","excerpt":"Abstract AL Guidelines is a community project, and as such YOU are …","ref":"/docs/contributing/forkandpr/","tags":"","title":"Guide to Fork \u0026 PR"},{"body":"Templates We have foreseen some template-files that you can simply copy and use. Look at them as “Patterns for describing patterns” 😉.\nWe have foreseen a Template:\n for patterns for guidelines ","categories":"","description":"","excerpt":"Templates We have foreseen some template-files that you can simply …","ref":"/docs/contributing/templates/","tags":"","title":"Templates"},{"body":"(coming soon)\n","categories":"","description":"","excerpt":"(coming soon)\n","ref":"/docs/contributing/theapprovalprocess/","tags":"","title":"Understanding the Approval Process"},{"body":" Warning Please note that these patterns may not be up-to-date with the patterns for AL and Business Central Development. ","categories":["Archived Pattern"],"description":"Patterns described to be used with Microsoft Dynamics NAV\n","excerpt":"Patterns described to be used with Microsoft Dynamics NAV\n","ref":"/docs/navpatterns/patterns/","tags":["NAV","C/AL"],"title":"Patterns"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nAliases: Encapsulation, Separation of Concerns [1]\nContext: 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.\nProblem: 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.).\nForces:\n 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.\nTo 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 and Encryption.\nFigure 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:\n 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. 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 pattern). \nFigure 1- Example definition, table used for Sensitive Data Encapsulation\nLets 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).\nFigure 2 illustrates the system before and after applying the Sensitive Data Encapsulation pattern.\n 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.\n 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. \nFigure 2 - Data access before and after Sensitive Data Encapsulation.\nBenefits:\n 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:\n 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 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\n[1] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Separation_of_concerns.\n[2] “GUID Structure,” [Online]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx.\n[3] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Binary_large_object.\n[4] waldo, “How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2”.\n[5] Microsoft, “Multitenant Deployment Architecture,” Microsoft, [Online]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx.\n[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].\n[7] “Shotgun Surgery,” [Online]. Available: https://en.wikipedia.org/wiki/Shotgun_surgery. [Accessed 31 07 2016].\n[8] M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999.\n[9] “Masking out,” [Online]. Available: https://en.wikipedia.org/wiki/Data_masking#Masking_out. [Accessed 29 7 2016].\n[10] “Key Vault,” Microsoft, [Online]. Available: https://azure.microsoft.com/en-us/services/key-vault/.\n[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].\n[12] “sniffer,” [Online]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef_sniffer.htm. [Accessed 02 08 2016].\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nAliases: …","ref":"/docs/navpatterns/patterns/security/1-sensitive-data-encapsulation/","tags":"","title":"Sensitive Data Encapsulation"},{"body":"Some of the software development practices, had not stood the test of time. Despite that, some are still being used today by developers everywhere.\n“An anti-pattern (or antipattern) is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive” (from Wikipedia)\nSince 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.\nBest regards,\nBogdana Botez\n","categories":"","description":"","excerpt":"Some of the software development practices, had not stood the test of …","ref":"/docs/navpatterns/2-anti-patterns/","tags":"","title":"2. Anti-Patterns"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: After applying Sensitive Data Encapsulation, all sensitive data is gathered in a known place in the database. This makes it possible to apply further protection best practices.\nProblem: If any non-authorized actor manages to get access to a copy of the database, the sensitive data is immediately available in clear-text.\nForces:\n 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.\nFigure 1 adds one more step (in continuation of the figure in pattern Sensitive Data Encapsulation), 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.\n\nFigure 1- Encryption becomes easier after first applying Sensitive Data Encapsulation.\nUsage: in Dynamics NAV, codeunit 1266 Encryption Management offers an API for encryption of data. The available functionality is described in Table 1.\nTable 1- Encryption functionality in Dynamics NAV (found in codeunit 1266 Encryption Management)\n 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\nIdeally, encryption should be enabled by default.\nHowever, 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).\nTo 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 theres 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:\nEncryptionIsNotActivatedQst@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?';LOCALPROCEDURECheckEncryption@6();BEGINIFNOTENCRYPTIONENABLEDTHENIFCONFIRM(EncryptionIsNotActivatedQst) THENPAGE.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.\n\nFigure 2- The administrator is advised to enable encryption.\nNow 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).\n\nFigure 3- Data Encryption Management page\nStan can now choose “Enable Encryption” from the ribbon which informs him that an encryption key will be created (Figure 4).\n\nFigure 4- The administrator is encouraged to save a copy of the encryption key.\nStan has the option to save the encryption key in a safe location. He invokes the action Enable Encryption and is guided forward (Figure 5).\n\nFigure 5- The encryption key needs to be protected by a password.\nStan 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).\n\nFigure 6- The administrator chooses a strong password.\nIn 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.).\nNAV Usages. Encryption examples can be found in NAV in the following places:\n Page 1260 Bank Data Conv. Service Setup Page 1270 OCR Service Setup Page 5330 CRM Connection Setup Table 1275 Doc. Exch. Service Setup Benefits:\n 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:\n 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 \u003caction\u003eENCRYPTIONKEY), 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 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\n[1] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Separation_of_concerns.\n[2] “GUID Structure,” [Online]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx.\n[3] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Binary_large_object.\n[4] waldo, “How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2”.\n[5] Microsoft, “Multitenant Deployment Architecture,” Microsoft, [Online]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx.\n[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].\n[7] “Shotgun Surgery,” [Online]. Available: https://en.wikipedia.org/wiki/Shotgun_surgery. [Accessed 31 07 2016].\n[8] M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999.\n[9] “Masking out,” [Online]. Available: https://en.wikipedia.org/wiki/Data_masking#Masking_out. [Accessed 29 7 2016].\n[10] “Key Vault,” Microsoft, [Online]. Available: https://azure.microsoft.com/en-us/services/key-vault/.\n[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].\n[12] “sniffer,” [Online]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef_sniffer.htm. [Accessed 02 08 2016].\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: …","ref":"/docs/navpatterns/patterns/security/2-data-encryption/","tags":"","title":"Data Encryption"},{"body":"Weve 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).\nYou can also download the C/AL coding guidelines as pdf, 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 for this idea and for helping out.\nThe 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.\nFor 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.\nQuestion: Since were having the guidelines, how come there is still C/AL code in NAV which doesnt respect them?\nAnswer: 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 were gradually improving the old code base as we visit various objects in order to add new functionality, however chances are that code we didnt touch in a long time had remained in its old form.\nWere looking forward to your comments. Where you can, do provide concrete examples of the alternatives, Good and Bad.\n ","categories":"","description":"","excerpt":"Weve decided to publish our current C/AL coding guidelines. They are …","ref":"/docs/navpatterns/3-cal-coding-guidelines/","tags":"","title":"3. CAL Coding Guidelines"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: Protected data needs to be used. There are many types of entities which might attempt to use the data.\nProblem: 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.\nForces:\n 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 users 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, 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.\nIn Figure 9 (figure numbering is continued from pattern Encryption), the panels 1, 2 and 3 have applied the Sensitive Data Encapsulation and Encryption 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.\nYou 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.\n\nFigure 1- Single Point of Access pattern applied.\nThis 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.\nUsage: call the procedures available in codeunit 1266 Encryption Management to store and access sensitive data.\nBenefits:\n 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:\n Single point of failure: A defect in the access library will affect all usages until it is found and fixed. References\n[1] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Separation_of_concerns.\n[2] “GUID Structure,” [Online]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx.\n[3] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Binary_large_object.\n[4] waldo, “How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2”.\n[5] Microsoft, “Multitenant Deployment Architecture,” Microsoft, [Online]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx.\n[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].\n[7] “Shotgun Surgery,” [Online]. Available: https://en.wikipedia.org/wiki/Shotgun_surgery. [Accessed 31 07 2016].\n[8] M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999.\n[9] “Masking out,” [Online]. Available: https://en.wikipedia.org/wiki/Data_masking#Masking_out. [Accessed 29 7 2016].\n[10] “Key Vault,” Microsoft, [Online]. Available: https://azure.microsoft.com/en-us/services/key-vault/.\n[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].\n[12] “sniffer,” [Online]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef_sniffer.htm. [Accessed 02 08 2016].\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: …","ref":"/docs/navpatterns/patterns/security/3-single-point-of-access/","tags":"","title":"Single Point of Access"},{"body":"Reminder, this is an ARCHIVE of the Patterns site, this information is not current. Spread the info\nNAV 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, Setup Table and definitely Hooks which will be a great investment in reducing your upgrade time. The more experienced developers can read directly the newer patterns, like Surrogate Key, Easy Update, Totals on Subpages, Using Queries instead of nested loops etc.\nBecome a NAV Design Pattern author\nYou have a pattern that you have used successfully? You have ideas on new patterns? Youve 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?\nSend your pattern idea to Bogdana Botez 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 dont have moderation capabilities yet, so we count on each author to only make meaningful/agreed changes).\nYou and your company also get credit by being mentioned on the pattern and also on our patterns authors page.\nOnce you have the idea, writing it down shouldnt take long. You will be helped by adopting the template that weve used.\nRemember the rules\nWhen 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, and we will review and update it.\nWe 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.\n","categories":"","description":"","excerpt":"Reminder, this is an ARCHIVE of the Patterns site, this information is …","ref":"/docs/navpatterns/4-get-involved/","tags":"","title":"(OLD) Get Involved"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nAliases: Masking out\nContext: 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.\nProblem: 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.\nForces:\n 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.\nUsage: 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.\n\nFigure 1 - The field “Password” is masked.\nTo apply this pattern in Dynamics NAV, the developer has two choices:\n 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 fields property ExtendedDatatype=Masked.\nMask 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.\nBenefits:\n 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:\n “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 users permissions and if permitted, show or send the clear-text value to the user who requested it. References\n[1] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Separation_of_concerns.\n[2] “GUID Structure,” [Online]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx.\n[3] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Binary_large_object.\n[4] waldo, “How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2”.\n[5] Microsoft, “Multitenant Deployment Architecture,” Microsoft, [Online]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx.\n[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].\n[7] “Shotgun Surgery,” [Online]. Available: https://en.wikipedia.org/wiki/Shotgun_surgery. [Accessed 31 07 2016].\n[8] M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999.\n[9] “Masking out,” [Online]. Available: https://en.wikipedia.org/wiki/Data_masking#Masking_out. [Accessed 29 7 2016].\n[10] “Key Vault,” Microsoft, [Online]. Available: https://azure.microsoft.com/en-us/services/key-vault/.\n[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].\n[12] “sniffer,” [Online]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef_sniffer.htm. [Accessed 02 08 2016].\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nAliases: …","ref":"/docs/navpatterns/patterns/security/4-masked-text/","tags":"","title":"Masked Text"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: 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. Microsofts 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.\nProblem: 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.\nForces:\n 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?\nSolution: To protect the data before it reaches the server, remember to configure SSL (Secure Sockets Layer) in Dynamics NAV.\nSSL 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.\nFigure 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 users data. Sniffing the traffic would capture the encrypted stream, but access to the real content would be impeded by encryption.\n\nFigure 1 - Data transmission before (http://…) and after SSL encryption (https://…).\nUsage: 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.\nBenefits:\n 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:\n 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 Microsofts cloud NAV solution has SSL by default and no extra work is required from the developer on that aspect. References\n[1] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Separation_of_concerns.\n[2] “GUID Structure,” [Online]. Available: https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx.\n[3] “Wikipedia,” [Online]. Available: https://en.wikipedia.org/wiki/Binary_large_object.\n[4] waldo, “How Do I: Manage Companies in Microsoft Dynamics NAV 2013 R2”.\n[5] Microsoft, “Multitenant Deployment Architecture,” Microsoft, [Online]. Available: https://msdn.microsoft.com/en-us/library/dn271675(v=nav.90).aspx.\n[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].\n[7] “Shotgun Surgery,” [Online]. Available: https://en.wikipedia.org/wiki/Shotgun_surgery. [Accessed 31 07 2016].\n[8] M. Fowler, Refactoring: Improving the design of existing code, Addison Wesley, 1999.\n[9] “Masking out,” [Online]. Available: https://en.wikipedia.org/wiki/Data_masking#Masking_out. [Accessed 29 7 2016].\n[10] “Key Vault,” Microsoft, [Online]. Available: https://azure.microsoft.com/en-us/services/key-vault/.\n[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].\n[12] “sniffer,” [Online]. Available: http://compnetworking.about.com/od/networksecurityprivacy/g/bldef_sniffer.htm. [Accessed 02 08 2016].\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: …","ref":"/docs/navpatterns/patterns/security/5-ssl-in-nav/","tags":"","title":"SSL in NAV"},{"body":"All actions must have an image assigned to them.\nBad code\n{7;1;Action;CaptionML=ENU=Customer-\u0026Balance;RunObject=Report121}Good code\n{7;1;Action;CaptionML=ENU=Customer-\u0026Balance;RunObject=Report121}Image=Report}","categories":"","description":"","excerpt":"All actions must have an image assigned to them.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/ux/actions-images/","tags":"","title":"Actions - Images"},{"body":"Discussions We enabled the “Discussions” forum on the github-page of our repository for you to discuss anything “Design Pattern” or “Best Practices” related.\nYou can find the discussions here: https://github.com/microsoft/alguidelines/discussions.\nFeel free to browse through them, find certain topics and/or participate in the discussions!\nCreate your own discussion You are obviously also free to start a new discussion. You can simply do that by using the “New Discussion” button on the top right.\nOr use this link: https://github.com/microsoft/alguidelines/discussions/new?category=bc-patterns\n","categories":"","description":"","excerpt":"Discussions We enabled the “Discussions” forum on the github-page of …","ref":"/discussions/","tags":"","title":"Discussions"},{"body":"Originally by Ciprian Iordache at Microsoft Development Center Copenhagen\nActivity Log Abstract\nThe Activity Log pattern tracks execution of activities. This is a Dynamics NAV specific implementation of the Audit Log pattern.\n\nProblem\nIn 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.\nSimilar 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.\nIn all these cases, we need to be able to troubleshoot.\nA 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.\nIn 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.\nSolution\nThe 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.\nActivity Log pattern\n 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.\n\nThis 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:\nActivityLog.LogActivity(ContextRecordID,ActivityLog.Status::Failed,ContextDescription,ActivityDescription,ActivityMessage);\nSimilar 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.\nThe following parameters should be provided to the function:\n 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 “\u003cprefix\u003e Log” and link it to the image named “Log”:\n{;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=VARActivityLog@1000:Record710;BEGINActivityLog.ShowEntries(RECORDID);END;}NAV usages\nIn 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 whats 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.\nSo as usages in NAV 2016, we have the document exchange and OCR features plus the related posted documents involved in the document exchange feature.\n COD1294.TXT COD1410.TXT PAG1270.TXT PAG1275.TXT PAG143.TXT PAG144.TXT PAG189.TXT TAB112.TXT TAB114.TXT TAB130.TXT Ideas for improvement\nReplace the scattered similar functionality (as mentioned above, we have several places having close functionality or similar requirements) with this new pattern.\nConsequences\n 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\nSupported from NAV 2016\nRelated Topics\nError 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.\nAudit Log as mentioned in the beginning, this pattern is a NAV specific implementation of the audit log pattern.\n","categories":"","description":"","excerpt":"Originally by Ciprian Iordache at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/activity-log/","tags":"","title":"Activity Logs"},{"body":"Originally By Nikola Kukrika and waldo\nAbstract 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).\n\nProblem In CAL overloading function signature is not supported. It is also not possible to provide default values for the function arguments.\nWhen 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.\nSecond commonly occurring problem is option duplication. In order to pass options often they are duplicated in the signature.\nThe 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.\nFew examples of the bad implementations are as illustrated here:\nBad example 1 PROCEDUREFillInVATReturnData@1200001(VARDeclarationID@1200000:Code[20];VARLineID@1200001:Code[20];VARPeerID@1200002:Code[20];VARDocumentNo@1200003:Code[20];VARNumberOfCopies@1200007:Integer;VARUploaded@1200004:Boolean;VARCorrection@1200005:Boolean;VARHasValidationErr@1200006:Boolean);Call\nFillInVATReturnData(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.\nBad example 2 LOCALPROCEDUREGetTableSyncSetupW1@3(OldTableId@1002:Integer;VARUpgradeTableId@1001:Integer;VARTableUpgradeMode@1000:'Check, Copy, Move, Force') :Boolean;BEGINCASEOldTableIdOFDATABASE::\"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);ELSEEXIT(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.\nSolution 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.\nMultiple parameters are grouped within the single object with a meaningful name so the code becomes more readable.\nIt is possible to assign default values and to have the code validation.\nArgument table should preferably be a temporary table since the implementation is simpler.\nThe examples of usages addressing problems shown above are:\nGood example 1 New table\nTAB50003VATReturnDataPROCEDUREFillInVATReturnData@1200001(VARVATReturnData@1200000:Record50003);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.\nGood example 2 Good example\nPROCEDUREGetTableSyncSetupW1@3(VARTableSynchSetup@1000:Record2000000135);BEGINSetTableSyncSetup(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.\nDownsides You need to create one more table\nComplex types cant be embedded as fields in tables (cannot have a record field type etc).\nNAV Usages Upgrade Codeunits\nRelated Patterns Posting Routine, Select behavior: Setting fields on existing records in order not to change the signatures.\n","categories":"","description":"","excerpt":"Originally By Nikola Kukrika and waldo\nAbstract The Argument Table …","ref":"/docs/navpatterns/patterns/argument-table/","tags":"","title":"Argument Table"},{"body":"When BEGIN follows THEN, ELSE, DO, it should be on the same line, preceded by one space character.\nBad code\nIFICPartnerRefType=ICPartnerRefType::\"Common Item No.\"THENBEGIN... END;Good code\nIF ICPartnerRefType = ICPartnerRefType::\"Common Item No.\" THEN BEGIN ... END; ","categories":"","description":"","excerpt":"When BEGIN follows THEN, ELSE, DO, it should be on the same line, …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/begin-as-an-afterword/","tags":"","title":"Begin as an 'After Word'"},{"body":"Only use BEGIN..END to enclose compound statements.\nBad code\nIFFINDSETTHENBEGINREPEAT... UNTILNEXT=0;END;Good code\nIFFINDSETTHENREPEAT... UNTILNEXT=0;Bad code\nIFIsAssemblyOutputLineTHENBEGINTESTFIELD(\"Order Line No.\",0);END;Good code\nIFIsAssemblyOutputLineTHENTESTFIELD(\"Order Line No.\",0);Bad code\nIFFINDSETTHENREPEATBEGIN... END;UNTILNEXT=0;Good code\nIFFINDSETTHENREPEAT... UNTILNEXT=0;Exception\n// Except for this case IFXTHENBEGINIFYTHENDOSOMETHING;ENDELSE(notX) ","categories":"","description":"","excerpt":"Only use BEGIN..END to enclose compound statements.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/begin-end/","tags":"","title":"Begin-End - Compound Only"},{"body":"Do not start a line with a binary operator.\nBad code\n\"Quantity to Ship\":=Quantity-\"Quantity Shipped\"Good code\n\"Quantity to Ship\":=Quantity-\"Quantity Shipped\"","categories":"","description":"","excerpt":"Do not start a line with a binary operator.\nBad code\n\"Quantity to …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/binary-operator-line-start/","tags":"","title":"Binary Operator to Start Line"},{"body":"Do not use blank lines at the beginning or end of any functions, after BEGIN, before END, or inside multiline expressions.\nBad code\nPROCEDUREMATRIX_OnDrillDown@1133(MATRIX_ColumnOrdinal:Integer);BEGINSetupDrillDownCol(MATRIX_ColumnOrdinal);DrillDown(FALSE,ValueType);END;Good code\nPROCEDUREMATRIX_OnDrillDown@1133(MATRIX_ColumnOrdinal:Integer);BEGINSetupDrillDownCol(MATRIX_ColumnOrdinal);DrillDown(FALSE,ValueType);END;Bad code\nIFNameIsValidANDName2IsValidTHENGood code\nIFNameIsValidANDName2IsValidTHEN","categories":"","description":"","excerpt":"Do not use blank lines at the beginning or end of any functions, after …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/blank-lines/","tags":"","title":"Blank Lines"},{"body":"Originally by Abhishek Ghosh at Microsoft Development Center Copenhagen\nAbstract The Blocked Entity is used when it is required to stop transactions for an entity (mostly master data), temporarily or permanently.\n\nDescription To block entities through metadata, read this pattern. To do the same thing through data, read Data Driven Blocked Entity pattern.\nThe 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.\nAn 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.\nIn 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.\nA 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.\nIn 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 customers 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.\nUsage 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.\nBoolean Implementation Add a Boolean field named Blocked in the table.\nIn the relevant logic, add a condition to check the status of the Blocked flag. The cheapest way is to use a TESTFIELD:\n\u003crecvariable\\\u003e.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.\nOption-Field Implementation Add an option field named Blocked in the table. The option values will reflect the different blocked states required by the company.\nAdd 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.\nImplement 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.\nNote: 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.\nHow 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 doesnt 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.\nA 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.\nNAV Specific Example Boolean Implementation \nAn example of the Boolean implementation on the Item card.\nIn codeunit 22 Item Jnl.-Post Line, the following lines of code have implemented a check based on the value of the Blocked field:\nIFNOTCalledFromAdjustmentTHENItem.TESTFIELD(Blocked,FALSE);Option-Field Implementation \nAn example of the option field implementation on the Customer card.\nThe 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.\nNAV Usages Entities where the Blocked Entity has been implemented include:\n Item G/L Account Customer Vendor Bin Related Topics The Released Entity.\n ","categories":"","description":"","excerpt":"Originally by Abhishek Ghosh at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/blocked-entity/","tags":"","title":"Blocked Entity"},{"body":"Do not declare parameters by reference if their values are not intended to be changed.\nUnintentional value changes might propagate. Also, it might lead people to believe that value changes are intended.\nBad code\nLOCAL PROCEDURE ShowMessage@15(VAR Text@1000 : Text[250]); BEGIN Text := GetMessageText; IF (Text \u003c\u003e '') AND GenJnlLineInserted THEN MESSAGE(Text); END; Good code\nLOCAL PROCEDURE ShowMessage@15(Text@1000 : Text[250]); BEGIN Text := GetMessageText; IF (Text \u003c\u003e '') AND GenJnlLineInserted THEN MESSAGE(Text); END; ","categories":"","description":"","excerpt":"Do not declare parameters by reference if their values are not …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/by-reference-parameters/","tags":"","title":"By Reference Parameters"},{"body":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen\nAbstract In a service-oriented deployment, web services are used to extend NAVs 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).\nDescription 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.\n 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.\nDiagram \nUsage 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.\nNAV 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.\nIf 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\nCode Sample OnInit=BEGINShortTimeout:=5000;LongTimeout:=30000;END;OnOpenPage=VARBankDataConvBank@1002:Record1259;ImpBankListExtDataHndl@1000:Codeunit1289;CountryRegionCode@1004:Text;HideErrors@1003:Boolean;BEGINCountryRegionCode:=IdentifyCountryRegionCode(Rec,GETFILTER(\"Country/Region Code\"));IFBankDataConvBank.ISEMPTYTHENBEGINImpBankListExtDataHndl.GetBankListFromConversionService(HideErrors,CountryRegionCode,ShortTimeout);EXIT;END;RefreshBankNamesOlderThanToday(CountryRegionCode,HideErrors,ShortTimeout);END;OnAction=VARImpBankListExtDataHndl@1000:Codeunit1289;FilterNotUsed@1001:Text;ShowErrors@1003:Boolean;BEGINShowErrors:=TRUE;ImpBankListExtDataHndl.GetBankListFromConversionService(ShowErrors,FilterNotUsed,LongTimeout);END;LOCALPROCEDUREIdentifyCountryRegionCode@1(VARBankDataConvBank@1002:Record1259;Filter@1000:Text) :Text;VARCompanyInformation@1001:Record79;BlankFilter@1003:Text;BEGINBlankFilter:='''''';IFFilter=BlankFilterTHENBEGINCompanyInformation.GET;BankDataConvBank.SETFILTER(\"Country/Region Code\",CompanyInformation.\"Country/Region Code\");EXIT(BankDataConvBank.GETFILTER(\"Country/Region Code\"));END;EXIT(Filter);END;LOCALPROCEDURERefreshBankNamesOlderThanToday@5(CountryRegionCode@1000:Text;ShowErrors@1002:Boolean;Timeout@1004:Integer);VARBankDataConvBank@1001:Record1259;ImpBankListExtDataHndl@1003:Codeunit1289;BEGINIFCountryRegionCode\u003c\u003e''THENBankDataConvBank.SETFILTER(\"Country/Region Code\",CountryRegionCode);BankDataConvBank.SETFILTER(\"Last Update Date\",'\u003c%1',TODAY);IFBankDataConvBank.FINDFIRSTTHENImpBankListExtDataHndl.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.\nIdeas for Improvement Expose the refresh rate through a setup table to make it easily configurable without changing the code.\n","categories":"","description":"","excerpt":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/cached-web-service-calls/","tags":"","title":"Cached Web Server Calls"},{"body":"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.\nBad code\n... { 2 ;2 ;Field ; SourceExpr=Name } ... OBJECT Table 2000000000 User ... { 2 ; ;Name ;Text50 } Good code\n... { 2 ;2 ;Field ; CaptionML=ENU=Name; SourceExpr=Name } ... OBJECT Table 2000000000 User ... { 2 ; ;Name ;Text50 } ","categories":"","description":"","excerpt":"CaptionML should always be specified on a page field for a system …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/captionml-for-system-tables/","tags":"","title":"CaptionML on System Pages"},{"body":"A CASE action should start on a line after the possibility.\nBad code\nCASELetterOF'A':Letter2:='10';'B':Letter2:='11';Good code\nCASELetterOF'A':Letter2:='10';'B':Letter2:='11';","categories":"","description":"","excerpt":"A CASE action should start on a line after the possibility.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/case-actions/","tags":"","title":"CASE Action"},{"body":"Do not write functions that have high class coupling. This makes the code hard to maintain.\nBad code\nAny procedure / trigger that has class coupling of \u003e 30 Good code\nAny procedure / trigger that has class coupling of \u003c= 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\\. ","categories":"","description":"","excerpt":"Do not write functions that have high class coupling. This makes the …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/class-coupling/","tags":"","title":"Class Coupling"},{"body":"Find below the rules to be used when disseminating or relating to the NAV Design Patterns.\n 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. 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. 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. 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. 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. If you do choose to use your own content, you must make it clear that it is not a NAV Design Pattern. ","categories":"","description":"","excerpt":"Find below the rules to be used when disseminating or relating to the …","ref":"/docs/navpatterns/4-get-involved/code-of-conduct/","tags":"","title":"Code of Conduct"},{"body":"The last possibility on a CASE statement must be immediately followed by a colon.\nBad code\nCASEDimOptionOFDimOption::\"Global Dimension 1\":DimValue.\"Dimension Code\":=GLSetup.\"Global Dimension 1 Code\";Good code\nCASEDimOptionOFDimOption::\"Global Dimension 1\":DimValue.\"Dimension Code\":=GLSetup.\"Global Dimension 1 Code\";","categories":"","description":"","excerpt":"The last possibility on a CASE statement must be immediately followed …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/colon-usage-in-case/","tags":"","title":"Colon usage in CASE"},{"body":"Never use curly bracket comments. During development, the “Block comment” functionality can be used instead. However, in production code, block comments are not recommended.\nBad code\nPeriodTxt:{Period}Good code\nPeriodTxt:// Period Bad code\nPROCEDUREMATRIX_OnAfterGetRecord@10(MATRIX_ColumnOrdinal:Integer);BEGIN{IFShowColumnNameTHENMatrixHeader:=MatrixRecords[MATRIX_ColumnOrdinal].NameELSEMatrixHeader:=MatrixRecords[MATRIX_ColumnOrdinal].Code;}MatrixRecord:=MatrixRecords[MATRIX_ColumnOrdinal];AnalysisValue:=CalcAmt(ValueType,TRUE);MATRIX_CellData[MATRIX_ColumnOrdinal]:=AnalysisValue;END;Good code\nPROCEDUREMATRIX_OnAfterGetRecord@10(MATRIX_ColumnOrdinal:Integer);BEGINMatrixRecord:=MatrixRecords[MATRIX_ColumnOrdinal];AnalysisValue:=CalcAmt(ValueType,TRUE);MATRIX_CellData[MATRIX_ColumnOrdinal]:=AnalysisValue;END;","categories":"","description":"","excerpt":"Never use curly bracket comments. During development, the “Block …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/comments-curly-brackets/","tags":"","title":"Comments inside Curly Brackets"},{"body":"Always start comments with // followed by one space character.\nBad code\nRowNo+=1000;//Move way below the budget Good code\nRowNo+=1000;// Move way below the budget ","categories":"","description":"","excerpt":"Always start comments with // followed by one space character.\nBad …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/comments-spacing/","tags":"","title":"Comment Spacing"},{"body":"Originally by Jan Hoek at IDYN\nAbstract 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”.\nDescription The value of one table field sometimes depends on the value of another field, typically following an application-defined transformation (note that were 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.\nIf 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 fields value.\nUsage 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 fields previous contents. If it is, populate the target fields value with the transformed source field value. If it is not, do nothing (effectively preserving the value set by the user).\nNAV 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.\n\nIn 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.\nConsequences 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 wont be any user-overridden values to protect.\n","categories":"","description":"","excerpt":"Originally by Jan Hoek at IDYN\nAbstract The Conditional Cascading …","ref":"/docs/navpatterns/patterns/conditional-cascading-update/","tags":"","title":"Conditional Cascading Update"},{"body":"Always end CONFIRM with a question mark.\nBad code\nChangeAllOpenedEntriesQst@1000:TextConst'ENU=Do you want to change all open entries for every customer and vendor that are not blocked';... IFCONFIRM(ChangeAllOpenedEntriesQst,TRUE) THENGood code\nChangeAllOpenedEntriesQst@1000:TextConst'ENU=Do you want to change all open entries for every customer and vendor that are not blocked?';... IFCONFIRM(ChangeAllOpenedEntriesQst,TRUE) THEN","categories":"","description":"","excerpt":"Always end CONFIRM with a question mark.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/ux/confirm/","tags":"","title":"CONFIRM"},{"body":"By Bogdan Sturzoiu at Microsoft Development Center Copenhagen\nAbstract 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.\nDescription 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.\nOther 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.\nFor these reasons, NAV supports the copying of documents as a method to re-use or link documents.\nThe Copy Document functionality is used in the following situations:\n 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\n 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:\n 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:\n Source document tables for document header and line. For example,Sales Header/Line.\n Destination document tables for document header and line.\nNote: 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.\n Copy Document engine: COD6620, Copy Document Mgt.\n Copy Document report for a specific document type. The report requires the following parameters:\n Source Document Type Source Document No. Include Header (optional) Recalculate Lines (optional) Example: REP901, Copy Assembly Document\n\nUsage Sequence Precondition: The user creates a new destination document Header, filling up the required information.\nStep 1: The user runs the Copy Document report (element no. 4), filling up the parameters:\n 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).\nPost processing: The user performs additional editing of the destination document.\nThe sequence flow of the pattern is described in the following diagram.\n\nExample: Copy Sales Document for Credit Memos.\nIn 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.\n Precondition: The user enters data in PAGE44, Sales Credit Memo.\n\nStep 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.\n\nStep 2: The Sales Credit Memo window is populated with information from the source sales document.\n\nPost processing: The user can now do additional editing of the sales credit memo.\nNAV Implementations Copy Sales Document (REP292) Copy Purchase Document (REP492) Copy Service Document (REP5979) Copy Assembly Document (REP901) ","categories":"","description":"","excerpt":"By Bogdan Sturzoiu at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/copy-document/","tags":"","title":"Copy Document"},{"body":"Originally by Nikola Kukrika at Microsoft Development Center Copenhagen\nAbstract 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.\nWe 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.\nDescription 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.\nIn 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.\nThe pattern consists of two parts:\n1. Using templates to create new records or applying templates to existing records\n2. Defining and updating existing templates\nUsage \nUsing the patterns involves three steps.\n 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.\n 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).\n Config. Template Lines records reference one Config. Template Header record (lines pattern). The lines can be of type:\n 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.\nTo 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.\nAny 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.\nAfter 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):\n// 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):\nFUNCTIONInsertDimensionsFromTemplates(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.CodeIFConfigTemplateLine.FINDSETTHENREPEATConfigTemplateHeader.GET(ConfigTemplateLine.\"Template Code\");// Ensure that the table where the template belongs to is Dimensions // We could have other related templates IFConfigTemplateHeader.\"Table ID\"=DATABASE::\"Default Dimension\"THENInsertDimensionFromTemplate(ConfigTemplateHeader,MasterRecordNo,TableID);UNTILConfigTemplateLine.NEXT=0;// Create a new Dimensions Record and link it to the Master Record FUNCTIONInsertDimensionFromTemplate(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:\n Recommended - Implement a separate action called New from Template. Optional - Implement the apply template function on the document itself. This is especially good in scenarios where users are allowed to change the template. 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.\nTo view or edit templates, you have two options:\n 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.\n\n2. Implement custom pages resembling the document.\nThis 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.\nExample of the Customer Template page:\n\nThe goals of this solution were:\n 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).\nThe 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:\n 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.\nTo further enhance the usability, we have provided the following additional functionality:\n 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:\nThe user opens the Customers List window and selects New\n\nFrom 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.\n\nFrom 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:\n\nNAV Usages This pattern is used in Microsoft Dynamics C5 2014 in the following objects:\n Temporary template tables:\n Mini Customer Template table (1300) Mini Item Template table (1301) Mini Dimensions Template table(1302) Mini Vendor Template table (1303) Pages to define templates:\n 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:\n 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:\n 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.\nIt 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.\n ","categories":"","description":"","excerpt":"Originally by Nikola Kukrika at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/create-data-from-templates/","tags":"","title":"Create Data from Templates"},{"body":"By Mike Borg Cardona and Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract This article illustrates NAV platform functionality to be used by C/AL developers.\nThe 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.\nDescription Ever had to construct win client URLs like the one below?\ndynamicsnav://myserver:7046/myInstance/myCompany/runpage?page=26\nToday, 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?\nThe good news is that GETURL has been introduced to handle all URL building for you.\nGETURL automatically handles:\n Multitenancy Correct URL format for each client Publicly accessible hostnames. Usage The format is:\n[String :=] GETURL(ClientType[, Company][, Object Type][, Object Id][, Record])\nWhere:\n 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.\nThe 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 “\u0026tenant=MyTenant” to the URL.\nWhen 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.\n 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:\n 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\u0026bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=26\u0026bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,27,record) List Page https://navwebsrvr:443/DynamicsNAV71_Instance1/Webclient?company=CRONUS\u0026page=27\u0026bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page https://navwebsrvr:443/DynamicsNAV71_Instance1/Webclient?company=CRONUS\u0026page=26\u0026bookmark=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\u0026page=27 GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Report,6) https://navwebsrvr:443/DynamicsNAV71_Instance1/Webclient?company=CRONUS\u0026report=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.\n 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:\n\nThis resulting UI looks as follows.\n\nThe 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.\n","categories":"","description":"","excerpt":"By Mike Borg Cardona and Bogdana Botez at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/create-urls-to-nav-clients/","tags":"","title":"Create URLs to NAV Clients"},{"body":"Originally by Nikola Kukrika at Microsoft Development Center Copenhagen\nAbstract The goal of this solution is to enable you to:\n Use charts in the web client. 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.\nThe 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.\n\nExample of the same chart in the win client:\n\nThe 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).\nImplementation Overview \nAdd-in Buffer Table This table is used to encapsulate the logic of the Business Chart Add-in. The table handles the following logic:\n 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.\nCardPart page The CardPart page hosts the Business Chart add-in and must use the add-in buffer table as a source table.\nOn the page, you must implement the following triggers:\n 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.\nThe most commonly used actions are:\n 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.\nTo do this, you need the following:\n 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:\n\nOptional: 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.\nSee, 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).\n\nUsage To implement the pattern, create a new ChartPart and set the source table to Business Chart Buffer.\nAdd a field named BusinessChart and set the ControlAddIn property to Microsoft.Dynamics.Nav.Client.BusinessChart.\nThen 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.\nIf you need a setup record and codeunit, then it is a good idea to encapsulate this logic within a method.\nNAV Specific Example 1 Implementation of the Finance Performance Chart page (762)\nBusinessChart::AddInReady() UpdateChart(Period::\" \");LOCALUpdateChart(Period:',Next,Previous') MoveAndUpdateChart(Period,0);LOCALMoveAndUpdateChart(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.\nThe following code is used to implement DataPointClicked\nBusinessChart::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.\nThe DataPointDoubleClicked trigger has the same implementation logic as the DataPointClicked trigger.\nNAV Specific Example 2 Implementation of chart part 1390 on the Small Business Role Center page (9022)\n\nThis 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.\n\nOn 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.\nUsers can also change the period length.\n\nChoosing the Chart Information button opens a short description of the chart.\n\nNAV Usages Implementation of multiple charts within a single part:\n Page 1390, Mini Generic Chart Charts that use a setup record and select the chart with Customize Chart Setup pages:\n 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:\n Page 768, Aged Acc. Receivable Chart Other implementations:\n 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.\nWe should investigate if we could make generic code for selecting periods and other common functionality by using RecordRefs.\nAdd-In improvements Different ways to visualize the data and to pick colors for categories.\nAs a nice-to-have feature, we could implement functionality to cycle through the charts with a timer.\n","categories":"","description":"","excerpt":"Originally by Nikola Kukrika at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/creating-custom-charts/","tags":"","title":"Creating Custom Charts"},{"body":"By Nikolai LEstrange, from TVision Technology Ltd. in the UK\nAbstract Track things that happen in other NAV Sessions.\n\nProblem 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.\nA 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.\nSolution There is a common pattern in many other languages called Publish-Subscribe (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.\nThe pattern has four components:\n 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 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).\nBelow are the table definitions:\n 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.\nThe 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.\nNote: 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.\nOur 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.\nListen(TableID:Integer) WITHObserverDOBEGIN\"Table ID\":=TableID;\"Server ID\":=SERVICEINSTANCEID;\"Session ID\":=SESSIONID;INSERT(TRUE);COMMIT;END;StopListening(TableID:Integer) WITHObserverDOBEGINRESET;SETRANGE(\"Server ID\",SERVICEINSTANCEID);SETRANGE(\"Session ID\",SESSIONID);SETRANGE(\"Table ID\",TableID);DELETEALL(TRUE);COMMIT;END;NotifyAll(ChangeNotification:Record\"Change Notification\") WITHObserverDOBEGINRESET;SETRANGE(\"Table ID\",ChangeNotification.\"Table ID\");IFFINDSETTHENREPEATNotify(Observer,ChangeNotification);UNTILNEXT=0;END;Notify(Observer:Record\"Change Observer\";ChangeNotification:Record\"Change Notification\") WITHChangeNotificationDOBEGIN\"Server ID\":=Observer.\"Server ID\";\"Session ID\":=Observer.\"Session ID\";\"Entry No.\":=0;INSERT;END;Poll(TableID:Integer;VARTempChangeNotification:TEMPORARYRecord\"Change Notification\") WITHChangeNotificationDOBEGINTempChangeNotification.RESET;TempChangeNotification.DELETEALL;RESET;SETRANGE(\"Table ID\",TableID);SETRANGE(\"Server ID\",SERVICEINSTANCEID);SETRANGE(\"Session ID\",SESSIONID);IFFINDSETTHENREPEATTempChangeNotification:=ChangeNotification;TempChangeNotification.INSERT;MARK(TRUE);UNTILNEXT=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:\nOnQueryClosePage(CloseAction:ActionNone) :BooleanObserverMgt.StopListening(DATABASE::\"NAV Whiteboard Booking\");Timer::AddInReady() IFObserverMgt.Listen(DATABASE::\"NAV Whiteboard Booking\") THENCurrPage.Timer.Ping(1000);Timer::Pong() CallUpdate;CurrPage.Timer.Ping(1000);LOCALCallUpdate() ObserverMgt.Poll(DATABASE::\"NAV Whiteboard Booking\",TempChangeNotification);WITHTempChangeNotificationDOBEGINIFFINDSETTHENREPEATIF\"Type of Change\"=\"Type of Change\"::DeleteTHENBEGIN... ENDELSEIFRecRef.GET(\"Record ID\") THENBEGIN... END;UNTILNEXT=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”.\nRelated Topics This pattern was originally described in the following blog:\nhttps://geeknikolai.wordpress.com/2015/10/30/pubsub-pattern-in-dynamics-nav-2016/\nBelow is the Wikipedia link to the PubSub pattern\nhttps://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern\n","categories":"","description":"","excerpt":"By Nikolai LEstrange, from TVision Technology Ltd. in the UK\nAbstract …","ref":"/docs/navpatterns/patterns/cross-session-events/","tags":"","title":"Cross Session Events"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nCues are the second usual application of the Singleton Table pattern in Dynamics NAV, after Setup Tables.\nContext: The user gets overview information about the business on the Dynamics NAV Role Center page.\nFigure 1 - Cue information in Dynamics NAV shows cue information seen by the user on the Sales Order Processor role center.\n\nThe 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.\nProblem: 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.\nSolution: Store overview information in a singleton table.\nThere are two ways of calculating overview information in NAV.\n By using a FlowField. This applies for simpler calculations, like filtered or unfiltered counts, sums etc.\n By writing C/AL code to perform custom calculations. Use this when:\n 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 and in Walkthrough: Creating a Cue Based on a FlowField.\nNAV Usages\nTable 1 - Cue tables in Dynamics NAV shows some examples of singleton tables used for creating Cues.\n 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\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nCues are …","ref":"/docs/navpatterns/patterns/singleton/singleton-table/cue-table/","tags":"","title":"Cue Table"},{"body":"Authors: Henrik Langbak and Kim Ginnerup, Bording Data\nAbstract 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.\nA 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.\nDescription 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 todays 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:\n The SQL Server is reading too many records\n There would be too much data sent over the network.\n(If the SQL Server and the NAV Service tier are on different machines.)\n The NAV Service Tier receives and throws away data.\n Ending Date Problem Ending Date may introduce some problems of its own.\nIf 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.\nEnding 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.\nIf you add a record in between you will have to update both the before and the after record.\nThe pattern we describe here will work whether there is an Ending Date or Not.\nThe pattern is also relevant for other types than date. The pattern is usable whenever you have dependencies between rows in a table.\nUse 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.\nUsage 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.\n\n1. Create the view You will need to create the view before you define the Table Object.\nYou will need to create a view for every company in the database.\nCREATEVIEW[dbo].[CRONUS$PriceView]ASSELECT[Code],[StartingDate],[Price]FROMdbo.[CRONUS$Price]ASAWHERE[StartingDate]=(SELECTMAX([StartingDate])FROMdbo.[CRONUS$Price]ASBWHEREB.[Code]=A.[Code]ANDB.[StartingDate]\u003c=GETDATE())Test the view to ensure that you get the correct result. It is much easier to test now than later.\n2. Create the Table object Remember to set the link table property before you save it.\n3. Implement the code IFPriceView.FINDSETTHEN// You have them 4. Create a deployment codeunit Create a SQL Deployment codeunit to manage your views.\nThe codeunit needs to Create or Alter the views for all companies.\nTo see an example of how to talk to SQL Server using .NET see waldos blog here:\nhttp://dynamicsuser.net/blogs/waldo/archive/2011/07/19/net-interop-calling-stored-procedures-on-sql-server-example-1.aspx\n5. Deployment You need to deploy in three steps:\n Delete the table objects referencing the views Deploy and run the deployment codeunit 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:\n If you add columns, you need to add them to the view first and then add them to the Table Object. 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.\nPrice.SETCURRENTKEY(Code,\"Starting Date\");Price.SETFILTER(\"Starting Date\",'..%1',TODAYIFPrice.FINDSETTHENBEGINREPEATPrice.SETRANGE(Code,Price.Code);Price.FINDLAST;Price.SETRANGE(Code);PriceTemp:=Price;PriceTemp.INSERT;UNTILPrice.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:\n The table has a more complex key.\nThis will require setting and clearing more filters You need to read from more than one table.\nSay you need to apply discount from a separate table.\nThis may give several lines in PriceTemp. If the Code field is controlled by a Type field.\nThe 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.\nUsing the pattern will only issue one SQL call and thereby one trip to the server.\nThe 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.\nThe 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.\nThe Pattern makes a scalable solution with a predictable performance. The performance will not deteriorate at the same rate as the NAV code example.\nNAV Usages The pattern does not exist in NAV (yet J). We have used it several times in our code for an Add-On.\nIdeas 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.\nAn alternative would be better support for linked table objects, specifically views. The current implementation is very fragile.\nThe pattern only supports fetching data for a given date (normally today). This is because you cannot control the where-clause of the sub-select.\nRelated Topics The idea of having a linked table object pointing to a view could be a pattern of its own.\n","categories":"","description":"","excerpt":"Authors: Henrik Langbak and Kim Ginnerup, Bording Data\nAbstract Date …","ref":"/docs/navpatterns/patterns/currently-active-record/","tags":"","title":"Currently Active Record"},{"body":"Do not write functions that have high cyclomatic complexity. This makes the code hard to maintain.\nBad code\nAny procedure / trigger that has a cyclomatic complexity \u003e 25, using the CC3 version mentioned in [this article][anchor0]. Good code\nAny procedure / trigger that has a cyclomatic complexity \u003c= 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\\. ","categories":"","description":"","excerpt":"Do not write functions that have high cyclomatic complexity. This …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/cyclomatic-complexity/","tags":"","title":"Cyclomatic Complexity"},{"body":"Written by Bogdan Andrei Sturzoiu, at Microsoft Development Center Copenhagen\nAbstract This pattern implements a generic mechanism for dynamically restricting and allowing usage of a record by the business process administrator.\nProblem 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.\nFor example, a new customer record should not be used for posting documents until it is approved by the relevant approver.\nWe could solve this by using the Blocked Entity pattern, but it requires database schema changes, which have an upgrade impact.\nThe blocked entity pattern involves:\n Adding a “blocked” status field on the record (either a Boolean or in the more advanced cases, an option field refining the usage). 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).\nSolution This pattern describes a generic mechanism of adding and lifting restrictions for any type of record.\nThe restriction mechanism has the following elements:\n 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. 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. 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:\n 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.\nExample For example, we want to restrict posting Gen. Journal Lines if a customer has not been added in Account No. field.\nFor this, the following components are needed:\n When a Gen. Journal Line is inserted, call RestrictRecordUsage in COD1550, either directly in the trigger or using an event subscriber. When you validate a Customer No. as Account no. and Customer as Account Type, lift the restrictions by calling AllowRecordUsage in COD1550. 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.\nThe code behind the “Add record restriction” workflow response:\nRecRef.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:\nRecRef.GETTABLE(Variant);CASERecRef.NUMBEROFDATABASE::\"Approval Entry\":BEGINRecordRestrictionMgt.AllowRecordUsage(RecRef.RECORDID);RecRef.SETTABLE(ApprovalEntry);RecRef.GET(ApprovalEntry.\"Record ID to Approve\");AllowRecordUsage(RecRef);END;DATABASE::\"Gen. Journal Batch\":BEGINRecRef.SETTABLE(GenJournalBatch);RecordRestrictionMgt.AllowGenJournalBatchUsage(GenJournalBatch);ENDELSERecordRestrictionMgt.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).\nConsequences Currently, there can only be one restriction per record. There are no restriction types.\nIn 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.\nNAV Versions This pattern has been introduced in Dynamics NAV 2016.\n","categories":"","description":"","excerpt":"Written by Bogdan Andrei Sturzoiu, at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/blocked-entity/data-driven-blocked-entity/","tags":"","title":"Data Driven Blocked Entity"},{"body":"By David Bastide and Soumya Dutta at Microsoft Development Center Copenhagen\n\nContext: This pattern is describing how you can migrate data using the Data Migration Façade.\nProblem: 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.\nSolution: 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.\nAdditionally, 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).\nThe façade framework has the following components:\n Two management codeunits:\n 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:\n 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.\n Data Migration Overview (page 1799) Usage: There are the following use cases:\n 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.\n 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.\n To initialize and start the data migration, you must call the following procedures:\n “Data Migration Status Façade”.InitStatusLine(My Migration Type,Database::Item,42000,0,Codeunit::“My extension Item migration codeunit”)\nThis 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)\nThis 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.\nUsage without staging tables: The overall workflow is:\n 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. 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”). Launch the migration: “Data Migration Façade”.StartMigration(My Migration Type,false). Your migration codeunits are called one at a time (OnRun) in the following order: G/L accounts (first, because customer/vendor posting groups refer to G/L accounts) Customers Vendors Items (because discounts may refer to customer groups) Others 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). \nFigure 1: sequence diagram of the data migration without staging tables\nThe following example shows how to migrate items without staging tables:\ntriggerOnRun();varItemDataMigrationFacade:Codeunit\"Item Data Migration Facade\";ItemNumber:Integer;ItemJson:Text;begin// loop on items retrieved through a web service for example forItemNumber:=1toExternalWebService.GetItemCountdobeginExternalWebService.GetItem(ItemNumber,ItemJson);// create item using the facade ifnotItemDataMigrationFacade.CreateItemIfNeeded(ItemJson.ItemNumber,ItemJson.ItemName1,ItemJson.ItemName2,ConvertItemType(ItemJson.ItemType)) thenexit;// item already exists // set some fields using the facade ItemDataMigrationFacade.SetVendorItemNo(ItemJson.VendItemNumber);ItemDataMigrationFacade.SetUnitVolume(ItemJson.Volume);ItemDataMigrationFacade.SetAlternativeItemNo(ItemJson.AltItemNumber);ifItemJson.PrimaryVendor\u003c\u003e''thenItemDataMigrationFacade.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;procedureMigrateItemUnitOfMeasure(ItemDataMigrationFacade:Codeunit\"Item Data Migration Facade\";ItemJson:Text);varMyUnitCodeStagingTable:Record\"My Unit Code Staging Table\";DataMigrationStatusFacade:Codeunit\"Data Migration Status Facade\";DescriptionToSet:Text[10];UnitCodeJson:Text;beginifItemJson.UnitCode=''then// log an error using the Data migration façade DataMigrationStatusFacade.RegisterErrorNoStagingTablesCase( 'My Migration Type',Database::Item,'Unit of measure is empty.');ifExternalWebService.GetUnitCode(ItemJson.UnitCode,UnitCodeJson) thenDescriptionToSet:=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\nUsage with staging tables: The overall workflow is:\n Integrate your extension in the Data Migration Wizard by subscribing to the events exposed by the Data Migration Façade.\n 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).\n 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.\n Launch the migration: “Data Migration Façade”.StartMigration(My Migration Type,false).\n Subscribe to the events to migrate entities and their dependencies.\n From the event subscribers, call the façade procedures to create entities and set their field values:\n “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) \nFigure 3: Simplified sequence diagram of the data migration with staging tables\nBelow is a simplified example showing how to create an item:\n[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Item Data Migration Facade\",'OnMigrateItem','',true,true)]procedureOnMigrateItem(VARSender:Codeunit\"Item Data Migration Facade\";RecordIdToMigrate:RecordId);varMyItemStagingTable:Record\"My Item Staging Table\";begin// handle the event if it targets this extension's staging table ifRecordIdToMigrate.TableNo\u003c\u003eDatabase::\"My Item Staging Table\"thenexit;MyItemStagingTable.Get(RecordIdToMigrate);// create item using the facade ifnotSender.CreateItemIfNeeded(MyItemStagingTable.ItemNumber,MyItemStagingTable.ItemName1,MyItemStagingTable.ItemName2,ConvertItemType(MyItemStagingTable.ItemType)) thenexit;// item already exists // set some fields using the facade Sender.SetVendorItemNo(MyItemStagingTable.VendItemNumber);Sender.SetUnitVolume(MyItemStagingTable.Volume);Sender.SetAlternativeItemNo(MyItemStagingTable.AltItemNumber);ifMyItemStagingTable.PrimaryVendor\u003c\u003e''thenSender.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\nBelow is another example showing how to use additional events to set fields that reference other tables, here the unit of measure:\n[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Item Data Migration Facade\",'OnMigrateItemUnitOfMeasure','',true,true)]procedureOnMigrateItemUnitOfMeasure(VARSender:Codeunit\"Item Data Migration Facade\";RecordIdToMigrate:RecordId);varMyItemStagingTable: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 ifRecordIdToMigrate.TableNo\u003c\u003eDatabase::\"My Item Staging Table\"thenexit;MyItemStagingTable.Get(RecordIdToMigrate);ifMyItemStagingTable.UnitCode=''thenerror('Unit of measure is empty.');MyUnitCodeStagingTable.SetRange(UnitCode,MyItemStagingTable.UnitCode);ifMyUnitCodeStagingTable.FindFirstthenDescriptionToSet:=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\nCombining 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.\nError 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.\n\nFigure 6: List of errors shown when clicking Show Errors on the Data Migration Overview page\nThe 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.\n\nFigure 7: Edit a staging table record\nThe 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.\nAfter 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.\nError handling without staging tables\nWhen 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.\nErrors 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.\nLimitations: 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.\n G/L entries are deleted automatically.\n 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.\n Usages in NAV: The Data Migration Façade is available starting from version 2018.\nThe following Façade codeunits for data migration management are available:\n COD6100 (Data Migration Facade)\n COD6101 (Data Migration Status Facade)\n The following Entity data migration façade codeunits are available:\n COD6110 (GL Acc. Data Migration Facade)\n COD6111 (Vendor Data Migration Facade)\n COD6112 (Customer Data Migration Facade)\n COD6113 (Item Data Migration Facade)\n COD6114 (Ex. Rate Data Migration Facade)\n References: Façade pattern on Wikipedia: https://en.wikipedia.org/wiki/Facade_pattern\n","categories":"","description":"","excerpt":"By David Bastide and Soumya Dutta at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/data-migration-facade/","tags":"","title":"Data Migration Façade"},{"body":"C/AL Coding Guidelines Design Find the C/AL guidelines by expanding the menu in the left.\n","categories":"","description":"","excerpt":"C/AL Coding Guidelines Design Find the C/AL guidelines by expanding …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/","tags":"","title":"Design"},{"body":"by waldo\nAbstract 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.\nThe problem Lets 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”.\nUsage 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.\n\nThe goal of this functionality is to:\n 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:\n 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.\nOne example of a subscription is the SMTP setup. In Codeunit 400 youll find the subscriber function HandleSMTPRegisterServiceConnection which subscribes to this discovery event, and calls the InsertServiceConnection to register itself.\nDescription 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. Its a pattern where using both publishers and subscribers in one application makes a lot of sense.\nLets break down to the steps that are needed to implement the pattern.\nStep 1: Publish the event In the below example, I create a table Module Status with a published event OnDiscoverModuleStatuses.\n\nYou 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.\nStep 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:\n\nStep 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:\n\nThe business logic doesnt really matter for this pattern. This is obviously dependent on the functionality where you would like to implement the pattern.\nStep 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.\nThe exact place of the subscriber is up to you. The main message is that its part of the module that wants to subscribe, and not part of the Module Status module in the application.\nHere is the subscriber (and one small helper function):\n\nYou see I can use the “sender” as a normal Record-variable. I access the previously created global function to “register” this sales-module.\nMicrosoft Dynamics NAV Versions This pattern only works with Microsoft Dynamics NAV 2016 and up.\n","categories":"","description":"","excerpt":"by waldo\nAbstract The “Discovery Event” pattern is a way for a generic …","ref":"/docs/navpatterns/patterns/discovery-event/","tags":"","title":"Discovery Event"},{"body":"By Xavier Garonnat, knk Ingénierie (France), xgaronnat@knk.fr\nAbstract 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.\nDescription 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:\n\nUsage You should use it any time you have to capture and store a document.\nExample To build this example from scratch, you will need:\n 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 …)\n 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. Dont forget to manage deletion of lines with trigger OnDelete().\nTable “Document Line”: will store the lines of the document\n 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).\nFor 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)\nPage “Document Subpage”: will display the lines in the main form, and will be in charge of assigning line number automatically.\nCreate 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.\").\nThen edit the properties:\n 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.\nPage “Document”: will display the document, and the lines with subpage.\nCreate the page for “Document Header” Table with the wizard by selecting the Document template:\n 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 :\n\nPage “Document List”: Use the Page wizard to create a List page based on the Document table and add fields, FactBox (RecordLinks, Notes…), etc.\nOnce created:\n 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.\nNow, observe how “Line No.” is calculated on the first line, and when inserting a new line between the first and second one.\nCode sample (copy link to your browser) : https://knk1fr-my.sharepoint.com/personal/xgaronnat_knk_fr/_layouts/15/guestaccess.aspx?guestaccesstoken=hL0P%2fyQ1ZreY5KlSPc%2b8dHrO4zjUkqQbg8DnGSbgd1Y%3d\u0026docid=02b3cb93e1ff1459380891795fb8441fc\nNAV Usages So many: Sales Order, Purchase Order, Transfer Order, Assembly Order…\nFor posted document, its quite similar, but you dont have to setup subpage properties like AutoSplitKey, used for data entry purpose only (and your pages content should be mainly read-only / non editable).\nIdeas for improvement A new property like “AutoSplitStartNumber”, enabled if AutoSplitKey=Yes, default value with \u003c10000\u003e. 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…).\nRelated Topics Use Series No. Pattern for your documents, and Copy Document to implement document duplication.\nReferences Walkthrough: Creating a Document Page : http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx\n ","categories":"","description":"","excerpt":"By Xavier Garonnat, knk Ingénierie (France), xgaronnat@knk.fr\nAbstract …","ref":"/docs/navpatterns/patterns/document/","tags":"","title":"Document"},{"body":"Originally by Anders Larsen at Microsoft Development Center Copenhagen\nAbstract 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.\nThe 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.\nTo 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.\nUsage 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.\nCall the code. For example:\nLocal IsXAvailable : Boolean If field X \u003c\u003e '' 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\n.. SetupTable.VerifyAndSetX .. NAV Specific Example In the Sales \u0026 Receivables Setup table (311) for the DK version, the following procedures have been added:\nLocalProcedureIsOIOUBLPathAvailable(...) ProcedureVerifyAndSetOIOUBLPath(...) The code in the Sales \u0026 Receivables Setup table can now be called directly from the related processing codeunit, such as the Sales-Post + Print codeunit (82).\nWere the code is called:\nIF(\"EAN No.\"\u003c\u003e'') THENSalesSetup.VerifyAndSetOIOUBLPathSetup(SalesHeader.\"Document Type\");If the setup is not updated properly, the user is prompted to update it as follows.\n\nChoosing Yes opens the related setup page.\n\nNAV 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.\nRelated Topics The anti-pattern is to do a testfield on a field that is not in the table that you are currently updating.\nThe 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.\n ","categories":"","description":"","excerpt":"Originally by Anders Larsen at Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/easy-update-of-setup-or-supplementary-information/","tags":"","title":"Easy Update Of Setup Or Supplementary Information"},{"body":"Any function used local must be defined as local.\n","categories":"","description":"","excerpt":"Any function used local must be defined as local.\n","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/encapsulate-local-functionality/","tags":"","title":"Encapsulate Local Functionality"},{"body":"The END ELSE pair should always appear on the same line.\nBad code\nIFOppEntry.FIND('-') THENIFSalesCycleStage.FIND('-') THENBEGIN... ENDELSE... Good code\nIFOppEntry.FIND('-') THENIFSalesCycleStage.FIND('-') THENBEGIN... ENDELSE... ","categories":"","description":"","excerpt":"The END ELSE pair should always appear on the same line.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/end-else-pair/","tags":"","title":"END ELSE Pair"},{"body":"By Jesper Schulz at Microsoft Development Center Copenhagen\nNote: This pattern describes new functionality which makes it possible to generalize the Journal Error Processing pattern.\nAbstract 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.\nDescription This article describes how to use the Error Message component in NAV, which in short gives you the possibility to:\n Link an error message to the page which enables you to resolve the problem. 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 NAVs 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.\nThe 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:\n\nBy 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.\n\nUsage 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:\n LogIfEmpty LogIfLengthExceeded LogIfInvalidCharacters LogIfOutsideRange LogIfGreaterThan LogIfEqualTo LogMessage The following parameters must be provided to these functions:\n 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.\nNAV 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.\nPROCEDUREExportChartOfAccounts@1(Year@1000:Integer;Month@1001:Integer);VARTempErrorMessage@1003:TEMPORARYRecord700;BEGINTempErrorMessage.ClearLog;// only necessary if variable is global ... CreateXMLHeader(Document,RootNode,CatalogoNodeTxt,Namespace,Year,Month,'1.1');IFGLAccount.FINDSETTHENBEGINREPEATTempErrorMessage.LogIfEmpty(GLAccount,GLAccount.FIELDNO(Name),TempErrorMessage.\"Message Type\"::Error);XMLDOMManagement.AddElement(RootNode,'Ctas','',Namespace,Node);XMLDOMManagement.AddAttribute(Node,'CodAgrup',GLAccount.\"SAT Account Code\");... CASEGLAccount.\"Debit/Credit\"OFGLAccount.\"Debit/Credit\"::Debit:XMLDOMManagement.AddAttribute(Node,'Natur','D');GLAccount.\"Debit/Credit\"::Credit:XMLDOMManagement.AddAttribute(Node,'Natur','A');ELSETempErrorMessage.LogMessage( GLAccount,GLAccount.FIELDNO(\"Debit/Credit\"),TempErrorMessage.\"Message Type\"::Error,STRSUBSTNO(GLAccountTypeErr,GLAccount.\"Debit/Credit\",GLAccount.RECORDID));END;UNTILGLAccount.NEXT=0;ENDELSETempErrorMessage.LogSimpleMessage(TempErrorMessage.\"Message Type\"::Error,NoSATAccountDefinedErr);IFNOTTempErrorMessage.HasErrors(TRUE) THENSaveXMLToClient(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.\nIdeas 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.\n","categories":"","description":"","excerpt":"By Jesper Schulz at Microsoft Development Center Copenhagen\nNote: This …","ref":"/docs/navpatterns/patterns/error-message-processing/","tags":"","title":"Error Message Processing"},{"body":"By David Bastide at Microsoft Development Center Copenhagen\n\nContext 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.\nThis 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.\nDescription 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.\nHeadlines are divided in 2 parts: the qualifier, and the payload as you can see in the figure below.\n\nFigure 1: Qualifier, Payload and emphasized text.\nUsage A page part has been added to each major Role Center:\n 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 \u0026 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.\nIf no headline is added on these pages, fallback headlines will be displayed.\nThe process to extend the headlines of a Role Center is simple:\n 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. 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. 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. 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:\n 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;triggerOnDrillDown() varEssentialBusHeadlineMgt:Codeunit\"Essential Bus. Headline Mgt.\";beginEssentialBusHeadlineMgt.OnDrillDownLargestSale();end;}}2. Subscribing to the OnComputeHeadlines event, and computing headlines [EventSubscriber(ObjectType::Codeunit,Codeunit::\"Headline RC Business Manager\",'OnComputeHeadlines','',true,true)]procedureOnComputeHeadlinesBusinessManager() begin// [...] compute headline, and init the EssentialBusinessHeadline record ifnotShowHeadlinethenexit;// not enough data to compute headline ifnotHeadlineManagement.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\") thenexit;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)]procedureOnIsAnyExtensionHeadlineVisible(varExtensionHeadlinesVisible:Boolean) varEssentialBusinessHeadline:Record\"Essential Business Headline\";AtLeastOneHeadlineVisible:Boolean;beginEssentialBusinessHeadline.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:=notEssentialBusinessHeadline.IsEmpty();// only modify the var if this extension is making some headlines visible, setting to false could override some other extensions setting the value to true ifAtLeastOneHeadlineVisiblethenExtensionHeadlinesVisible:=true;end; 4. Setting the headline text on the page triggerOnAfterGetRecord() beginEssentialBusinessHeadline.GetHeadline(EssentialBusinessHeadline.\"Headline Name\"::LargestSale);LargestSaleVisible:=EssentialBusinessHeadline.\"Headline Visible\";LargestSaleText:=EssentialBusinessHeadline.\"Headline Text\";end;\nFigure 2: Sequence diagram of headline usage\nUsages in NAV: Essential Business Headlines extension ","categories":"","description":"","excerpt":"By David Bastide at Microsoft Development Center Copenhagen\n\nContext …","ref":"/docs/navpatterns/patterns/extending-the-role-center-headlines/","tags":"","title":"Extending the Role Center Headlines"},{"body":"Originally by Bogdan Sturzoiu at Microsoft Development Center Copenhagen\nAbstract This pattern shows a solution for integrating W1 features to pre-existing country features that use different tables to achieve similar functionality.\nDescription 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.\nThen, 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.\nThis was the issue that was tackled in the NAV 2013 R2, in relation to the SEPA Credit Transfers functionality.\nUsing a Proxy The generic Proxy pattern is “a class functioning as an interface to something else” (Wikipedia).\n\nFigure 1. Proxy in UML\nPattern Elements The NAV data model translation of the proxy pattern can be used as explained below.\nThe 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.\nThe 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.\nThe interface is the fixed form in which the data is presented to be consumed by the client.\nThe 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).\nPattern Steps The user creates records in the local tables.\n The user invokes an action that must be processed using the W1 feature code.\n 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.\n The W1 code now performs the action on the W1 table data.\n 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 customers 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).\nIn 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.\nThe W1 feature flow is as follows:\n\nFigure 2. W1 object call sequence\nNote: CT = Credit Transfers, pain = payments initiation (the XML format used for SEPA Credit Transfers and SEPA Direct Debit).\nThe 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)).\nIn W1, the codeunit simply outputs the same set of general journal lines that it receives as an input:\nOnRun(VARRec:Record\"Gen. Journal Line\") GenJnlLine.COPYFILTERS(Rec);CopyJnlLines(GenJnlLine,Rec);LOCALCopyJnlLines(VARFromGenJnlLine:Record\"Gen. Journal Line\";VARTempGenJnlLine:TEMPORARYRecord\"Gen. Journal Line\") IFFromGenJnlLine.FINDSETTHENBEGINGenJnlBatch.GET(FromGenJnlLine.\"Journal Template Name\",FromGenJnlLine.\"Journal Batch Name\");REPEATTempGenJnlLine:=FromGenJnlLine;TempGenJnlLine.INSERT;UNTILFromGenJnlLine.NEXT=0ENDELSECreateTempJnlLines(FromGenJnlLine,TempGenJnlLine);LOCALCreateTempJnlLines(VARFromGenJnlLine:Record\"Gen. Journal Line\";VARTempGenJnlLine:TEMPORARYRecord\"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:\n 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.\n Selects the local payment data, for example in Italy, in the Vendor Bill Header and Vendor Bill Lines tables.\n Transforms the local payment data into temporary records of the Gen. Journal Line table.\n Outputs the temporary general journal lines that will be further processed and exported, exactly as in W1.\n OnRun(VARRec:Record\"Gen. Journal Line\") GenJnlLine.COPYFILTERS(Rec);CopyJnlLines(GenJnlLine,Rec);LOCALCopyJnlLines(VARFromGenJnlLine:Record\"Gen. Journal Line\";VARTempGenJnlLine:TEMPORARYRecord\"Gen. Journal Line\") IFFromGenJnlLine.FINDSETTHENBEGINGenJnlBatch.GET(FromGenJnlLine.\"Journal Template Name\",FromGenJnlLine.\"Journal Batch Name\");REPEATTempGenJnlLine:=FromGenJnlLine;TempGenJnlLine.INSERT;UNTILFromGenJnlLine.NEXT=0ENDELSECreateTempJnlLines(FromGenJnlLine,TempGenJnlLine);LOCALCreateTempJnlLines(VARFromGenJnlLine:Record\"Gen. Journal Line\";VARTempGenJnlLine:TEMPORARYRecord\"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);IFVendorBillLine.FINDSETTHENBEGINCumulativeAmount:=0;PrevVendorBillLine:=VendorBillLine;REPEATVendorBillLine.TESTFIELD(\"Document Type\",VendorBillLine.\"Document Type\"::Invoice);IF((VendorBillLine.\"Vendor No.\"\u003c\u003ePrevVendorBillLine.\"Vendor No.\") OR(VendorBillLine.\"Vendor Bank Acc. No.\"\u003c\u003ePrevVendorBillLine.\"Vendor Bank Acc. No.\")) THENBEGINInsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount);CumulativeAmount:=VendorBillLine.\"Amount to Pay\";ENDELSECumulativeAmount+=VendorBillLine.\"Amount to Pay\";PrevVendorBillLine:=VendorBillLine;UNTILVendorBillLine.NEXT=0;InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount);END;VendorBillLine.SETRANGE(\"Cumulative Transfers\",FALSE);IFVendorBillLine.FINDSETTHENREPEATVendorBillLine.TESTFIELD(\"Document Type\",VendorBillLine.\"Document Type\"::Invoice);InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,VendorBillLine,VendorBillLine.\"Amount to Pay\");UNTILVendorBillLine.NEXT=0;LOCALInsertTempGenJnlLine(VARTempGenJnlLine:TEMPORARYRecord\"Gen. Journal Line\";VendorBillHeader:Record\"Vendor Bill Header\";VendorBillLine:Record\"Vendor Bill Line\";AmountToPay:Decimal) WITHTempGenJnlLineDOBEGININIT;\"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:\n\nFigure 3. The local country object flow\nAs 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:\n The entry point of the flow is the local table/page.\n Codeunit 1222 is overloaded to prepare general journal lines from the local records.\n NAV Usages The data mapping technique has been used for the SEPA Credit Transfer feature, and will be used in subsequent local integration projects.\nIdeas 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).\nAlso, 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.\n","categories":"","description":"","excerpt":"Originally by Bogdan Sturzoiu at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/feature-localization-for-data-structures/","tags":"","title":"Feature Localization For Data Structures"},{"body":"For user messages, errors etc., use FIELDCAPTION not FIELDNAME and TABLECAPTION not TABLENAME.\nReason:\n The correct translation will be automatically used. If the caption/name changes, then there will be a single point of change needed. Bad code\nIFNOTCONFIRM(UpdateLocationQst,TRUE,FIELDNAME(\"Location Code\"),...) Good code\nIFNOTCONFIRM(UpdateLocationQst,TRUE,FIELDCAPTION(\"Location Code\"),...) ","categories":"","description":"","excerpt":"For user messages, errors etc., use FIELDCAPTION not FIELDNAME and …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/fieldcaption-and-tablecaption/","tags":"","title":"FIELDCAPTION and TABLECAPTION"},{"body":"Never use FIELDERROR with a period as it is automatically inserted.\nBad code\nInvalidValue@1025:TextConst'ENU=is invalid.';... Cust.FIELDERROR(\"No.\",InvalidValue);Good code\nInvalidValue@1025:TextConst'ENU=is invalid';... Cust.FIELDERROR(\"No.\",InvalidValue);","categories":"","description":"","excerpt":"Never use FIELDERROR with a period as it is automatically inserted. …","ref":"/docs/navpatterns/3-cal-coding-guidelines/ux/fielderror/","tags":"","title":"FIELDERROR"},{"body":"FINDSET, FIND('+') or FIND('-') should only be used when NEXT is used and vice versa.\nBad code\nIF Cust.FIND('-') THEN ERROR(CustIsBlockErr) Good code\nIF Cust.FINDFIRST THEN ERROR(CustIsBlockErr) Bad code\nIF Cust.FINDFIRST THEN REPEAT ... UNTIL Cust.NEXT = 0; Good code\nIF Cust.FINDSET THEN REPEAT ... UNTIL Cust.NEXT = 0; ","categories":"","description":"","excerpt":"FINDSET, FIND('+') or FIND('-') should only be used when NEXT is used …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/findset-findfirst-findlast/","tags":"","title":"FINDSET FINDFIRST FINDLAST"},{"body":"Declare Text Constant as global variables.\nBad code\nPROCEDUREGetRequirementText@6(...) :Text[50];VARRequirementOptionsTxt@1002:TextConst'ENU=Shipment,Receive,Pick,Put-Away';BEGINGood code\nVARRequirementOptionsTxt@1002:TextConst'ENU=Shipment,Receive,Pick,Put-Away';... PROCEDUREGetRequirementText@6(...) :Text[50];BEGIN","categories":"","description":"","excerpt":"Declare Text Constant as global variables.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/global-text-constants/","tags":"","title":"Global Text Constants"},{"body":"By Eric Wauters (waldo), Partner-Ready-Software\nAbstract 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.\nDescription 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.. .\nAfter years, its 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”.\nBy 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.\nTo minimize the impact of customizations, the idea of hooks is:\n 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:\n 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 doesnt exist yet - you create your Hook Codeunit. As the name assumes .. this is always a codeunit. We apply the following rules to it:\n 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:\n 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, its very clear what are hooks, and what arent.. Step 3, its 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:\n 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.\nExample 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:\nStep 1: create codeunit “Sales-Post Hook”\n\nStep 2: create the hook function “OnBeforePostDocument”\n\nStep 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.\n\nStep 4: implement the business logic, by calling out to a new function. And implement the test-codeunit.\n\nConsequences This pattern can be used in all cases to put business logic. But I see three possible approaches\n 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… Only at objects of the default application which you are customizing. This way, you dont want to create hooks for your own objects, only default existing objects. (recommended) You create hooks on all places you dont 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: Its important that the hook function is readable in the most extreme way. For this, we recommend to use the “Atomic Coding” concept.\nSee here a comparison / extension of hooks : http://www.waldo.be/2016/02/29/nav-2016-hooks-or-events/\n","categories":"","description":"","excerpt":"By Eric Wauters (waldo), Partner-Ready-Software\nAbstract As a partner, …","ref":"/docs/navpatterns/patterns/hooks/","tags":"","title":"Hooks"},{"body":"By Soren Klemmensen, Partner-Ready-Software \u0026 360 Visibility\nAbstract This Pattern is meant to create generic \u0026 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.\nTo 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:\n To create a generic and reusable auto generated link (A Surrogate Key), Immune to natural key data \u0026 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.\n\nFigure 1: Table structure for linking a Document Header and Line Table with a Document Comment Table.\n\nFigure 2: Table Structure for linking a Master Data Table with a Master Data Comment Table\nA 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.\n\nFigure 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.\nIt is recommended using this pattern in all tables which need sub tables unless specific reasons exists for not doing this.\nUsage Step 1: Create a generic Unique Record Identifier in the main table\nThe 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 \u0026 AutoIncrement to Yes.\nStep 2: Create a generic link-able sub table.\nCreate a new table (Sub Table) which you would like to be reusable with a primary key containing\n 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.\nMake sure to also add any other fields containing the information you wish to store as needed to the table.\nThe 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.\nStep 3: Create a page showing the sub table information.\nNow create a page showing the data in the sub table.\nStep 4: Add an Action or factbox.\nCreate 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.\nStep 5: Create a Hook for Function OnDatabaseDelete in Codeunit 1 ApplicationManagement if one doesnt already exist. See the Hook pattern.\nStep 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.\nNAV Specific Example Lets assume we would like to create comment for a larger number of very different tables in the system.\nUpdate 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 \u0026 AutoIncrement to Yes. Save the changes.\n\n_\nCreate Comment table (Step 2): Create a new table called Comment. Add 3 fields Table No., Unique Record Identifier \u0026 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.\n\nCreate 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.\n__\nUpdate 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.\n\nCreate a hook OnDatabaseDelete (Step 5):\nCreate 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.\n\nCreate the code needed to delete comments linked to a deleted record (Step6):\nCreate a DeleteComments function taking the RecRef of Data Type RecordRef and add the code as shown blow.\n\nIt 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.\nThe 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.\nThese 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 \u0026 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.\nLooking at the main table the Unique Record Identifier is also completely reusable for any other linking needed.\nOther 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.\nUpgrade 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.\nOther risks could be if Transfer Fields are used and data is being copied unintentionally.\nNAV Usages This is a new pattern not currently used in Microsoft Dynamics NAV.\nIdeas 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.\nConsequences (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.\nRelated 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.\n","categories":"","description":"","excerpt":"By Soren Klemmensen, Partner-Ready-Software \u0026 360 Visibility\nAbstract …","ref":"/docs/navpatterns/patterns/implementation-of-surrogate-keys-using-autoincrement-pattern/","tags":"","title":"Surrogate keys using Autoincrement Pattern"},{"body":"By Soumya Dutta at Microsoft Development Center Copenhagen\nContext 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 theyre doing first.\nProblem 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.\nSolution Notifications display a message in a blue bar at the top of the workspace, as shown in Figure 1.\n\nFigure 1 - Example of a notification\nNotifications 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 isnt 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.\nIn this example, if you choose Details a page opens to show the status of the inventory, as shown in Figure 2.\n\nFigure 2 - Clicking an action in a notification\nRaising a notification The code in Figure 3 raises the notification in Figure 1.\nCOD 311: Item-Check Avail.\nCreateAndSendNotification\nAvailabilityCheckNotification.ID(GetItemAvailabilityNotificationId);\nAvailabilityCheckNotification.MESSAGE(STRSUBSTNO(NotificationMsg,ItemNo));\nAvailabilityCheckNotification.SCOPE(NOTIFICATIONSCOPE::LocalScope);\nAvailabilityCheckNotification.ADDACTION(DetailsTxt,CODEUNIT::“Item-Check Avail.”,ShowNotificationDetails);\nItemAvailabilityCheck.PopulateDataOnNotification(AvailabilityCheckNotification,ItemNo,UnitOfMeasureCode\n,InventoryQty,GrossReq,ReservedReq,SchedRcpt,ReservedRcpt,CurrentQuantity,CurrentReservedQty,\nTotalQuantity,EarliestAvailDate);\nAvailabilityCheckNotification.SEND;\n…\nFigure 3 - Raising a notification\nThe first thing to note is that a new Notification DataType object has been introduced to C/SIDE.\n\nFigure 4. Notification is a new data type\nIn the code sample in Figure 3, the first line defines the scope. Currently , only the LocalScope is supported.\nIdentifying 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.\nCOD 311: Item-Check Avail.\nGetItemAvailabilityNotificationId\nEXIT(2712AD06-C48B-4C20-820E-347A60C9AD00);\nFigure 5. Uniquely identifying a notification\nIf 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.\nIncluding messages notifications Notifications should display a message. This message is set by an assignment call to the MESSAGE parameter of the notification object.\nInvoking 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:\n 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.\nCOD 311: Item-Check Avail.\nShowNotificationDetails\nItemAvailabilityCheck.InitializeFromNotification(AvailabilityCheckNotification);\nItemAvailabilityCheck.SetHeading(AvailabilityCheckNotification.MESSAGE);\nItemAvailabilityCheck.RUNMODAL;****\nFigure 6 - Invoking an action\nTo 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.\nPage 1872: Item Availability Check\nInitializeFromNotification\nGET(AvailabilityCheckNotification.GETDATA(ItemNo));\nSETRANGE(“No.\",AvailabilityCheckNotification.GETDATA(ItemNo));\nEVALUATE(TotalQuantity,AvailabilityCheckNotification.GETDATA(TotalQuantity));\nEVALUATE(InventoryQty,AvailabilityCheckNotification.GETDATA(InventoryQty));\nCurrPage.AvailabilityCheckDetails.PAGE.SetUnitOfMeasureCode(\nAvailabilityCheckNotification.GETDATA(UnitOfMeasureCode));\nFigure 7 - Fetching parameters from a notification object\nNote how GETDATA uses a key to fetch values from the notification object, and how those values are used to initialize the page.\nNotifications can include zero, one, or more than one action buttons. More than one action buttons result in multiple ADDACTION calls to the notification object.\nPopulating 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.\nPage 1872: Item Availability Check\nPopulateDataOnNotification\nAvailabilityCheckNotification.SETDATA(ItemNo,ItemNo);\nAvailabilityCheckNotification.SETDATA(UnitOfMeasureCode,UnitOfMeasureCode);\nAvailabilityCheckNotification.SETDATA(GrossReq,FORMAT(GrossReq));\n…\nFigure 8 - Populating parameters on notifications\nThe 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.\nDisplaying 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 serverclient calls. Instead, call only SEND. Calling SEND for a notification that is already displayed updates the notification.\nTurning 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 dont want to be disturbed or are willing to accept the consequences of ignoring the message. This is unique to notifications.\n\nFigure 9 - The My Notifications page\nAdditionally, 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.\n In the top right corner, choose the Search for Page or Report icon, enter my notifications, and then choose the related link. To turn on or turn off a notification, select or clear the Enabled check box. 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.\n 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.\nOnInitializingNotificationWithDefaultState\nMyNotifications.InsertDefaultWithTableNum(GetItemAvailabilityNotificationId,\nItemAvailabilityNotificationTxt,\nItemAvailabilityNotificationDescriptionTxt,\nDATABASE::Item);\nFigure 10 - Adding a notification to the My Notifications page\nYou 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.\n\nFigure 11 - Defining filter criteria to turn on a notification\n 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 dont 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.\nIsItemAvailabilityNotificationEnabled\nEXIT(MyNotifications.IsEnabledForRecord(GetItemAvailabilityNotificationId,Item));\nFigure 12 - Checking whether notifications are turned on\nYou may check that the call to this function is made almost as the first step in checking for availability.\n 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.\nNAV specific usages For examples of how these objects are used in Dynamics NAV, look at the code for the following objects:\n Codeunit 1802 Data Migration Notifier Codeunit 311 Item-Check Avail. Codeunit 312 Cust-Check Cr. Limit Codeunit 1854 Item Sales Forecast Notifier (in SalesAndInventoryForecast extension) Codeunit 1852 Item Sales Forecast Scheduler (in SalesAndInventoryForecast extension) Best practices The following list summarizes best practices for creating notifications:\n Do not set data on the notification that you will not use in the method invoked from the action button. 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. 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. 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. ","categories":"","description":"","excerpt":"By Soumya Dutta at Microsoft Development Center Copenhagen\nContext …","ref":"/docs/navpatterns/patterns/notifications/in-context-notifications/","tags":"","title":"In-context Notifications"},{"body":"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.\nBad code\nIFGLSetup.\"Unrealized VAT\"OR(GLSetup.\"Prepayment Unrealized VAT\"ANDNewCVLedgEntryBuf.Prepayment) Good code\nIFGLSetup.\"Unrealized VAT\"OR(GLSetup.\"Prepayment Unrealized VAT\"ANDNewCVLedgEntryBuf.Prepayment) Bad code\nIFGenJnlLine.\"Account No.\"\u003c\u003eICPartner.CodeTHENICPartner.GET(\"Account No.\");IFGenJnlLine.Amount\\\u003e0THENBEGIN... Good code\nIFGenJnlLine.\"Account No.\"\u003c\u003eICPartner.CodeTHENICPartner.GET(\"Account No.\");IFGenJnlLine.Amount\u003e0THENBEGIN... Bad code\nDialog.OPEN(WindowTxt+'@1@@@@@@@@@@@@@@@@@@@@@@@');Good code\nDialog.OPEN( WindowTxt+'@1@@@@@@@@@@@@@@@@@@@@@@@');Bad code\nTempOldCustLedgEntry.DELETE;// Find the next old entry for application of the new entry Good code\nTempOldCustLedgEntry.DELETE;// Find the next old entry for application of the new entry Bad code\nIFNOT(\"Applies-to Doc. Type\"IN[\"Applies-to Doc. Type\"::Receipt,\"Applies-to Doc. Type\"::\"Return Shipment\"]) Good code\nIFNOT(\"Applies-to Doc. Type\"IN[\"Applies-to Doc. Type\"::Receipt,\"Applies-to Doc. Type\"::\"Return Shipment\"]) Bad code\nWHILE(RemAmt\u003e0) OR(RemAmtLCY\u003e0) DOGood code\nWHILE(RemAmt\u003e0) OR(RemAmtLCY\u003e0) DOBad code\nUNTIL(RemAmt\u003e0) AND(RemAmtLCY\u003e0);Good code\nUNTIL(RemAmt\u003e0) AND(RemAmtLCY\u003e0) ","categories":"","description":"","excerpt":"In general, use an indentation of two space characters. Logical …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/indentation/","tags":"","title":"Indentation"},{"body":"Variables should always be set to a specific value, before they are used.\nBad code\nPROCEDURE 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\nPROCEDURE 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\n// 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\nPROCEDURE GetItemsToPlan@22() : Boolean; BEGIN SETRANGE(\"Document Type\",\"Document Type\"::Order); ... EXIT(FINDSET) END; ","categories":"","description":"","excerpt":"Variables should always be set to a specific value, before they are …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/initialized-variables/","tags":"","title":"Initialized Variables"},{"body":"Originally by Nikola Kukrika at Microsoft Development Center Copenhagen\nAbstract 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 users productivity after user has learned how to use a feature.\nDescription 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.\nUsers' expectations are changing. They expect the software to be usable out-of-the-box because this is the trend in software generally.\nOne 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.\nIn 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.\nIn the Mini App solution we have used following elements:\n Dismissible dialogs FastTabs with instructional text Help tiles on a Role Center Tooltips on actions and fields Task-oriented page Help Usage The following pattern applies to dismissible parts in the UI.\nWe 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.\n\nDismissible Dialogs Dismissible dialogs show the instructional message about the functionality, with the user option to select “Dont 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.\n\nOn 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.\nWhen 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.\nFastTabs with Instructional Text Instructional text on FastTabs is ideal for showing larger amounts of text in the UI.\n\nWhen 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.\nSimilar 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.\nInformation 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.\n\nNote: 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).\nTo implement tiles for instructional videos 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.) Get the code to embed the video (select option embed). You can reuse the code on the Mini Video Player Page page (1395) or implement a custom one. Important parts:\nVideoPlayerAddIn.SetFrameAttribute function is used to set an attribute to the iframe that will be playing the video.\nExample of the embed code:\n\u003ciframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/7SGp9pA9cAY\" frameborder=\"0\" allowfullscreen\\\u003e\u003c/iframe\\\u003e You must assign src attribute to src of the embed code, for example:\nVideoPlayer.SetFrameAttribute('src','https://www.youtube.com/embed/7SGp9pA9cAY');Without this, the video will not play. You can use the same function to assign other attributes, for example to remove frame border use:\nVideoPlayer.SetFrameAttribute(' frameborder','0');Height and width should be set by using the following functions, since they ensure that the video will be centered on the page.\nVideoPlayerAddIn.SetHeight(Height) andVideoPlayerAddIn.SetWidth(Width);If you would like to reuse the Mini Video Player Page page (1395), then use:\nSetParameters(Height,Width,Src,Caption), which uses the functions described above. 4. As a last step you need to implement the action on the group and assign a video icon\nNote:\nVideos are implemented to be Web Client only. This is done because Flash player control that is used by most of the providers is not working well with WebBrowser control that the Windows Client is using.\nFor displaying the videos on the Windows client, the simplest option is to provide an action with a link that opens a video page in a browser or a page hosting all of the instructional videos you have provided. Optionally you can implement a .NET add-in control that would be able to play the video from selected provider.\nTo implement tiles for help topics You only need to add an empty action with a TileHelp icon. Platform will render the action and will generate the logic to trigger a help call when user clicks on the icon. On the Help Server create an help topic that matches the URL.\nTooltips on actions and fields Platform improvements in NAV 2013 R2 provide ability to create tooltips for actions and all kinds of fields in the web client simply by filling the TooltipML property on the page object.\n\nNote: In NAV 2013 R2, tooltips (in the 1330-range pages only) are extracted from intro paragraphs in the related field topic and inserted build-time using an infrastructure system.\nTask-oriented page Help Every page in NAV 2013 R2 has a help icon in top right corner that should open a Task-oriented help topic that should be related to this page. We recommend providing help topics for new task pages that you provide with your solutions.\n\nNAV Usages Dismissible dialogs - Used in the Description field in pages 1305, 1325, 1355, 1373, ….\nFastTabs with instructional text Navigate page (344).\nHelp Tiles on Role Center Small Business Role Center page (9022) and Mini Activities page (1310).\nTooltips All pages in the 1300 number range.\nTask-oriented page help all task pages in 1300 number range\nIdeas for Improvement Provide the support for the invoking any Help topics (URL on the Help Server from C/AL code. Then we would be able to promote help actions anywhere or launch them from C/AL code if needed.\nImplement tooltips across the application and in all country versions. (Requires a run-time infrastructure system.)\n ","categories":"","description":"","excerpt":"Originally by Nikola Kukrika at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/instructions-in-the-ui/","tags":"","title":"Instructions in the UI"},{"body":" ","categories":"","description":"","excerpt":" ","ref":"/docs/navpatterns/patterns/integration-of-addresses/","tags":"","title":"Integration of Addresses"},{"body":"(Dynamics NAV 2015)\nDot Net Types\nmscorlib.System.Convert\nmscorlib.System.Globalization.CultureInfo\nmscorlib.System.Globalization.DateTimeStyles\nmscorlib.System.Globalization.NumberStyles\nmscorlib.System.Type\nmscorlib.System.Array\nmscorlib.System.EventArgs\nmscorlib.System.Security.Cryptography.SHA512Managed\nmscorlib.System.Security.Cryptography.HashAlgorithm\nmscorlib.System.Text.Encoding\nmscorlib.System.Text.UTF8Encoding\nmscorlib.System.Environment\nmscorlib.System.IO.Directory\nmscorlib.System.IO.Path\nmscorlib.System.IO.File\nmscorlib.System.IO.FileAttributes\nmscorlib.System.Collections.ArrayList\nmscorlib.System.Collections.IEnumerator\nmscorlib.System.Collections.Generic.IEnumerator`1\nmscorlib.System.TimeSpan\nmscorlib.System.DateTime\nmscorlib.System.DateTimeKind\nmscorlib.System.DateTimeOffset\nmscorlib.System.Decimal\nmscorlib.System.String\nSystem.System.Diagnostics.Process\nSystem.System.Diagnostics.ProcessStartInfo\nSystem.System.IO.Compression.CompressionMode\nSystem.System.IO.Compression.GZipStream\nSystem.System.Uri\nSystem.System.UriPartial\nSystem.Data.System.Data.DataColumn\nSystem.Data.System.Data.DataTable\nSystem.Data.System.Data.DataRow\nSystem.Web.System.Web.HttpUtility\nSystem.Windows.Forms.System.Windows.Forms.DialogResult\nSystem.Windows.Forms.System.Windows.Forms.FileDialog\nSystem.Windows.Forms.System.Windows.Forms.OpenFileDialog\nSystem.Windows.Forms.System.Windows.Forms.SaveFileDialog\nSystem.Windows.Forms.System.Windows.Forms.FolderBrowserDialog\nSystem.Xml.*\nDocumentFormat.OpenXml.*\nmscorlib.System.IO.DirectoryInfo\nmscorlib.System.IO.FileInfo\nMicrosoft.Dynamics.Nav.Client.CodeViewerTypes.Microsoft.Dynamics.Nav.Client.CodeViewerTypes.BreakpointCollection\nMicrosoft.Dynamics.Nav.Client.CodeViewerTypes.Microsoft.Dynamics.Nav.Client.CodeViewerTypes.VariableCollection\nMicrosoft.Dynamics.Nav.SMTP.Microsoft.Dynamics.Nav.SMTP.SmtpMessage\nMicrosoft.Dynamics.Nav.Management.DSObjectPickerWrapper.*\nMicrosoft.Dynamics.Nav.Timer.*\nMicrosoft.Dynamics.Nav.DO.ClientProxyWrapper.*\nMicrosoft.Dynamics.Nav.Client.BusinessChart.*\nMicrosoft.Dynamics.Nav.Client.BusinessChart.Model.*\nMicrosoft.Dynamics.Nav.Integration.Office.*\nMicrosoft.Dynamics.Nav.Integration.Office.Mock.*\nMicrosoft.Dynamics.Nav.EwsWrapper.*\nMicrosoft.Dynamics.Nav.EwsWrapper.ALTestHelper.*\nMicrosoft.Dynamics.NAV.OLSync.OLSyncSupplier.*\nMicrosoft.Dynamics.Nav.OLSync.Common.*\nMicrosoft.Dynamics.Nav.NavUserAccount.*\nMicrosoft.Dynamics.Nav.OpenXml.*\nMicrosoft.Dynamics.Nav.RapidStart.*\nMicrosoft.Dynamics.Framework.RapidStart.Common.*\nMicrosoft.Dynamics.Nav.Client.TimelineVisualization.Microsoft.Dynamics.Nav.Client.TimelineVisualization.\nVisualizationScenarios\nMicrosoft.Dynamics.Framework.UI.WinForms.DataVisualization.Timeline.Microsoft.Dynamics.Framework.UI.\nWinForms.DataVisualization.TimelineVisualization.DataModel+TransactionChangesRow\nMicrosoft.Dynamics.Framework.UI.WinForms.DataVisualization.Timeline.Microsoft.Dynamics.Framework.UI.\nWinForms.DataVisualization.TimelineVisualization.DataModel+TransactionChangesDataTable\nMicrosoft.Dynamics.Framework.UI.WinForms.DataVisualization.Timeline.Microsoft.Dynamics.Framework.UI.\nWinForms.DataVisualization.TimelineVisualization.DataModel+TransactionRow\nMicrosoft.Dynamics.Framework.UI.WinForms.DataVisualization.Timeline.Microsoft.Dynamics.Framework.UI.\nWinForms.DataVisualization.TimelineVisualization.DataModel+TransactionDataTable\nMicrosoft.Office.Interop.Word.*\nMicrosoft.Office.Interop.Excel.*\nMicrosoft.Dynamics.BAPIWrapper.*\nMicrosoft.Dynamics.Nav.Types.Microsoft.Dynamics.Nav.Types.ConfigSettings\nMicrosoft.Dynamics.Nav.DocumentService.*\nMicrosoft.Dynamics.Nav.DocumentService.Types.*\nmscorlib.System.IO.StreamWriter\nMicrosoft.Dynamics.Nav.Client.TimelineVisualization.Microsoft.Dynamics.Nav.Client.TimelineVisualization.\nInteractiveTimelineVisualizationAddIn\nSystem.System.ComponentModel.CancelEventArgs\nSystem.System.Text.RegularExpressions.Regex\nSystem.System.Text.RegularExpressions.RegexOptions\nmscorlib.System.IO.StreamReader\nSystem.Windows.Forms.System.Windows.Forms.Control\nSystem.Windows.Forms.System.Windows.Forms.ControlEventArgs\nSystem.Windows.Forms.System.Windows.Forms.DragEventArgs\nSystem.Windows.Forms.System.Windows.Forms.GiveFeedbackEventArgs\nSystem.Windows.Forms.System.Windows.Forms.HelpEventArgs\nSystem.Windows.Forms.System.Windows.Forms.InvalidateEventArgs\nSystem.Windows.Forms.System.Windows.Forms.KeyEventArgs\nSystem.Windows.Forms.System.Windows.Forms.KeyPressEventArgs\nSystem.Windows.Forms.System.Windows.Forms.LayoutEventArgs\nSystem.Windows.Forms.System.Windows.Forms.MouseEventArgs\nSystem.Windows.Forms.System.Windows.Forms.PaintEventArgs\nSystem.Windows.Forms.System.Windows.Forms.PreviewKeyDownEventArgs\nSystem.Windows.Forms.System.Windows.Forms.QueryAccessibilityHelpEventArgs\nSystem.Windows.Forms.System.Windows.Forms.UICuesEventArgs\n","categories":"","description":"","excerpt":"(Dynamics NAV 2015)\nDot Net Types\nmscorlib.System.Convert …","ref":"/docs/navpatterns/3-cal-coding-guidelines/internally-used-dot-net-types/","tags":"","title":"Internally used DotNet Types"},{"body":"C/AL Coding Guidelines Internationalization Find the C/AL guidelines by expanding the menu in the left.\n","categories":"","description":"","excerpt":"C/AL Coding Guidelines Internationalization Find the C/AL guidelines …","ref":"/docs/navpatterns/3-cal-coding-guidelines/internationalization/","tags":"","title":"Internationalization"},{"body":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract This pattern describes an optimized way to handle invalid, incomplete, or inconsistent data that users enter in journals.\nDescription Scenario: A user has entered data on a journal line and proceeds to invoke a processing action on it, such as posting or exporting to electronic payments. NAV validates the data before it is committed. If any validation errors are found, the user must be informed of validation errors in the most optimal way.\nOne design is that when an error is found, stop execution and prompt the user to correct the error. After correcting the error, the user restarts processing and is stopped again at the next error, and so on. Stopping and showing each error is time-consuming and frustrating for the user.\nAnother design is that processing does not stop when an error is found. Instead, all errors are gathered in a table and displayed all at once at the end of processing. This way, the processing is ideally invoked only once, reducing the time and effort spent by the user to expose and correct all data validation errors.\nIn both designs, the processing is not finalized if any errors are found (for example, exporting to electronic payments is not done, until the data error is resolved).\nThis document describes how to implement the second error-handling design: Showing all errors at the end.\nUsage The example below comes from the implementation of SEPA Credit Transfer.\nAfter setting up SEPA-specific configurations, the user can start entering vendor payments that will later be exported to the payment file. (The setup depends on the country, but generally involves choosing number series for SEPA export files, choosing the export format, and enabling SEPA Credit Transfer.)\nIn the W1 solution (and most of the countries), payment lines are created in the Payment Journal page, from where the user can invoke the Export Payments to File action, which will attempt to create a SEPA-compliant XML file containing the description of the journal payments that are to be made by the bank.\nWhen the Export Payments to File function is invoked, NAV validates the journal line data. If the data must be completed or updated, then no file will be created and the user sees the following message:\n\nTo give a visual overview, the lines that need corrections are highlighted in red. The factbox is context-sensitive, meaning that it shows only the errors that relate to the currently selected line.\nWhen the first payment journal line is selected, the FactBox show errors for the first line.\n\nWhen the second payment journal line is selected, the FactBox shows errors for the second line.\n\nApplication Objects In the following table, the Generic Object column contains the objects that you can use as a base for your implementation.\n Generic Object Description Sample W1 implementation of SEPA Credit Transfer Journal Page This is the journal list page where the user invokes the processing action. Payment Journal Action on Page The processing action invoked by the user on the journal list page. Export Payments to File Errors Page List Part A FactBox that displays any journal line validation errors. To improve user experience, the developer can highlight the lines with errors in red and conveniently sort the lines with errors at the top. Payment Journal Errors Part Validation codeunit Contains code that checks that the journal line contains correct, complete, and coherent data and that the line is ready for whatever process must be done next. SEPA CT-Check Line Processing codeunit Executes the processing of the journal lines. SEPA CT-Export File Generic Object: Journal Error Text Table\nDescription:\nContains:\n The error messages Link information about where the error messages belong. For example, in table 1228, Payment Jnl. Export Error Text, the error is linked uniquely to a journal line by the following fields: Journal Template Name, with TableRelation=“Gen. Journal Template” Journal Batch Name, with TableRelation=“Gen. Journal Batch”.Name WHERE (Journal Template Name=FIELD(Journal Template Name)) Journal Line No. Other related information can be added, such as document number of the original source document, if the current journal line originates from a document.\nAn extra improvement would be to add a drilldown or a link to the page where the user can fix the error. This would significantly simplify the scenario by excluding manual navigation and investigation by the user to find the page where the error can be fixed.\nSample W1 implementation of SEPA Credit Transfer: Payment Jnl. Export Error Text\n* The W1 implementation of file export for SEPA Credit Transfer contains the generic SEPA functionality. However, due to differences in data models and user scenarios in various country implementations, the selected local versions contain adaptations of the generic functionality.\nFlow Find below a diagram describing the flow between the objects involved in the journal error processing.\n\nCode Following the flow above, the code (in the SEPA Credit Transfer example) is as follows.\n\nThe public interface of this table contains simple functionality for adding/deleting errors and for interrogation on if any errors are associated with the current journal template and batch.\nCreateNew(GenJnlLine:Record\"Gen. Journal Line\";NewText:Text) SetLineFilters(GenJnlLine);IFFINDLASTTHEN;\"Journal Template Name\":=GenJnlLine.\"Journal Template Name\";\"Journal Batch Name\":=GenJnlLine.\"Journal Batch Name\";\"Document No.\":=GenJnlLine.\"Document No.\";\"Journal Line No.\":=GenJnlLine.\"Line No.\";\"Line No.\"+=1;\"Error Text\":=COPYSTR(NewText,1,MAXSTRLEN(\"Error Text\"));INSERT;JnlLineHasErrors(GenJnlLine:Record\"Gen. Journal Line\") :BooleanSetLineFilters(GenJnlLine);EXIT(NOTISEMPTY);JnlBatchHasErrors(GenJnlLine:Record\"Gen. Journal Line\") :BooleanSetBatchFilters(GenJnlLine);EXIT(NOTISEMPTY);DeleteJnlLineErrors(GenJnlLine:Record\"Gen. Journal Line\") IFJnlLineHasErrors(GenJnlLine) THENDELETEALL;DeleteJnlBatchErrors(GenJnlLine:Record\"Gen. Journal Line\") IFJnlBatchHasErrors(GenJnlLine) THENDELETEALL;NAV Usages SEPA Credit Transfer feature - for export of vendor payments\n SEPA Direct Debit feature for export of customer payment instructions\n The same concept of storing error messages (but with a different flow) is also present in:\n Planning Error Log table (5430) - Supply Planning feature\n Costing table (5890) - Costing feature\n Ideas for Improvement Older code in NAV does not use this pattern yet. It would be good for consistency reasons, and also for overall user experience, to extend this pattern to replace the error processing in more areas.\nWe can also improve by helping users find the place where they must fix the error by providing auto-navigation to the required page.\n","categories":"","description":"","excerpt":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/journal-error-processing/","tags":"","title":"Journal Error Processing"},{"body":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract The role of a journal line is to temporarily hold transaction data until the transaction is posted. Before posting, the entries are in a draft state, which means that they are available for corrections and/or deletion. As soon as the entries are posted, they are converted to ledger entries.\nJournal templates are used to specify the underlying journal structure and to provide the default information for the journal batches. Journal batches usually serve to group journal lines, such as lines created by two different users.\n\nDescription Journal templates and journal batches are used if there is a need to create and post one or more entries. They are implemented in multiple areas of the application, like Sales, Purchases, Cash Receipts, Payments, Fixed Assets1.\nJournal Templates The journal templates are located on the Journal Template page. A Journal Template definition contains a series of attributes, such as:\n Name Description Type Recurring No. Series The Journal Template table stores the relevant attributes that define the nature and behavior of the journal templates, for example:\n Journal Template Table Field Description Test Report ID The journals offer the possibility of running test reports3. The role of a test report is to simulate the posting process. The verification criteria for the journal lines is ran, and the report can be displayed, all without doing the actual posting. This helps finding and correcting any errors that might exist in the data. The name of the test report is the same with the name of the corresponding journal, plus the suffix \" - Test\". For example, the General Journal has the associated test report named General Journal - Test. Posting Report ID This report is printed when a user selects Post and Print4. Page ID For some journals, more UI objects are required. For example, the General Journals have a special page for bank and cash. Source Code Here you can enter a Trail Code for all the postings done through this Journal4. Recurring Whenever you post lines from a recurring journal, new lines are automatically created with a posting date defined in the recurring date formula. Each journal template defines a default value of those attributes. The values that are defined in a template will be inherited by the journal batches, which will be created from a journal template.\nMicrosoft Dynamics NAV is released with a number of standard journal templates predefined in the Journal Templates page. More templates can be defined by the users.\nJournal Batches Journal batches are created with the help of the journal templates.\nA journal batch is typically used to make a distinction between collections of logically grouped journal lines. A typical design is to have a journal batch for each user who enters lines. The batches are used during the posting process, in order to post one or multiple lines at once.\nJournal Lines Journal lines contain the actual business data (posting dates, account numbers, amounts) that will be posted as ledger entries.\nDuring posting, only the information from the journal lines is needed. However, the information has been created with the help of the journal templates and grouped together using the journal batches.\nPosting creates ledger entries from the temporary content that is stored in the journal lines. Ledger entries are not created directly. Instead, they are posted from journal lines.\n\nAggregation There is a 1:n aggregation relationship between journal templates and journal batches, as well as between journal batches and journal lines. Deleting a template will cascade deletion of the related batches and lines. Deleting a batch will cascade into deletion of related lines.\nRecurring Journals A recurring journal is used to post transactions that repeat periodically. In a recurring journal, the user enters only the variable data, such as posting date, amounts, and accounts to be used for posting.\nAfter posting a recurring journal, new journal lines are created containing the posting date for the next recurring period. The posting date recurrence pattern is previously defined in the Recurring Frequency field (for example, monthly recurrences are defined with the date formula 1M).\nA boolean field named Recurring is placed on both the journal templates and journal batches, giving the possibility of defining the type of the journal to be used.\nConsistent User Experience To keep a consistent user interface experience, it is recommended that the the following guidelines are taken respected concerning navigation:\n Journal template to journal batches:\n On the Journal Templates page, create an action called “Batches” and place it in the Navigate tab of the ribbon. Link the action to the batches list page.\n Journal batch to journal lines:\n On the Batch page, create an action called “Edit Journal” in the Home ribbon tab. Link the action to the journal lines list page.\n To keep a consistent user interface experience, it is recommended that the the following guidelines are taken respected concerning posting:\n Posting multiple batches\n On the Journal Batches page, posting actions (Post, Post and Print) are available. When invoked, the batch posting will iterate through all related journal lines and trigger the posting routine for all of the lines.\n Usage General Journals The General Journal Templates page (101) uses the Gen. Journal Template table (80).\nVarious template types are defined: General,Sales,Purchases,Cash Receipts,Payments,Assets,Intercompany,Jobs. Based on the journal type, two other attributes are automatically set on the template lines as follows:\n Page ID: Defines which journal page relates to the current journal template Source Code: Filled with the default codes that are defined in Source Code Setup table (242). The General Journals Batches page (251) is linked to the Gen. Journal Batch source table (232), which has a multiple-to-1 relationship with Gen. Journal Template table, based on the Journal Template Name field.\nSome of the fields in the Gen. Journal Batch table are not editable. Instead, their value is automatically calculated from the parent Gen. Journal Template table. For example, the Recurring field (22) is a FlowField with the following calculation formula:\nLookup(\"Gen. Journal Template\".RecurringWHERE(Name=FIELD(JournalTemplateName))) Similarly, the Template Type field is a FlowField that gets its value from the parent table:\nLookup(\"Gen. Journal Template\".TypeWHERE(Name=FIELD(JournalTemplateName))) Setting up a New Batch When the user creates a new batch, the following field values are transferred from the Gen. Journal Template table to the Gen. Journal Batch table:\n\"Bal. Account Type\":=GenJnlTemplate.\"Bal. Account Type\";\"Bal. Account No.\":=GenJnlTemplate.\"Bal. Account No.\";\"No. Series\":=GenJnlTemplate.\"No. Series\";\"Posting No. Series\":=GenJnlTemplate.\"Posting No. Series\";\"Reason Code\":=GenJnlTemplate.\"Reason Code\";\"Copy VAT Setup to Jnl. Lines\":=GenJnlTemplate.\"Copy VAT Setup to Jnl. Lines\";\"Allow VAT Difference\":=GenJnlTemplate.\"Allow VAT Difference\";Cascade record deletion When a record from the Gen. Journal Template table is deleted, the corresponding Gen. Journal Batch and Gen. Journal Line records are also deleted.\nCascade updates When the reason code or the posting number series change in the current batch, all linked Gen. Journal Line records are updated (see ModifyLines function on the Gen. Journal Batch table).\nThe Gen. Journal Line table (814) stores a relation with the Journal Batch Name field (51) in the Gen. Journal Batch table. The Gen. Journal Line table also inherits the table relation with the Journal Template Name field (1) in the Gen. Journal Template table.\nNAV Usages Implementations of this pattern in NAV include:\n General Journal (see “Use the Pattern” above) Item Journal Resource Journal Job Journal References\n NAV Course 50534 Finance Essentials in Microsoft Dynamics NAV 2013, Chapter 3: “General Journals”. NAV Course 50435 Application Setup in Microsoft Dynamics NAV 2013, Chapter 5: “Set up Journal Templates and Batches” Test reports Definition on MSDN. Microsoft Dynamics NAV 2009: Using the journals and entries in a custom application Blog article by Mark Brummel Search result for “Journal+NAV” Various topics on MSDN Related Pattern: Standard Journal For cases when most of the journal data can be used later (like monthly electricity payments, for example), the user has the possibility to save the current transaction details for later use. See the related pattern, Standard Journal.\n ","categories":"","description":"","excerpt":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/journal-template-batch-line/","tags":"","title":"Journal Template Batch Line"},{"body":"The IF..THEN pair, WHILE..DO pair, and FOR..DO pair must appear on the same line or the same level of indentation.\nBad code\nIF(x=y) AND(a=b) THENGood code\nIF(x=y) AND(a=b) THEN","categories":"","description":"","excerpt":"The IF..THEN pair, WHILE..DO pair, and FOR..DO pair must appear on the …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/keyword-pairs-indentation/","tags":"","title":"Keyword Pairs - Indentation"},{"body":"The END, IF, REPEAT, FOR, WHILE, ELSE and CASE statement should always start a line.\nBad code\nIFIsContactNameTHENValidateContactNameELSEIFIsSalespersonCodeTHENValidateSalespersonCodeELSEIFIsSalesCycleCodeTHENValidatSalesCycleCode;Good code\nIFIsContactNameTHENValidateContactNameELSEIFIsSalespersonCodeTHENValidateSalespersonCodeELSEIFIsSalesCycleCodeTHENValidatSalesCycleCode;","categories":"","description":"","excerpt":"The END, IF, REPEAT, FOR, WHILE, ELSE and CASE statement should always …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/line-start-keywords/","tags":"","title":"Line Start Keywords"},{"body":"C/AL Coding Guidelines Localizability Find the C/AL guidelines by expanding the menu in the left.\n","categories":"","description":"","excerpt":"C/AL Coding Guidelines Localizability Find the C/AL guidelines by …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/","tags":"","title":"Localizability"},{"body":"The REPEAT statement should always be alone on a line.\nBad code\nIFReservEntry.FINDSETTHENREPEATGood code\nIFReservEntry.FINDSETTHENREPEAT","categories":"","description":"","excerpt":"The REPEAT statement should always be alone on a line.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/lonely-repeat/","tags":"","title":"Lonely Repeat"},{"body":"Maintainability Index: Do not write functions that have a very low maintainability index. This makes the code hard to maintain.\nBad code\nAny procedure / trigger that has a maintainability index \u003c 20 Good code\nAny procedure / trigger that has a maintainability index \u003e= 20\\. The Maintainability Index is computed as a function: - Lines Of Code (inverse proportional) - the Halstead Volume - Cyclomatic Complexity (inverse proportional). More info\n Halstead Volume Cyclomatic Complexity Bad code\nAny procedure / trigger that is \u003e 100 lines of code Good code\nAny procedure / trigger that is \u003c= 100 lines of code. A full C/AL Statement counts as 1 line of code ","categories":"","description":"","excerpt":"Maintainability Index: Do not write functions that have a very low …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/maintainability-index/","tags":"","title":"Maintainability Index"},{"body":"By Soren Klemmensen, Partner-Ready-Software \u0026 360 Visibility\nAbstract The goal of this design pattern is to outline a standard way of creating master data, such as customers, vendors or items, in NAV.\nDescription This pattern creates a standard master data entity, listing all necessary prerequisites, attributes and methods to generate a basic version of the data entity.\nIt is being used for creating a master data entity and can roughly be divided into 2 categories: Business and Product\nExamples of Master Data tables are:\nBusiness Data:\n Table 18: Customer Table 23: Vendor Table 270: Bank Account Table 5050: Contact Product Data:\n Table 15 G/L Account Table 27: Item Table 156: Resource Table 5600: Fixed Asset Table 5718: Nonstock Item Table 5913: Loaner Master Data has attributes such as Location, Countries \u0026 Item Vendors. These tables are closely related to Master Data tables and are called Supplemental and Subsidiary tables.\nSupplemental:\n Table 9: Country/Region Table 14: Location Subsidiary:\n Table 99: Item Vendor Master Data is among other used in journals, posting routines and historic data like ledger entries.\nNaming \u0026 Conventions\nTable \u0026 Card Page\n Singular\n Examples: Customer, Vendor \u0026 Item\n List Page\n Plural if Editable = TRUE.\n Singular + “List” if Editable = FALSE.\n Example The data entity has a single primary key field with the following properties:\n Field No. 1 Name “No.” Date Type Code 20 Each master data entity has a field which gives a name tag to the data entity carrying the natural name of the entity. This field is called Name if the data entity refers to a living person or an organization, such as a customer or a vendor; it is called Description instead if the data entity does not refer to a person or organization, such as an item. The field has the following properties:\n Name Name or Description Date Type Text 50 An added benefit of using the Name or Description field naming is that this will be part of the dropdown when looking up based on the table relation.\nThe table properties of a master data table contain the following entries:\n LookupPageID A ListType Page referring to the table which is not editable. DrillDownPageID The same page as defined in the LookupPageID DataCaptionFields The primary key plus the field which provides the primary name tag for the record. This will typically be the Name or Description field defined earlier. NAV Specific Example We will create an Example table here with a Card and List Page as described above.\nFirst we create the Table with No. as the primary key.\n\nThan we create a non-editable Page called Example List\n\nThan we create an Example Card Page with the following definition\n\nNow we can set the properties of the 2 pages.\nFirst the Example Card Page Properties\n\nThan the Example List Page Properties\n\nLast but not least we set the Table Properties\n\nNAV Usages You can see this pattern used in the following tables \u0026 pages:\nBusiness Data:\n Table 18: Customer, Page 21 Customer Card \u0026 Page 22 Customer List Table 23: Vendor, Page 26 Vendor Card \u0026 Page 27 Vendor List Table 270: Bank Account, Page 370 Bank Account Card \u0026 Page 371 Bank Account List Table 5050: Contact, Page 5050 Contact Card \u0026 Page 5052 Contact List Product Data:\n Table 15 G/L Account, Page 17 G/L Account Card \u0026 Page 18 G/L Account List Table 27: Item, Page 30 Item Card \u0026 Page 31 Item List Table 156: Resource, Page 76 Resource Card \u0026 Page 77 Resource List Table 5600: Fixed Asset, Page 5600 Fixed Asset Card \u0026 Page 5601 Fixed Asset List Table 5718: Nonstock Item, Page 5725 Nonstock Item Card \u0026 Page 5726 Nonstock Item List Table 5913: Loaner, Page 5922 Loaner Card \u0026 Page 5923 Loaner List Consequences This pattern should not be used when this is not Master Data.\nReferences Patterns that are typically used in connection with the Master Data Pattern could be the “No. Series”, “Address Integration” and/or the “Entity State” design patterns., Master Data are central to almost everything we do, so most patterns connect in one way or another to the Master Data Pattern.\n","categories":"","description":"","excerpt":"By Soren Klemmensen, Partner-Ready-Software \u0026 360 Visibility\nAbstract …","ref":"/docs/navpatterns/patterns/master-data/","tags":"","title":"Master Data"},{"body":"Always end MESSAGE or ERROR with a period.\nBad code\nCustIsBlockedErr@1025:TextConst'ENU=You cannot %1 this type of document when Customer %2 is blocked with type %3';... ERROR(CustIsBlockedErr,...);Good code\nCustIsBlockedErr@1025:TextConst'ENU=You cannot %1 this type of document when Customer %2 is blocked with type %3.';... ERROR(CustIsBlockedErr,...);","categories":"","description":"","excerpt":"Always end MESSAGE or ERROR with a period.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/ux/message-and-error/","tags":"","title":"MESSAGE and ERROR"},{"body":"By Martin Dam at Microsoft Development Center Copenhagen\nAbstract The goal of this pattern is to enable the users to download multiple files as a zip file instead of downloading one by one. On the Web Client this is preferred way of delivering multiple files since it is one of the web patterns and we cannot use File Management code unit to place files silently on the machine.\nDescription When generating reports that consists of multiple, and usually an unknown number of files, the developer will have to handle the download which also depends on the client the user is on. The problem is that the WinClient has access to the users file system, whereas the web client does not. Following web guidelines, and the fact that client side .NET is not available in Web client, you cant initiate multiple downloads which requires the developer respond to the type of client. In some browsers it is possible to download files one-by-one in the Web client by using a confirm dialog, however this is a hack and should not be used.\nTo solve this problem, a generic download mechanism is used that is client dependent event when multiple files need to be downloaded. For Web client the files are compressed using ZIP and for WinClient the files are downloaded directly to the file system.\nThe pattern is usable for all objects that output multiple files and is available in both WinClient and Web client.\nUsage The pattern consists of two steps: 1) Gathering the files and 2) downloading the file(s)\nFor first step consists of a loop that goes through the files that needs to be downloaded. If it is on the Web client, the files are added to a ZIP archive server-side using a naming convention defined by the integration function GetSeriesFileName. This function takes a filename and number, and transforms it to unique names following a meaningful deterministic pattern e.g. prepend an integer before the file extension. The same function is used when the temporary files are created server side, so the files can be found deterministically later. This removes the need for storing filenames and consequently allows an arbitrary number of files. The second integration function: GetTotalNumberOfFiles, returns the total number of files generated during the data processing and makes the pattern able to handle an arbitrary number of files.\nThe second step is the actually download of file(s). For the Web client this consists of closing the ZIP achieve and downloading via the standard download handler that works in the Web client. For the Win client, the files are saved directly to the client during the first step.\nCode 1: File loop shows an example implementation of this pattern. ServerFileName is generated at the beginning of the report/codeunit, and is the base for GetSeriesFilename. The file that is actually written to during data processing is stored in another variable which holds the output from GetSeriesFilename on the current file number. Note; the example code will only create a ZIP file if there in fact are multiple files to be downloaded.\nIFFileName=''THENERROR(SupplyFileNameErr);IFZipMultipleFilesAND(GetTotalNumberOfFiles\\\u003e1) ANDFileManagement.IsWebClientTHENBEGINBasename:=FileManagement.GetFileName(FileName);ZipFileName:=FileManagement.CreateZipArchiveObject;FORFileNo:=1TOGetTotalNumberOfFilesDOFileManagement.AddFileToZipArchive( GetSeriesFilename(ServerFileName,FileNo),GetSeriesFilename(Basename,FileNo));FileManagement.DownloadHandler(ZipFileName,'','','',STRSUBSTNO('%1.zip',FileManagement.GetFileNameWithoutExtension(FileName))) ENDELSEBEGINIFFileManagement.IsWebClientTHENBEGINIFGetTotalNumberOfFile\u003e1THENERROR(MultipleFilesWebClientErr);FileManagementDownloadHandler(GetSeriesFilename(ServerFileName,1),'','','',FileManagement.GetFileName(FileName));ENDELSEFORFileNo:=1TOGetTotalNumberOfFilesDOFileManagement.DownloadToFile(GetSeriesFilieName(ServerFileName,FileNo),GetSeriesFilename(FileName,FileNo));END;Code 1: File loop\nThe following code is an example implementation of the GetSeriesFilename function. It needs to support the case where no directory is given, only a filename, in order to add files to the root of the ZIP archive. The example will add a file number right before the extension, e.g. C:\\directory\\file.txt will become C:\\directory\\file1.txt etc.\nLOCALGetSeriesFilename(FileName:Text;FileNo:Integer) :TextIFSTRPOS(FileName,'\\\\') \u003c\u003e0THENDirectory:=FileMgt.GetDirectoryName(FileName) +'\\\\';EXIT(Directory+FileMgt.GetFileNameWithoutExtension(FileName) +FORMAT(FileNo) +'.'+FileMgt.GetExtension(FileName));Code 2: GetSeriesFilename The pattern depends on .NET library System.IO.Compression.ZipFile, which from NAV 2015 is implemented in Codeunit 419 (File management). It consists of three functions:\n CreateZipArchiveObject: Which creates a System.IO.Compression.ZipArchive on a server side file AddFileToZipArchive: Which adds a server side file to the archive using System.IO.Compression.ZipFileExtensions.CreateEntryFromFile(). This function allows to use arbitrary naming and does not require to create a server directory before creating the ZIP achieve. CloseZipArchive: Which simply closes the ZIP file and saves it to disk. The pattern is integrated into the report/codeunit in question by providing a filename field on the request page if it is on WinClient but hidden if it is in Web client. On the Web client, a meaningful default filename is used for the file to download, e.g. in Code 1, Filename is set by the user on the request page if it is WinClient, and set to a default value in Web client.\nNAV Usages This pattern is used by VAT Report and Blacklist communication in the Italian localization in NAV 2015. The ZIP archive functions are available on all localization from NAV 2015.\nConsequences This pattern can be used whenever you need to ZIP one or more files. The above example downloads the file, but it could have been transmitted, saved to a persistent storage etc. It could also be used to improve download speed between server and client where the WinClient would unzip the files locally and save individually to disk. This follows the normal procedure in NAV in the WinClient, which is to download files directly to disk, so a ZIP file should only be created when the user specifically needs it or the Web client is invoking the report/codeunit.\nRelated Topics File Management\nReferences System.IO.Compression.ZipFile\n","categories":"","description":"","excerpt":"By Martin Dam at Microsoft Development Center Copenhagen\nAbstract The …","ref":"/docs/navpatterns/patterns/multi-file-download/","tags":"","title":"Multi-file Download"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract This pattern describes how to open a related document (or card) page from a list page, for the case when there can be more than one pages associated to the rows of the list page.\nDescription The example below illustrates the connection of a List Page with multiple Document Pages, while the second example links the List Page with Card Pages.\n\nThe records contained in a list page have an associated page, which is specified in the CardPageID property of the list page. The NAV infrastructure assures the following scenarios are in place, without the need to add any explicit C/AL code:\n From the selected record in the list page, the user can double-click in order to open the related card page. The “Edit” action is available on the ribbon as well as in the right-click context menu of the list page rows. Invoking this action, opens the related card page. However, there are situations when rows of the list page can correspond to different pages each (either cards or documents). For example, consider a list page containing 3 rows, requiring the following behaviour:\n Row1 Opens page ID 1 Row2 Opens page ID 2 Row3 Opens page ID 3 This situation is not handled automatically by NAV. There is no possibility to specify more than one CardPageID in the list page properties. Furthermore, there is no possibility to specify one or more document page IDs on the list page. Therefore, those cases need to be handled explicitly by the C/AL developer.\nUsage The solution used in NAV implementations is at the list page level, as following:\n The property CardPageID of the list page remains undefined.\n An action named “Show Document” or “Card” is created on the Navigate tab, with the properties:\n Image = EditLines Promoted = Yes ShortCutKey = Shift+F7 The OnAction trigger for the Card action, contains explicit logic to run the targeted card page. It can, for example, be a CASE statement, which invokes PAGE.RUN(…) based on an enumeration field of the current row.\n NAV Specific Example For example, the NAV page Sales List (page ID 45), which displays the Sales Header Table (table ID 36), chooses which card to open, based on the Document Type field. This is an option field, which can have the following values: Quote, Order, Invoice, Credit Memo, Blanket Order, Return Order. For each document type, the related card page must be opened.\n\nFor this purpose, a new action (“Card”) is added to the Sales List page. The OnAction trigger of this new action contains the page selection logic:\nCASE\"Document Type\"OF\"Document Type\"::Quote:PAGE.RUN(PAGE::\"Sales Quote\",Rec);\"Document Type\"::Order:PAGE.RUN(PAGE::\"Sales Order\",Rec);\"Document Type\"::Invoice:PAGE.RUN(PAGE::\"Sales Invoice\",Rec);\"Document Type\"::\"Return Order\":PAGE.RUN(PAGE::\"Sales Return Order\",Rec);\"Document Type\"::\"Credit Memo\":PAGE.RUN(PAGE::\"Sales Credit Memo\",Rec);\"Document Type\"::\"Blanket Order\":PAGE.RUN(PAGE::\"Blanket Sales Order\",Rec);END;NAV Usages Some of the NAV implementations of this pattern can be found in the following pages:\n Sales List (45) and Sales List Archive (5159) Purchase List (53) and Purchase List Archive (5166) Available - Sales Lines (499) Sales Lines (516) Purchase Lines (518) ","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/multi-page-list/","tags":"","title":"Multi-Page List"},{"body":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen\nAbstract Generally, NAV translation refers to the translation of UI elements like captions and user texts (messages on dialogs, warnings, error messages). This translation is done by the Microsoft Dynamics NAV team before releasing the localized version of the product.\nBut there is one more scenario. In this scenario, Cronus International Ltd., wants to sell a “Fiets” to a Dutch customer, a\"Cykel\" to a Danish one, and a “Bicicletta” to an Italian customer. All 3 are the same inventory item - and its default name is “Bicycle”. But for reporting, Cronus International Ltd. wants to use the customer language preferences for translating the bicycles name.\nSometimes theres a need to support multiple languages for domestic transactions, too. For example, Switzerland has 4 official languages: German, French, Italian and Romansh, the first 3 of them being supported by NAV.\nDescription The example below uses the Item Translation feature of NAV, however, implementations of the same pattern exist for other application areas.\nHow to use the pattern Enter translations for “Bicycle”\nIn the Windows client, on the bicycle Item card, on the Home ribbon tab, choose Translations.\n\nOn the opened page, enter the Danish (language code DAN), the Italian (ITA), and the Dutch (NLD) translations for “Bicycle”.\n\nSet the desired language for the Dutch, Danish, and Italian customers\nOn the customer card for your 3 customers, in the Foreign Trade FastTab, choose the preferred language for each customer. If no language is specified, then the default item description will be used for items sold or anyhow associated to that customer. If for example, the DAN (Danish) language is specified for the customer, and the “Bicycle” has a translation in Danish, then this translation “Cykel” will be used instead of the default name “Bicycle”.\n\nSee the result\nAfter those changes, when the customer (in this case the Danish “Lauritzen Kontormøbler A/S”) transactions a bicycle, the translated description “Cykel” will be displayed on the documents and reports. For example, creating a sales order for this customer with 1 item No. 1000, shows:\n\nUsage Create the translation table\nNamed “\u003cEntity\u003e Translation” table, where \u003cEntity\u003e is replaced with the name of the actual object being translated. For the Item example above, this table will be named “Item Translation”.\nThe table definition contains at a minimum:\n Field Description Entity ID field For example, Item No. Language Code Identifies the language of this translation string (for example, “DAN” (Danish), “BGR”(Bulgarian). This is one of the language codes defined in the Languages table. Translation The translated string. The table above has a key composed of the first two fields.\nCreate the user interface for entering new translations of \u003cEntity\u003e\n Create a Translations page to present the table created above On the Entity card - add a Translations menu option which will open the Translations page NAV Usages Some of the NAV implementations of this pattern are:\n Item Translation Payment Term Translation Shipment Method Translation Unit of Measure Translation Related Topics The Extended Text pattern is a more powerful version of the Multilanguage application data pattern presented in this section. The main differences are:\n Pattern Multilanguage Application Data Extended Text Supports translation of application data Yes Yes Format Single- or multi-line Single-line Applies to document type Can choose which document types are affected. All document types are affected. ","categories":"","description":"","excerpt":"Originally by Bogdana Botez at Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/multilanguage-application-data/","tags":"","title":"Multilanguage Application Data"},{"body":"When calling an object statically use the name, not the number\nBad code\nPAGE.RUNMODAL(525,SalesShptLine) Good code\nPAGE.RUNMODAL(PAGE::\"Posted Sales Shipment Lines\",SalesShptLine) ","categories":"","description":"","excerpt":"When calling an object statically use the name, not the number\nBad …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/named-invocations/","tags":"","title":"Named Invocations"},{"body":"Anti-Patterns in NAV Upgrade By Carlos Raul Garcia and Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: when NAV is upgraded, whether on-premises or in the cloud, developers have the chance to write upgrade code to move data across changing data structures. Writing good quality code will help successful upgrades.\nGeneral on upgrade Problem: assuming that the upgrade table contains data.\nIf the table is empty, it means that either the upgrade has run, or there was no data in the original tenant; in both cases, the upgrade code should exit immediately.\nSolution: if using an upgrade table, always validate that the table contains data before doing anything.\nUpgrade code, can it be rerun safely? Problem: if the upgrade code is not written in a way that makes it runnable twice (idempotent), then several failures can happen, including something as critical as data corruption.\nIn on premise NAV installations, if something fails at upgrade, there is no way to run only the “remaining” tasks. You will need to run the whole upgrade again, and might end-up with data that you cannot trust.\nWhat about the cloud? In Platform As A Service (PaaS), in some situations, the upgrade code needs to be run twice (for example, when moving tenants from a broken/frozen VM to a healthy one).\nSolution: Make sure each of your upgrade procedures only kicks in if it didnt run before.\nExamples\nThe examples below have happened in real live NAV PaaS upgrade:\nTable data overwrite\n Problem: at upgrade, a new column has bee­n added to a table and initialized with default values. In the meanwhile, during production, some of the default values are changed to production real life values. The second time the upgrade runs, those values will be overwritten with defaults, any personalization lost. Solution: before initializing with default values, check if non-default values exist. Crash on math operations\n Problem: one tenant upgrade managed to divide by zero, by assuming a non-zero value. Solution: dont assume values can never be zero, always check before using them in divisions. Use of external components\n Problem: a one-time registration through web services to an external service failed when attempting to register a second time. Solution: check if already registered, before attempting again. Parallelism Problem: Upgrade procedures can be run in parallel, causing issues when different procedures attempt to modify the same table at the same time.\nWhen modifications to the same table are being made from two or more different procedures, there is no guarantee on sequential run, or on a certain order they will be run in.\nSolution: if sequential or ordered execution is needed, make the affected upgrade procedures local and call them all, in the desired sequence, from a public upgrade procedure.\nAccess to cloud machines Problem: dependencies on manual installation steps do not fit in the cloud.\nIf Dynamics NAV is installed on-premises, then any additional setup (like dependencies of external dlls, manual configuration steps etc.) can be done manually or semi-manually by the IT admin, at first setup and upgrade.\nIn the cloud, NAV partners dont have access to the machines hence they cannot deploy and configure those external dependencies as they did in the old on-premises installations.\nSolution: Dont assume you will have access to PaaS or SaaS machines. Build your solution in such a way that it doesnt depend on executing manual configurations on the host machine.\n","categories":"","description":"","excerpt":"Anti-Patterns in NAV Upgrade By Carlos Raul Garcia and Bogdana Botez …","ref":"/docs/navpatterns/2-anti-patterns/nav-upgrade/","tags":"","title":"Nav Upgrade"},{"body":"Do not nest WITHs that reference different types of objects.\nBad code\nWITHPostedWhseShptLineDOBEGIN... WITHItemLedgEntryDOInsertBufferRec(...,\"Serial No.\",\"Lot No.\",...);... END;Good code\nWITHPostedWhseShptLineDOBEGIN... InsertBufferRec(...,ItemLedgEntry.\"Serial No.\",ItemLedgEntry.\"Lot No.\",...);... END;","categories":"","description":"","excerpt":"Do not nest WITHs that reference different types of objects.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/nested-withs/","tags":"","title":"Nested WITHs"},{"body":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen\nAbstract When there is a need to use .NET classes within C/AL, one of the main challenges is to handle the exceptions the methods of these .NET classes may throw. Eventually, if not handled, they will basically bubble up as runtime errors, halting the current operation a user is doing without having a chance to properly display errors in a user-friendly format.\nDescription Using the .NET classes in order to extend NAVs functionality usually triggers the need to create an add-on assembly. This is a pretty powerful approach and opens the door for empowering NAV with new and extra functionality while harnessing the full power of .NET.\nFor example, integration with a Web service into NAV can be done to extend NAVs functionality or benefit from a service model offered through a 3rd party. To do so, it is possible to write a .NET add-in to handle the required bi-directional communication between NAV and the Web service. Alternatively, the implementation itself can be done in C/AL, with no add-in dependency. The latter option simplifies customization, deployment and upgradeability. Additionally, it builds up on the knowledge NAV developers have with C/AL programming.\nOn the other hand, not using an add-in exposes NAV to runtime errors due to unhandled exceptions that get thrown at different levels. The first is the communication layer, in which HTTP requests and responses are exchanged. The second is the business logic layer, at which the content of the requests and response is being prepared and groomed using XML Elements and being retrieved or edited based on the respective XPaths.\nWhen to Use It When .NET classes are used, they may throw exceptions upon failure. Some of these exceptions cannot pre-checked (e.g. like existence of a file on disk) and will only be figured out at runtime. Eventually, to present the error reason to a user and explain what needs to be done to address it, the exception needs to be handled gracefully. This also protects the client for unexpected crashes that may deteriorate the user experience.\nDiagram \nUsage A Try-Catch-Finally statement does not exist in C/AL. The alternative is to run the code consuming .NET objects within a codeunit, and handle the runtime errors, as follows:\n Write the code that uses the .NET classes in a codeunit. Run the codeunit using CODEUNIT.RUN or the Run function on a codeunit variable. Handle the return value of the OnRun trigger for the codeunit within an IF statement. Write the exception handling code in a function, and call it when the return value for OnRun is FALSE. The exception handling function should determine which exception to handle, and pass this over to COD1291 DotNet Exception Handler codeunit. When an exception is thrown, it is already wrapped up within an NAV exception. This means the real exception to look for is retrievable through the InnerException property of the NAV exception. Then, next step would be to properly determine the type of that exception, and act accordingly. The COD1291 DotNet Exception Handler codeunit takes care of looping through the nested levels of inner exceptions, digging for an exception with the expected type. If found, it is retrieved; otherwise, the main (outer) exceptions message is retrieved.\nNAV Specific Example Overview The exception handling pattern is implemented in the integration with a web service for bank file format conversion. Within the respective “External Data Handling Codeunit” for that web service, communication through SOAP requests is required. Eventually, the HTTP web request and response .NET classes are used for that purpose.\nFor instance, if a failure to establish a connection to the web service due to lack of Internet access, a WebException is thrown with the relevant error details. COD1290 Web Service Mgt. codeunit wraps up the required functionality to interact with a web service in C/AL, handling all the required plumping work to send web requests, receive web responses, and extract valid and error details from the web response.\nCode Sample The “External Data Handling Codeunit” is a consumer of COD1290 Web Service Mgt. codeunit. If a runtime exception occurs, it gets handled as follows:\nLOCALPROCEDURESendDataToConversionService@1(VARPaymentFileTempBlob@1003:Record99008535;BodyTempBlob@1004:Record99008535;PostingExch@1007:Record1220);VARBankDataConvServiceSetup@1000:Record1260;WebServiceRequestMgt@1001:Codeunit1290;BodyInStream@1005:InStream;ResponseInStream@1002:InStream;BEGINIFNOTBodyTempBlob.Blob.HASVALUETHENERROR(NoRequestBodyErr);PrepareSOAPRequestBody(BodyTempBlob);COMMIT;BankDataConvServiceSetup.GET;BodyTempBlob.Blob.CREATEINSTREAM(BodyInStream);WebServiceRequestMgt.SetGlobals(BodyInStream,BankDataConvServiceSetup.\"Service URL\",BankDataConvServiceSetup.\"User Name\",BankDataConvServiceSetup.GetPassword);IFNOTWebServiceRequestMgt.RUNTHENWebServiceRequestMgt.ProcessFaultResponse;WebServiceRequestMgt.GetResponseContent(ResponseInStream);CheckIfErrorsOccurred(ResponseInStream,PostingExch);ReadContentFromResponse(PaymentFileTempBlob,ResponseInStream);END;PROCEDUREProcessFaultResponse@15();VARXMLDOMMgt@1006:Codeunit6224;DotNetExceptionHandler@1000:Codeunit1291;WebException@1005:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.WebException\";WebExceptionStatus@1004:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.WebExceptionStatus\";XmlDoc@1003:DotNet\"'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument\";HttpWebResponseError@1007:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpWebResponse\";HttpStatusCode@1008:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpStatusCode\";ResponseInputStream@1002:InStream;BEGINDotNetExceptionHandler.Collect;IFNOTDotNetExceptionHandler.CastToType(WebException,GETDOTNETTYPE(WebException)) THENDotNetExceptionHandler.Rethrow;IFNOTWebException.Status.Equals(WebExceptionStatus.ProtocolError) THENERROR(WebException.Message);ResponseInputStream:=WebException.Response.GetResponseStream;DebugLogStreamToTempFile(ResponseInputStream,'WebExceptionResponse',TempDebugLogTempBlob);HttpWebResponseError:=WebException.Response;IFNOT(HttpWebResponseError.StatusCode.Equals(HttpStatusCode.Found) ORHttpWebResponseError.StatusCode.Equals(HttpStatusCode.InternalServerError)) THENERROR(WebException.Message);XmlDoc:=XmlDoc.XmlDocument;XmlDoc.Load(ResponseInputStream);ERROR(XMLDOMMgt.FindNodeTextWithNamespace(XmlDoc.DocumentElement,FaultStringXmlPathTxt,'soap',SoapNamespaceTxt));END;OBJECTCodeunit1291DotNetExceptionHandler{OBJECT-PROPERTIES{Date=;Time=;VersionList=;}PROPERTIES{OnRun=BEGINEND;}CODE{VAROuterException@1000:DotNet\"'mscorlib'.System.Exception\";PROCEDURECatch@3(VARException@1002:DotNet\"'mscorlib'.System.FormatException\";Type@1007:DotNet\"'mscorlib'.System.Type\");BEGINCollect;IFNOTCastToType(Exception,Type) THENRethrow;END;PROCEDURECollect@1();BEGINOuterException:=GETLASTERROROBJECT;END;PROCEDURETryCastToType@5(Type@1000:DotNet\"'mscorlib'.System.Type\") :Boolean;VARException@1001:DotNet\"'mscorlib'.System.FormatException\";BEGINEXIT(CastToType(Exception,Type));END;PROCEDURECastToType@2(VARException@1002:DotNet\"'mscorlib'.System.FormatException\";Type@1007:DotNet\"'mscorlib'.System.Type\") :Boolean;BEGINException:=OuterException;REPEATIFType.Equals(Exception.GetType()) THENEXIT(TRUE);Exception:=Exception.InnerException;UNTILISNULL(Exception);EXIT(FALSE);END;PROCEDURERethrow@4();BEGINIFNOTISNULL(OuterException.InnerException) THENERROR(OuterException.InnerException.Message);ERROR(OuterException.Message);END;BEGINEND. }}NAV Usages The DotNet Exception Handler codeunit has been used for the Web service integration required for:\n Payment Export from the Payment Journal for creating bank-specific payment files. Bank Statement Import on the Bank Acc. Reconciliation card for importing the content of bank-specific statements. 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 Extend the language support in C/AL to provide a built-in Try-Catch-Finally statement, similar to .NET languages.\nConsequences When this pattern should not be used: avoid nesting of codeunits. To properly handle the exceptions, you need to use the codeunit as an atomic piece of functionality that may pass or fail without using Codeunit.Run internally.\n","categories":"","description":"","excerpt":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/net-exception-handling-in-cal/","tags":"","title":"NET Exception Handling in CAL"},{"body":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract Number series assignment is widely used in Microsoft Dynamics NAV to automatically assign unique numbers to data entries.\nDescription Documents and entities of any type (invoices, orders, customers, inventory items etc) are usually assigned an unique number, which can be later referenced whenever that particular entry needs to be consulted. When a new data entry is created, NAV implements the possibility to auto-assign a new number for this entry. For example, whenever a new sales order is created, it can be auto-numbered. This number has a specific format which is set up previously by the NAV administrator. For example, sales orders could have numbers between SO00001 and SO99999. When all the numbers in this series have been used, NAV will show an error and the administrator has to either extend the current number series, or create a new series to be used.\nUsage The number series is implemented at the table level. Each time a new record is inserted, the user can either:\n type a new number (if allowed by the setup), or have an auto-generated number created. Number Series definition From the implementation point of view, a number series is a record in the table 308 - “No. Series”.\n\nThe most relevant fields are:\n Code Code 10 Used to identify the number series in further places where it will be used. Default Nos. Boolean The boolean Default Nos. decides whether this number series can use automatic numbering. If false, then the user is expected to manually look up the No. field and select it from the number series. Manual Nos. Boolean If the Manual Nos. is Yes, then the used will be allowed to manually type the value of the next number (“No.\") field. Date Order Boolean Date Order is used to decide whether or not the numbers from the range are assigned chronologically. Number Series sequence The sequence definition is found in table 309 - No. Series Line. Contains the explicit definition of the series, for example a series called BANK, could start with BANK001 and increase incrementally by one, in the sequence BANK001, BANK002, BANK003, …. Until the last number BANK999. When hitting the number BANK990, the user will receive a warning that the series is about to be exhausted and it must either be increased, or a new series should be assigned.\n\n\nThe most relevant fields are:\n Series Code Code 10 Links it to the number series defined in table 308. Starting No. Integer This is the first number in the sequence, for a book indexing application it can be BOOK0001. Ending No. Integer The last number in the sequence, for example BOOK5000. Warning No. Integer When this number is reached, the user will see a warning message stating that the number series is running out of assignable numbers. Increment-by No. Integer The value for incrementing the numeric part of the series. Last No. Used Code 20 The last number from the sequence that was assigned. Last Date Used Date Stating when the last number was assigned. Add the default number series to the setup Various series of numbers can be defined as seen above. For example, a library can have a number series for indexing rental of each of the following: books, movies, music, video. The books series can be split by domain, for example a series BOOKSCIFI can have BOOK0001…BOOK1500, then BOOKTECH can use the sequence BOOK1501…BOOK4000 and so on.\nThe default number series for a certain application area is typically stored in the domain setup table. For example, NAV Demo Database stores the default Item number series in the Inventory Setup table 313. This means that you will need to add the Number Series fields in your setup table and ensure that before the customer starts using the solution, the number series is created and added to the setup defaults.\nHow to use the Number Series The table which will host the number from the number series, needs the following fields:\n No. Code 20 Contains the auto-generated sequential number. No. Series Code 10 The number series definition, which decides what the next No. will be. And the code to make the number series alive:\nOnInsert\nOnInsert() IF\"No.\"=''THENNoSeriesMgt.InitSeries(DefaultNoSeriesCode,OldNoSeriesCode,NewDate,NewNo,NewNoSeriesCode);Field “No.\"\nNo. -OnValidate() IF\"No.\"\u003c\u003exRec.\"No.\"THENBEGIN// Validate that \"No.\" corresponds to the current No. Series rules NoSeriesMgt.TestManual(DefaultNoSeriesCode);\"No. Series\":='';END;AssistEdit\nAssistEdit() :BooleanIF\"No.\"=''THENNoSeriesMgt.InitSeries(DefaultNoSeriesCode,OldNoSeriesCode,NewDate,NewNo,NewNoSeriesCode);Where:\n DefaultNoSeriesCode is typically found in the application domain setup table. OldNoSeriesCode is typically the previous value of the “No. Series” code, which is found in xRec.“No. Series” NewDate is typically 0D (empty date) NewNo and NewNoSeriesCode are the current values found in “No.\" and “No. Series” NAV Usages See below an example of how NAV implements the number series pattern.\nSales and Receivables The setup table 311 (Sales \u0026 Receivables Setup) contains the default number series to be used in the whole application domain. In the demo data, some of the series defined here are: Customer Nos., Quote Nos., Order Nos., Invoice Nos., Posted Invoice Nos., Credit Memo Nos., Posted Credit Memo Nos., etc. Those number series are dimensioned for the needs of a typical small to medium sized company, however, various business have different patterns (for example, posting an unusual high number of invoices). In this case, the number series should be adjusted accordingly to make space for the customized company needs.\nThe default number series defined in the setup is then used in the individual tables. For example, table 18 - Customer, has\nField “No.” {1;;No. ;Code20;AltSearchField=SearchName;OnValidate=BEGINIF\"No.\"\u003c\u003exRec.\"No.\"THENBEGINSalesSetup.GET;NoSeriesMgt.TestManual(SalesSetup.\"Customer Nos.\");\"No. Series\":='';END;IF\"Invoice Disc. Code\"=''THEN\"Invoice Disc. Code\":=\"No.\";END;}Field “No. Series” {107;;No. Series;Code10;TableRelation=\"No. Series\";Editable=No}AssistEdit PROCEDUREAssistEdit@2(OldCust@1000:Record18) :Boolean;VARCust@1001:Record18;BEGINWITHCustDOBEGINCust:=Rec;SalesSetup.GET;SalesSetup.TESTFIELD(\"Customer Nos.\");IFNoSeriesMgt.SelectSeries(SalesSetup.\"Customer Nos.\",OldCust.\"No. Series\",\"No. Series\") THENBEGINNoSeriesMgt.SetSeries(\"No.\");Rec:=Cust;EXIT(TRUE);END;END;END;OnInsert OnInsert=BEGINIF\"No.\"=''THENBEGINSalesSetup.GET;SalesSetup.TESTFIELD(\"Customer Nos.\");NoSeriesMgt.InitSeries(SalesSetup.\"Customer Nos.\",xRec.\"No. Series\",0D,\"No.\",\"No. Series\");END;... ENDTo run the AssistEdit procedure, include this code on the No. - OnAssistEdit() trigger of the Page:\nNo. - OnAssistEdit() IFAssistEdit(xRec) THENCurrPage.UPDATE; ","categories":"","description":"","excerpt":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/no-series/","tags":"","title":"No Series"},{"body":"By David Bastide at Microsoft Development Center Copenhagen\n\nContext\nThis pattern is about sending notifications in Dynamics NAV, starting with version 2018, tracking them in the Notification Lifecycle Management framework, and recalling them when needed.\nDescription\nNotifications are easy to use in a wide range of cases. Instead of using notifications in a fire-and-forget way, we need to track them so that we can recall them if we need to.\nIf we can have only one notification on a given page, an easy and efficient solution is to use a predefined Notification ID, as suggested in the “Using In-context Notifications” pattern.\nHowever, some cases can be more complicated. For example, when you are adding lines to a table, what if several lines raise individual notifications? Using the same notification ID for each notification will no longer work because the latest notification overwrites the previous ones. Only one notification for a given notification ID can exist, and only the notification message would be updated. This is illustrated in Figure 1.\n\nFigure 1: Notification that an item that is not in stock. The notification ID is a predefined GUID, 2712AD06-C48B-4C20-820E-347A60C9AD00, for example.\n\nFigure 2: You add a second item that is not in stock. the notification is fired with the same GUID, 2712AD06-C48B-4C20-820E-347A60C9AD00, for example. The previous notification is overwritten.\nHere is the code for this behavior:\nLOCALPROCEDURECreateAndSendNotification@23(UnitOfMeasureCode@1010:Code[20];InventoryQty@1009:Decimal;GrossReq@1008:Decimal;ReservedReq@1007:Decimal;SchedRcpt@1006:Decimal;ReservedRcpt@1005:Decimal;CurrentQuantity@1004:Decimal;CurrentReservedQty@1003:Decimal;TotalQuantity@1002:Decimal;EarliestAvailDate@1001:Date) :Boolean;VARItemAvailabilityCheck@1011:Page1872;AvailabilityCheckNotification@1000:Notification;BEGINAvailabilityCheckNotification.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;EXIT(FALSE);END;LOCALPROCEDURE**GetItemAvailabilityNotificationId**@27() :GUID;BEGINEXIT('2712AD06-C48B-4C20-820E-347A60C9AD00');END;An easy fix would be to dynamically generate the notification ID. However, what if you fix the issue that triggered the notification?\nHere is the code for this possible fix:\nLOCALPROCEDURECreateAndSendNotification@23(UnitOfMeasureCode@1010:Code[20];InventoryQty@1009:Decimal;GrossReq@1008:Decimal;ReservedReq@1007:Decimal;SchedRcpt@1006:Decimal;ReservedRcpt@1005:Decimal;CurrentQuantity@1004:Decimal;CurrentReservedQty@1003:Decimal;TotalQuantity@1002:Decimal;EarliestAvailDate@1001:Date) :Boolean;VARItemAvailabilityCheck@1011:Page1872;AvailabilityCheckNotification@1000:Notification;BEGINAvailabilityCheckNotification.ID(CREATEGUID);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;EXIT(FALSE);END;Now, notifications do not replace each other, but we cannot recall them because we do not track each notification ID.\n\nFigure 3: Three sales lines with a notification for each one\nImagine that youre adding several items to a sales order, and inventory is low for some of the items. Each sales line will send a notification for its item if the quantity to sell is higher than the available inventory. By using dynamically generated notification IDs (CREATEGUID), each notification will not be overwritten, which is what we want. This is shown in Figure 3. But after you see the notification, you may decide to decrease the quantity in the sales line. At that point, the notification should be recalled. To do that, we need a way to track the notifications and their IDs.\nSolution\nThe solution is to use the Notification Lifecycle Management framework.\nThe framework allows you to keep track of notifications by saving notification IDs and with other useful information (record ID and optional additional context) that will allow you to easily find the notification IDs to recall. This can be seen as an internal dictionary to put and get notification IDs.\nThis framework has three main components:\n A temporary, in-memory table: Notification Context (1519). This table stores each notification GUID, the record ID of the record that caused each notification (on what object), and optionally, an additional GUID that represents an additional context: the cause of the notification (why). This lets you track and recall each notification. You can fire-and-forget the notification, but if you need to recall it you can find it by using the record ID of the cause and the optional additional context ID.\n A singleton codeunit: Notification Lifecycle Mgt. (1511), that provides functions to create new notification context lines and recall them. This codeunit contains one instance of the temporary table Notification Context.\n A helper codeunit:Notification Lifecycle Helper (1508), that subscribes to various events and makes the calls to the Notification Lifecycle Mgt. codeunit.\n The unit tests for this framework are in codeunit Notification Lifecycle Tests (139480).\nThe main functions provided by codeunit 1511 are:\n SendNotification(NotificationToSend : Notification;RecId : RecordID)\n Sends a notification and keeps track of it in the simplest way. We have a notification to send and the record ID of the object that triggered the notification. SendNotificationWithAdditionalContext(NotificationToSend : Notification;RecId : RecordID;AdditionalContextId : GUID)\n Sends a notification and keeps track of it with additional information. For example, a GUID that represents the context in which the notification was sent, and an item with insufficient inventory. RecallNotificationsForRecord(RecId : RecordID;HandleDelayedInsert : Boolean)\n Recalls all notifications that were sent by a given record ID. The HandleDelayedInsert flag should be TRUE if it is possible that the record ID provided is from a record that was not yet in the database (TRUE unless we recall notifications after deletion of a record). RecallNotificationsForRecordWithAdditionalContext(RecId : RecordID;AdditionalContextId : GUID;HandleDelayedInsert : Boolean)\n Recalls the notification that was sent by a given Record ID in a particular context. The HandleDelayedInsert flag should be TRUE if it is possible that the Record ID provided is from a record that was not yet in the database (TRUE unless we recall notifications after deleting a record). SetRecordID(RecId : RecordID)\n Sets the record ID after delayed insertion of a record. This will update the initially incomplete Record ID in the Notification Context table to a full Record ID. UpdateRecordID(CurrentRecId : RecordID;NewRecId : RecordID)\n Replace CurrentRecId with NewRecId in the Notification Context table. This is called by SetRecordId. Usage\nThe simple case is:\n We create a notification object. We call SendNotification or SendNotificationWithAdditionalContext. When we want to recall the notification, we call RecallNotificationsForRecord or RecallNotificationsForRecordWithAdditionalContext. \nFigure 4: without additional context\n\nFigure 5: with additional context\nHowever, delayed insert means that the simple case seen above doesnt happen very often. The issue is that when we call SendNotification, we provide the cause objects record ID. If this object has not been inserted yet, which is often the case when the user creates a new invoice, a new line, and so on, the record ID is incomplete. When the object is inserted the record ID is completed, but if we call RecallNotificationsForRecord at a later point, the record ID will be different from the incomplete record ID we used when sending the notification. The solution is to detect that the object is not yet inserted when we send the notification, and at a later point, set the record ID when the cause object is inserted.The realistic case is:\n We have a temporary object with a partially complete ID. Something like: Sales Line, 1000, “”. We send a notification caused by this object (item out of stock). The temporary table receives NotificationId, empty record Id (Quote, “\"), additional context (item out of stock). When the user leaves the field, the line is inserted. We replace the empty record ID (Quote, “\") by the full record ID (Sales Line, 1000, 10000). We recall the notification (the user put a lower quantity for example). We search for records with the full record ID and the additional context (item out of stock). If found, they are recalled. \nFigure 6: delayed insert, with additional context\nUsages in NAV:\nCOD311 (Item-Check Avail.)\nCOD312 (Cust-Check Cr. Limit)\nCOD1508 (Notification Lifecycle Handler)\nRelated Patterns:\nIn-context notifications\nSingleton codeunit\n","categories":"","description":"","excerpt":"By David Bastide at Microsoft Development Center Copenhagen\n\nContext …","ref":"/docs/navpatterns/patterns/notifications/notification-lifecycle-management-pattern/","tags":"","title":"Notification Lifecycle Management Pattern"},{"body":"A collection of patterns about notifications.\n","categories":"","description":"","excerpt":"A collection of patterns about notifications.\n","ref":"/docs/navpatterns/patterns/notifications/","tags":"","title":"Notifications"},{"body":"By Nikolai LEstrange, from TVision Technology Ltd. in the UK\nAbstract Track all record changes against a defined table or set of tables.\nProblem Microsoft Dynamics NAV has the built in ability to track all record changes against any table, however it does not always fire the triggers for every table.\nSolution Create a setup table to define which other tables you want to track changes for, and optionally what triggers you want to fire, then link this up to the standard triggers in Codeunit 1.\nCodeunit 1 Application Management contains the triggers OnDatabaseInsert, OnDatabaseModify, OnDatabaseDelete and OnDatabaseRename which are what we need to subscribe to in order to track record changes. However these triggers are only fired sometimes. This is determined by the parameters set in the function GetTableTriggerSetup, which is called once per table per session.\nIn order to define which tables we are interested in we can create a new table with the following fields:\nObservable Table:\n “Table ID” Integer Object.ID WHERE (Type=CONST(Table)) TrackInsert Boolean [optional] TrackModify Boolean [optional] TrackDelete Boolean [optional] TrackRename Boolean [optional] Then we can create a Codeunit that will set the Table Trigger Setup parameters and also subscribe to the OnDatabase triggers.\nLOCAL[EventSubscriber]GetTableTriggerSetup(TableId:Integer;VAROnDatabaseInsert:Boolean;VAROnDatabaseModify:Boolean;VAROnDatabaseDelete:Boolean;VAROnDatabaseRename:Boolean) IFObservable.GET(TableId) THENBEGINIFObservable.TrackInsertTHENOnDatabaseInsert:=TRUE;IFObservable.TrackModifyTHENOnDatabaseModify:=TRUE;IFObservable.TrackDeleteTHENOnDatabaseDelete:=TRUE;IFObservable.TrackRenameTHENOnDatabaseRename:=TRUE;END;LOCAL[EventSubscriber]OnDatabaseInsert(RecRef:RecordRef) IFObservable.Get(RecRef.NUMBER) ANDObservable.TrackInsertTHEN//do something LOCAL[EventSubscriber]OnDatabaseModify(RecRef:RecordRef) IFObservable.Get(RecRef.NUMBER) ANDObservable.TrackModifyTHEN//do something LOCAL[EventSubscriber]OnDatabaseDelete(RecRef:RecordRef) IFObservable.Get(RecRef.NUMBER) ANDObservable.TrackDeleteTHEN//do something LOCAL[EventSubscriber]OnDatabaseRename(RecRef:RecordRef;xRecRef:RecordRef) IFObservable.Get(RecRef.NUMBER) ANDObservable.TrackRenameTHEN//do something Note: In NAV2016 all these functions can be EventSubscribers that subscribe to the functions in Codeunit 1 as per above, in earlier versions of NAV these functions will need to be Global and called explicitly from within the Codeunit 1 functions.\nNAV Usages Variations of this pattern exists in the standard product in:\n Codeunit 423 Change Log Management Codeunit 5150 Integration Management. In this Codeunit the tables that fire triggers are hardcoded in C/AL. Consequences It is important that in our GetTableTriggerSetup function we only ever set the parameters to TRUE, and never set them to FALSE. This is because there may be other Codeunits listening to the triggers for that table, e.g. Change Log. This is also why we check the setup again within each trigger.\nRelated Topics This pattern was originally described in the following blog:\nhttps://geeknikolai.wordpress.com/2015/10/30/observer-pattern-in-dynamics-nav-2016/\nNAV Versions From NAV 2016 use the code as shown For earlier versions see Note above ","categories":"","description":"","excerpt":"By Nikolai LEstrange, from TVision Technology Ltd. in the UK\nAbstract …","ref":"/docs/navpatterns/patterns/observer/","tags":"","title":"Observer"},{"body":"A line of code should not have more than one statement.\nBad code\nIFOppEntry.FIND('-') THENEXITGood code\nIFOppEntry.FIND('-') THENEXITBad code\nTotalCost+=Cost;TotalAmt+=Amt;Good code\nTotalCost+=Cost;TotalAmt+=Amt;","categories":"","description":"","excerpt":"A line of code should not have more than one statement.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/one-statement-per-line/","tags":"","title":"One Statement Per Line"},{"body":"The number of parameters passed to a string must match the placeholders.\nBad code\nCannotDeleteLineErr@1005 : TextConst 'ENU=You cannot delete this line because one or more rating values exists.'; ... ERROR(CannotDeleteLineErr,TABLECAPTION); Good code\nCannotDeleteLineErr@1005 : TextConst 'ENU=You cannot delete this line because one or more rating values exists.'; ... ERROR(CannotDeleteLineErr); Bad code\nCannotUseThisFieldErr@1020 : TextConst 'ENU=You cannot use this field for %2 fields.'; ... ERROR(CannotUseThisFieldErr,0,Field.Class); Good code\nCannotUseThisFieldErr@1020 : TextConst 'ENU=You cannot use this field for %1 fields.'; ... ERROR(CannotUseThisFieldErr,Field.Class); ","categories":"","description":"","excerpt":"The number of parameters passed to a string must match the …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/parameter-placeholders/","tags":"","title":"Parameter Placeholders"},{"body":"This is the list of people that have been part of the NAV Design Patterns team. If you would like to join the project follow the instructions provided on Be a NAV Pattern Author page.\nProject administrator: Bogdana Botez.\nAuthors (in alphabetical order):\n Abshishek Ghosh, Microsoft (4 patterns)\n Using Query Objects to Detect Duplicates Blocked Entity Single-Record (Setup) Table Temporary Dataset Report Anders Larsen, Microsoft (1 pattern)\n Easy Update of Setup or Supplementary Information\n Andreas Moth, Microsoft (1 pattern)\n Anti-pattern: Reusable bugs\n Bogdan Sturzoiu, Microsoft (4 patterns)\n Feature Localization for Data Structures\n Copy Document\n Using C/AL Query Objects Instead of Nested Loops\n Data-Driven Blocked Entity\n Bogdana Botez, Microsoft (18 patterns)\n Silent File Upload and Download\n Standard Journal\n No. Series\n Data Model Proxy\n Journal Error Processing\n Journal Template-Batch-Line\n Multilanguage Application Data\n SELECT DISTINCT using Queries\n Anti-patterns: reusable bugs\n Sensitive Data Encapsulation\n Data Encryption\n Single Point of Access\n Masked Text\n SSL in NAV\n Singleton\n Singleton Codeunit\n Anti-Patterns in NAV Upgrade\n Cue table\n Carlos Raul Garcia, Microsoft (1 pattern)\n Anti-Patterns in NAV Upgrade\n Ciprian Iordache, Microsoft (2 patterns)\n Activity Log\n Totals and Discounts on Subpages (Sales and Purchases)\n David Bastide, Microsoft (3 patterns)\n Notification Lifecycle Management pattern\n Data Migration Façade\n Extending the Role Center Headlines\n Elly Nkya, Microsoft (2 patterns)\n Singleton Table\n Anti-patterns: reusable bugs\n Eric Wauters (waldo), iFacto, PRS (6 patterns)\n Hooks\n Posting Routine - Select Behaviour\n Variant Facade\n Argument Table\n Discovery Event\n Anti-patterns: reusable bugs\n Gary Winter, agiles (1 pattern)\n Variant Façade Henrik Langbak, Kim Ginnerup, Bording Data A/S (2 patterns)\n Currently Active Record\n Released Entity\n Jan Hoek, IDYN (2 patterns)\n Conditional Cascading Update\n Setup Specificity Fallback\n Jesper Schulz, Microsoft (1 pattern)\n Error Message Processing, part I\n Martin Dam, Microsoft (1 pattern)\n Multi-File Download\n Mike Borg Cardona, Microsoft (1 pattern)\n Creating URLs to NAV Clients\n Mostafa Balat, Microsoft (3 patterns)\n .NET Exception Handling\n Cached Web Service Calls\n Try Method\n Nikola Kukrika, Microsoft (7 patterns)\n Totals and Discounts on Subpages (Sales and Purchases)\n Create Data from Templates\n Argument Table\n Instructions in UI\n Creating Custom Charts\n Variant Façade\n Anti-patterns: reusable bugs\n Nikolai LEstrange, from TVision Technology Ltd. in the UK_\n_ (2 patterns)\n Observer\n Cross Session Events\n Raed Selim, Microsoft (1 pattern)\n Product Name Soumya Dutta (2 patterns)\n In-context notifications Data Migration Façade Søren Klemmensen, 360 Visibility, PRS (2 patterns)\n Master Data\n Surrogate Key\n Tim Grant, Trendmicro (1 pattern)\n Read Once Setup Record\n Report Selector (this pattern was started by 2 workgroups by multiple authors, but finalized and corrected by Tim).\n Xavier Garonnat, knk Ingénierie (1 pattern)\n Document\n They have also invested their time and energy in this project:\n Eva Dupont, Microsoft - our publisher on MSDN NAV Team Blog. Kurt Juvyns, Microsoft - coordinator of pattern videos Pattern evangelists:\n Eric Wauters (waldo), iFacto, PRS Gary Winter, agiles, PRS Mark Brummel, Brummel Dynamics Services, PRS Mike Doster, Mergetool Søren Klemmensen, 360 Visibility, PRS And last but not least, we have collaborated with Plataan who hired Eric Wauters from ifacto and Mark Brummel from Brummel Dynamics Services and PRS, to publish on video some of our patterns.\n","categories":"","description":"","excerpt":"This is the list of people that have been part of the NAV Design …","ref":"/docs/navpatterns/4-get-involved/patterns-authors/","tags":"","title":"Patterns Authors"},{"body":"By waldo\nAbstract Send information (parameters) to a processing framework/routine so that it knows what to do, how to behave.\nDescription For a processing routine to behave correctly, it needs sometimes input of a user to know what it has to do, check or avoid doing. To do this, usually a piece of UI is getting called (STRMENU) with the question what to do. These input needs to get to the routine.\n The user selects the option on how he wants the process to behave There are extra fields on the processing table, that are used internally and act like parameters. These Fields get filled according to the selections that the user has made The processing codeunit receives the processing table, and therefor also the parameters \nUsage Example: Sales Post.\nOn Sales Header, there were fields created which act like internal parameter-fields for the “Sales Post” routine:\n\nWhen pressing “Post”, the Selection Codeunit is getting called:\n\nOr in case of the Post\u0026Print, the selection codeunit is different:\n\nNext, the user is able to select the options with an STRMENU, which results in filling in the fields above, like:\nSelection:=STRMENU(Text000,3);IFSelection=0THENEXIT;Ship:=SelectionIN[1,3];Invoice:=SelectionIN[2,3];The processing codeunit is being called after these options were set.\nNAV Usages This is also being used in the Purchase Post.\nHowever, the Service Post works different. In Short:\n There were no parameter fields added to the processing table (Service Header) The processing routine isnt called by CODEUNIT.RUN, but a function in a declared codeunit, where you pass the Invoice and Ship parameter separately. Ideas for improvement Implement it consequently. There is (in my knowledge) no reason to do Service Posting differently from Sales and Purchase.\nFurthermore, one might argue if adding fields to a table (which also means adding fields to the SQL Table) is the right solution to pass parameters to processing methods.\nOn the other hand, as we are handling tables as being “classes” in many cases, it does make sense to add “properties” to those “classes” to change the behavior of the method (SalesHeader.Post).\nRelated Topics I would like to add a pattern like “Using Argument tables” (as a sub-pattern for the facade-pattern). It somewhat is related to this way of handling parameters: using tablefields to pass a flexible amount of parameters to functions/codeunits.\n ","categories":"","description":"","excerpt":"By waldo\nAbstract Send information (parameters) to a processing …","ref":"/docs/navpatterns/patterns/posting-routine-select-behavior/","tags":"","title":"Posting Routine - Select Behavior"},{"body":"Abstract On many occasions, its needed to refer to the product name in messages or errors. Its not a good practice to hardcode the brand name like Dynamics NAV 2017, and change this value with each rebranding. You can use client ProductName System Object instead to refer to the product name.\n\nProblem When you want to refer to product name in informational messages or errors, its not a good practice to hardcode the brand name, as this requires changing this text when a rebranding happens.\nSolution Instead of hardcoding the product name like “Dynamics NAV 2017”, its recommended to use ProductName System Object that platform provides.\nYou can use ProductName to refer to the product name, this you can use in text messages. ProductName has 3 values ProductName.Short, ProductName.Full, and ProductName.Marketing, each one should be used according to the context of your message.\nIts recommended to use ProductName.Short for most in-product texts , ProductName.Full when other dynamics apps are present in the message context (like CRM), and ProductName.Marketing only when absolutely necessary.\nUsage: You should make a placeholder in your text constant and substitute this placeholder with ProductName as shown below.\n\nOutput\n\nBenefits This decouples your messages from the application name This removes the effort of maintaining these messages and keeping them up to date with the brand name. Limitations ProductName cant be used for tooltips and captions, it can only be used for text constants (Labels). ProductName System object doesnt exist in NAV 2016 and earlier version. ","categories":"","description":"","excerpt":"Abstract On many occasions, its needed to refer to the product name …","ref":"/docs/navpatterns/patterns/product-name/","tags":"","title":"Product Name"},{"body":"Expand to see NAV design patterns which use queries.\n","categories":"","description":"","excerpt":"Expand to see NAV design patterns which use queries.\n","ref":"/docs/navpatterns/patterns/queries/","tags":"","title":"Queries"},{"body":"By Tim Grant\nAbstract One time query and validation of a setup table.\nDescription Firstly identifies if a setup table record is in memory, removing the need to execute and validate the re-query again within a code unit. (From NAV 2013+ service tier database caching exists).\nIf you need to query a setup table, but not sure if the table is yet in memory from earlier code, this helps to determine this call (see Singleton Table pattern).\nAllows a central function to validate critical fields before processing automated code. TESTFIELD calls are added to the function and not the INIT call in order to ensure that critical functions do not run without this human check in place as these may rely on key configuration. If you have a design where specific field values are critical (custom or standard) for integrity, then INIT INSERT is a dangerous default which could result in the corruption of processes. This is separate automated INIT INSERT from a setup page.\nNAV Specific Example A global variable record and a global status indicator, but within the context of a local function.\n\n\nNAV Usages A similar example of this is in Codeunit 80, but without any validation.\n\nE.g. If there is a bespoke change, then this existing GetGLSetup can be called earlier to accommodate for an earlier bespoke change:\n\nThis means that by the time the code reaches the original GetGLSetup code requirement, this record is already in memory as the status flag is set to True, eliminating another check. For such Patterns the setup record should never be cleared, it should be called once globally, initiated and left in memory for future checks. It should not be declared locally at the same time, review your code for matching local variable usage before implementing this.\nIdeas for improvement Merge Singleton Table with dynamic validation field meta configuration. This removes the coding of TESTFIELD to a central setup check.\nExample with the Sales \u0026 Receivables Setup\n\n\n\nConsequences If in the circumstance that a field value in the setup table is expected to change within the life of the code component instance. e.g. If a CHANGECOMPANY is required to cross reference another Setup table, use a separate variable.\nRelated Topics This is related to the Singleton Table pattern.\n","categories":"","description":"","excerpt":"By Tim Grant\nAbstract One time query and validation of a setup table. …","ref":"/docs/navpatterns/patterns/read-once-initialization-and-validation/","tags":"","title":"Read-once Initialization and Validation"},{"body":"C/AL Coding Guidelines Readability Generally, all readability rules are Microsoft style choices only. You can use them to keep consistency with the existing code.\nFind the C/AL guidelines by expanding the menu in the left.\n","categories":"","description":"","excerpt":"C/AL Coding Guidelines Readability Generally, all readability rules …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/","tags":"","title":"Readability"},{"body":"Find below some related NAV Design Patterns links.\nMSDN NAV Team Blog - posts about patterns\nNAV Application Design slides from NAV TechDays conference in Antwerp, 2013\nNAV Application Design movie from NAV TechDays conference in Antwerp, 2013\nNAVs Secret Code: Design Patterns of Today and Tomorrow slides from NAV TechDays conference in Antwerp, 2013\n","categories":"","description":"","excerpt":"Find below some related NAV Design Patterns links.\nMSDN NAV Team Blog …","ref":"/docs/navpatterns/related-links/","tags":"","title":"Related Links"},{"body":"Authors: Henrik Langbak and Kim Ginnerup, Bording Data\nAbstract This pattern prevent data from being used elsewhere before it is in a system consistent state.\nNAV inserts a record as soon as the primary key has been set. But the record may not be in a valid state at this point in time. How do you know if a newly inserted record is ready for use?\nDescription Whenever you need to stall the release of data, you can use this pattern.\nBecause NAV decides when a record is written to the database, it may not be in a system consistent state. Nobody should use the record before everything is in place and the record is valid. An inserted record may even have data in other tables that needs to be inserted and in a valid state before other parts of the system can use the data without running into a problem.\nData entered into the system may have to be approved by a second person before it can be used.\nData requires different parties (e.g. Departments) to add information before data is valid.\nThe solution is an Option Field with two or three values:\n(Open, Released) or (Open, Pending, Released)\nThe states should be interpreted as:\n State Description Open Not all data is in place. The record is system inconsistent. The record or record hierarchy is invisible for all other parts of the system. Pending The record is system consistent. But is awaiting someone to manually raise the state to Released. The record is still invisible. Released All data is in place and the record is system consistent, and ready for use. It is now visible for the rest of the system. The state can never be reversed. The option field name: Release State.\nThis pattern is very similar to the Blocked Entity pattern, but it has one significant difference.\nThe record is not visible to any part of the system, before it is in the Released state.\nThere is no going back. When the Released state is reached, it will stay that way for the life of the record. In case of a tri-state, it is ok to bypass Pending seen from a system state perspective.\nIf there is a hierarchy, e.g. Header and Lines, then the Release State field resides on the Header. As long as the Header remains unreleased, the lines are considered inconsistent and must not be used.\nThe important and critical part of this pattern is that the whole application needs to obey the “Release State”-contract or the system will fail.\nUsage To use this pattern you need to create an Option Field named: “Release State” with at least the two states: Open, Released.\nAutomatic pending or release If it is feasible to set the Release State automatically, create a local function named: “CheckAndSetReleaseState” that validates the record and sets Release State to Pending or Released, when all system requirements are met.\nThe function only works one way. It can only increase the state. If the function is called when release state is Pending or Release, the function will do nothing.\nIf the function is implemented, then the user should not be able to change the value from Open to Pending or Released, only the function can do that.\nThe function should be called on every change, this way it will be visible to the end user immediately when all requirements are met.\nIf the Pattern is implemented without this function, then field is maintained by the end user.\nNAV Specific Example NAV has Table 36 Sales Header, Field 120 Status.\nIn this example, it is called: Status.\nStatus has 4 values: Open, Released, Pending Approval, Pending Prepayment.\nNAV Usages The example above, taken from NAV, shows similarity with this pattern, but in the Sales Header example it is possible to modify the Release state to an earlier state, through a function in NAV. This is not recommended in the pattern.\nIdeas for improvement In case of a Pending State, you may need an Approved Date and Approved By. Depending on how formal it needs to be.\nConsequences This pattern is only used on data creation.\nIf there is a need for shuffling between states back and forth, then this is not the pattern to use.\nRelated Topics Blocked Entity is a variant of this pattern but Blocked Entity is used later in the life-cycle.\nAn alternative to the pattern is temporary tables. But the temporary table is an all or nothing approach. If all data in the Record is valid, the temporary record can update the real data. If not, abandon the process. The Release State pattern is simpler and requires less code.\nReferences There is a term called: Long Term Lock. This pattern has some resemblance.\nWhen talking about hierarchical data structures and the Release State is held on the root node, there is a pattern called Hierarchical Locking that has some resemblance.\n","categories":"","description":"","excerpt":"Authors: Henrik Langbak and Kim Ginnerup, Bording Data\nAbstract This …","ref":"/docs/navpatterns/patterns/released-entity/","tags":"","title":"Released Entity"},{"body":"From the PRS workshop at NAVTechDays 2013, this pattern was written by 2 work groups\nGroup 1: Dale Gauci \u0026 Kimberly Congleton\nGroup 2: Jens Winberg, Tim Grant, Alen Tot\nThanks to Tim Grant who had merged the two patterns, corrected, sent for review and finalized them.\nMeet the Pattern It should be possible to change which document report object should be used when printing. This configuration can be stored in one place (Report Selection) and available at configuration time. In this situation, the code for printing records can remain the same.\nThe purpose of this pattern is to describe the process to implement a reports selection by retrieving the specific Document Header, determining which type of document is related to it in the Report Selection Screen, and call the report which needs to be printed by passing the specific document header. This specifies the reports that you can print when you work with the various documents for sales and purchases, such as orders, quotes, invoices, and credit memos.\nKnow the Pattern The program can preselect which report will be printed when you print from various types of purchase and sales headers. For example, on an order, the Order Confirmation report is automatically printed.\nThe Report Selection table contains the specification of which report will be printed in different situations. The Report Selection table also contains the report ID and report name for the report that will be printed when the user works with a given document type.\nThe user can, of course, choose to have the program print a different report than the preselected one. You can also add reports to the Report Selection table to have the program print more than one report per document type.\nThis pattern should be used when the user needs to print a new type of document which can have different report layouts, or when the user needs to print several different reports in sequence. This can also be used during a new post and print routine, a test report for journal posting or for re-printing a posted document. Using this pattern will minimize code by allowing a flexible means of specifying different reports to print, instead of hard-coding a report id when printing a document.\nUse the Pattern The Report Selection Pattern involves the Report Selection table as the central configuration element also with the Report Selection Page. The table is used in 4 generic functional workflows:\n Test Print un-posted If the Report Selection is related to a Test Report relating to a Document:\n The Documents Page including Printing Actions Test Report-Print Codeunit 228 Print un-posted. If the Report Selection is related to an existing Document (un-posted): The Documents Page (Document / List) including the Printing Actions The Document-Print Codeunit 229 is used atomically to use the document type in the generic Sales Header table before the report selection is found. Print while posting. If the Document is printed at the point of posting then: The Documents Post + Print Codeunit (82 or 92), with the related GetReport and PrintReport functions. Print after posting. If the Report Selection is related to an existing Document (posted): The specific document related posted header table is used along with a typical function: PrintRecords within the respective table. Example Sales Document (Invoice)\nPre-conditions\n The document header/lines table is present and there is a report which has a parent DataItem linked to this document. A document and list page is present and related to the document. A post and print Codeunit exists for the document. Implementation:\n Add a new Option String to the Report Selection table, Usage field (including any ML Captions). Calling of GetReport function, passing the document header. SalesSetup.GET;IFSalesSetup.\"Post \u0026 Print with ob Queue\"THENSalesPostViaobQueue.EnqueueSalesDoc(SalesHeader) ELSEBEGINCODEUNIT.RUN(CODEUNIT::\"Sales-Post\",SalesHeader);GetReport(SalesHeader);END;COMMIT; Implementing the new document type within the GetReport Function, and calling PrintReport with the New OptionString \"Document Type\"::Invoice:BEGINIF\"Last Posting No.\"=''THENSalesInvHeader.\"No.\":=\"No.\"ELSESalesInvHeader.\"No.\":=\"Last Posting No.\";SalesInvHeader.SETRECFILTER;PrintReport(ReportSelection.Usage::\"S.Invoice\");END; Implement the new Document Type and calling the associated report ID, passing the document header NAV Usages Codeunits 82, 92, for post and printing purchase and sales documents Codeunit 229 for Document printing Header Tables 110, 112, 114, 120, 122, 124, 295, 297, 302, 304. 5744, 5746, 6650, 6660 This pattern is already used for printing documents like sales invoices, proforma, waybills, Finance Charge Memos, Receipt Documents.\nIdeas for improvement The “Usage” Field could be more dynamic through a setup field linked to a document type table mapped to the document header Table ID.\nReport Selection table is currently based on the Usage of the report to be defined. A more generic way could be to only select what record id the printing selection is based on could also be implemented. (I think this means Recordref and Table Number could be used to identify the posted tables)\nThe Report Selection matrix could be evolved to accommodate the Journal post \u0026 print configuration. This setup currently resides in the Gen. Journal Template table.\nMerge the PrintReport functions in the purchase and sales post printing functions (82, 92) into a more atomic print selection component.\nMerge the PrintRecords functions in the separate posted header tables into a more atomic print selection component.\nRelated Patterns Posting Routine Pattern (Journal/Document) Post Batch Routine Pattern ","categories":"","description":"","excerpt":"From the PRS workshop at NAVTechDays 2013, this pattern was written by …","ref":"/docs/navpatterns/patterns/report-selection/","tags":"","title":"Report Selection"},{"body":"By Bogdana Botez, Andreas Moth, Eric Wauters (waldo), Elly Nkya, Nikola Kukrika\nApril 1st, 2015\nAbstract It is difficult to come up with new and different bugs in each release, and it is a waste of resources to not use the ones which already had proven successful in the past. To avoid reinventing the wheel, we propose to come up with new innovative ways to create bugs that are reusable and generic enough to be used in various places of the application.\nExamples Option Strings\nOne example of a reusable bug is to find a heavily used table, like table 36 Sales Header, and observe one of the more important fields of type Option, for example Document Type. The OptionString property has the following value: Quote,Order,Invoice,Credit Memo,Blanket Order,Return Order, which you should update to add one option, for example Transport Order in the beginning.\nThe main benefit of this reusable bug is that code changed in one place, has impact in multiple sides on the application: document creation and handling, posting etc.\nApplication Management\nCodeunit 1, ApplicationManagement is a good place for creating reusable bugs. A simple INSERT on the RecRef on the first line of OnDatabaseInsert will create a sure and versatile bug that is reusable all over the application. Redundancy on database insertion ensures that data is surely conveyed to the data storage layer, twice.\nGod objects\nWe are considering to no longer make localization builds for countries. It consumes lab resources to keep running multiple country builds. Instead, we will merge everything into one single build. This is a bigger scale implementation of the “God object”. Inside this unique build, we will use IF statements and sporadically CASE statements to select each countrys behavior. For more help on how to use IFs, see also the IF .. THEN|ELSE C/AL Coding Guideline.\nField length economy\nWhen you post a document, make sure to transfer data to a field that is smaller than the field you are assigning from. This will not immediately be caught and will only hurt a subset of the customers who uses Microsoft Dynamics NAV to its fullest.\nGuidelines When bug addition is not entirely obvious, there is a second way to approach the problem. By following some general coding best practices like the ones described below, reliable bug innovation is facilitated and can come naturally as a collateral effect.\nCode structure\nPut everything in one function and only use comments to explain the structure of your code. And dont use functions - because this only complicates things… having to navigate from function to function, and completely lose track of where you are in the business logic.\nOn top of that .. put everything in one codeunit. Because also that will simplify and make your structure more readable.\nUse Hungarian Notation on your variables, because at any time, you need to know what type, and what context your variable is on.\nDeclare all your functions and variables global, so they are available at any time.\nDont do Unit Testing\nUnit testing adds complexity and extra time to the stuff youre doing. Also, it eats up extra codeunits which means: it costs money. You will never be able to foresee all scenarios possible, so youre destined to forget and not test everything. So you will save time in not doing unit testing.\nNever add images to actions\nBecause there is an image by default. When you dont provide an image on an action on a page, the application will foresee a ball… and when you never do it, your application will have a very consistent way of showing your actions, by providing that picture of that ball. On top of that, youll save time.\nDo not care about ControlIDs\nWhen youre doing development of your product, do not care about ControlIDs, and just leave the Offset ID to the default value of 0. This way, when merging, you will receive nice notifications, saying both you and Microsoft have added functions in that objects. You can use this feature to document all these places.\nHooks\nNever apply the hook pattern. Hooks will only reduce upgrade time. This means, you will only shortly enjoy using the AMU (Application Merge Utilities). The more you change in default application, the longer it takes to upgrade, the longer you will enjoy the toolkit\nThis can be taken one level higher. Simply you are not hardcore if you do not use notepad to resolve all of the merge issues.\nHow to use RecRef\nWhy fuss around declaring specific table variables, just generalize, all you need is one, two, or perhaps three RecRef variables, with a few IFs and CASEs here and there for reflection, to carry you all the way.\nArguments\nUsing only a few arguments on the functions is a sign of a weak developer. Stick in as many arguments as possible on the function, even if you are not using them, they could be useful in the future.\nJust another field / action\nThinking of the design is overrated, each problem can be solved by adding an additional field or the table/page or with adding another action. We all know this has worked well in the past.\nReusability\nWe have decided that each time we fix a bug, we now also explain how it can be applied as a pattern. We then use anti-virus software to search for these patterns, to make sure we do not re-introduce these bugs anywhere else in NAV.\nBusiness logic placement\nAs a best practice, we have also decided to move code into pages. Business logic should no longer be in tables and codeunits, but instead pages should know and be aware of the context and update it accordingly. As opposite to tables and codeunits, pages are aware of the context.\nConclusion Happy April Fools' Day.\nDisclaimer: this is inspired from IETF documentation published on April 1st, like for example the revolutionizing IP over Avian Carriers standard.\n","categories":"","description":"","excerpt":"By Bogdana Botez, Andreas Moth, Eric Wauters (waldo), Elly Nkya, …","ref":"/docs/navpatterns/2-anti-patterns/reusable-bugs/","tags":"","title":"Reusable Bugs"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\nSecurity patterns for NAV Problem statement When sensitive data is stored inside the Dynamics NAV database, if negligently handled, it can become vulnerable. Particularly, the location, access and the state of the data are critical.\nUse the following patterns to enhance security on your NAV system.\n Sensitive Data Encapsulation Data Encryption Single Point of Access Masked Text SSL in NAV ","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\nSecurity …","ref":"/docs/navpatterns/patterns/security/","tags":"","title":"Security"},{"body":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract This pattern explains how to perform SELECT DISTINCT by using queries in Dynamics NAV.\nDescription\nWhen working with tables, sometimes a developer needs to perform a SELECT DISTINCT (also known as SELECT UNIQUE) from a table. As NAV does not provide this out of the box, we present below a way to select unique records by using queries.\nProblem statement\nLets consider the VAT Entry table as below: \n\nThe goal is to select one line for each separate document that produced VAT Entries. In other words, we want records grouped by Type, Document Type and Document No.. However, if there are multiple lines with the same value of the triad Type, Document Type and Document No. in the VAT Entry table, we only want to see one of them.\nSolution Create a new query object VAT Entry Distinct Document No., with a single DataItem sourced from VAT Entry table. Add the three desired group-by fields Type, Document Type and Document No. as columns.\n\nTo enable grouping, add one more column, with Method Type = Totals. This will automatically set the Group By checkbox to TRUE on the three precedent fields.\nNote that the Group By field is read-only and trying to set it by hand will clarify that:\n\nRunning the query yields a single record per document. You can notice in the second line below for example, how the sales invoice number 103001 had 2 VAT Entries, but it shows up only once in the query:\n\nExample One thing is to be noted: there is a limitation to how much information you can take out from the records. For example, if we need to extract more information than just the one we already have in the columns, then the following apply: adding one more column of Method Type = None will indeed show more information, but it might affect the grouping. More details below.\nThe grouping is affected for example when the additional column is the VAT Entry No. In this case, this column brings up additional grouping criteria and one group for each entry number will end up being created.\n\nYou can notice that both lines of document 103001 are not visible, which contradicts the goal of SELECT DISTINCT.\n\nThe grouping is not affected when the additional column does not influence grouping (has variation identical with one of the other existing columns). For example, adding Posting Date as a new column, does not change anything because posting date is the same for all lines of a document, so the query result is identical with the initial one:\n\nBelow is the result of this query, where you can notice that the initial grouping is preserved and correct. Bonus, we can now read the Posting Date of the document too.\n\nThe grouping is also not affected when adding more columns of Method Type = Totals. However, this can only be done with columns of Decimal data type.\nNAV Usages This pattern is used in Query 19: VAT Entries Base Amt. Sum. This query is used in Report 19: VAT- VIES Declaration Tax Auth.\n\nThe pattern is also used in Query 1511: User IDs by Notification Type.\nRelated Topics A variation using loops could be described, for C/AL development on NAV 6 where query objects are not available.\n","categories":"","description":"","excerpt":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/queries/select-distinct-with-queries/","tags":"","title":"SELECT DISTINCT with Queries"},{"body":"IF and ELSE statements should be on separate lines.\nBad code\nIFAtom[i+1]='\u003e'THENHasLogicalOperator:=TRUEELSEBEGIN... END;Good code\nIFAtom[i+1]='\u003e'THENHasLogicalOperator:=TRUEELSEBEGIN... END;","categories":"","description":"","excerpt":"IF and ELSE statements should be on separate lines.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/separate-if-and-else/","tags":"","title":"Separate IF and ELSE"},{"body":"By Jan Hoek at IDYN\nAbstract The Setup Specificity Fallback pattern allows users to efficiently define a potentially complex setup in terms of rules and exceptions to these rules, exceptions to the exceptions, etc.\nDescription The pattern involves a setup table with a compound (i.e. consisting of more than one field) primary key, where each record in the table maps a combination of primary key values to a particular setup value. However, setting up and maintaining each and every combination could prove to be rather labour-intensive.\nWith the Setup Specificity Pattern in place, primary key fields in the setup table can have a special value (typically: zero or an empty string) that acts as a wildcard, meaning that the setup record in question applies to a combination of primary key fields with any value in the field containing that wildcard. According to the pattern, when querying the setup table, the application attempts to find the appropriate setup record by searching less and less specific, starting with only specified primary key values, and possibly ending with only wildcard values, replacing specific values with wildcards in a predefined order until a setup record is found, e.g.:\n Step 1. Try to find record with: Field A = value “a” and Field B = value “b” If found, return record; if not, go to step 2. Step 2. Try to find record with: Field A = value “a” and Field B = wildcard value If found, return record; if not, go to step 3. Step 3. Try to find record with: Field A = wildcard value and Field B = value “b” If found, return record; if not, go to step 4. Step 4. Try to find record with: Field A = wildcard value and Field B = wildcard value If found, return record; if not, optionally return hard-coded value The least specific record can be thought of as the general rule, and each of the subsequent records is an exception to that rule. By defining only exceptions to the rule, instead of each and every combination, the burden of setting up and maintaining the setup records is strongly reduced, and the overall setup is much easier to read and understand.\nUsage Create your setup table. Remember that this pattern applies only to setup tables with a compound primary key; Create a function that will return the required value from the setup; For each level of specificity, the function should test if the corresponding record exists. If it does, the setup value should be returned. If it doesnt, the logic should fall-back to a lower level of specificity. (Optional) If even the least specific setup record can not be found, the function may return a blank value or hard-coded default value. NAV Usages The Printer Selection table in NAV is an example of the Setup Specificity Fallback pattern. Its primary key consists of two fields. A blank value in either field means that the record applies to any user or report respectively.\n\nThe FindPrinter function in codeunit 1 searches for the printer to use, with a decreasing level of specificity.\n\n","categories":"","description":"","excerpt":"By Jan Hoek at IDYN\nAbstract The Setup Specificity Fallback pattern …","ref":"/docs/navpatterns/patterns/setup-specificity-fallback/","tags":"","title":"Setup Specificity Fallback"},{"body":"By Abhishek Ghosh, at Microsoft Development Center Copenhagen\n\nThis is the first and most well-known of the two usual applications of the Singleton Table pattern in Dynamics NAV.\nProblem: the developer needs to store information about the operating setup or environment in the database, in a way that can be persisted across sessions.\nSolution: The information is stored in a table with one record only. The user is subsequently able to modify, but not add or delete records in the table.\nThe implementation of the pattern involves several considerations:\n Suffixing the table name with Setup (ex: General Ledger Setup). Defining a suitable primary key Creating a page where the user can view and edit a record, but not add new records or delete an existing one Optionally, updating the Company - Initialize codeunit. Defining a Primary Key\nSince this kind of tables is a collection of several environment or setup parameters, the primary key does not refer to any business attributes for this kind of tables. However, for maintaining the integrity of the database, it is necessary to define a primary key.\nSo, the most common implementation is to have a field “Primary Key” of Code[10]. This is populated with a blank value when the record is inserted. This field is not added to the page, so that the user cannot be modify it later.\nCreating a Page\nThe CardPage type is most suitable for representing this kind of tables. In addition, the InsertAllowed and DeleteAllowed properties in the page should be set to false to prevent the user from adding or deleting records in the table.\nIn the OnOpenPage trigger, the following code should be added to insert a record when the user opens the page for the first time, if a record does not exist already.\nOnOpenPage() RESET;IFNOTGETTHENBEGININIT;INSERT;END;The following diagram describes the flow of the program, once the user tries to access the setup information. The user opens the page. If the record containing setup information already exists, then the page opens on the existing record. Else, a new empty record is created and the page opens on it.\n\nCompany-Initialize Codeunit\nThe Company-Initialize codeunit (codeunit 2) is executed when a new company is created. We recommended that you add records to the single-record tables in this codeunit. If some of the fields are expected to have default values, they can also be populated here.\nNAV Usages\nSeveral Setup tables in NAV implement this pattern. Some of those are:\n Table 98 General Ledger Setup Table 311 Sales \u0026 Receivables Setup Table 312 Purchases \u0026 Payables Setup Table 313 Inventory Setup Table 242 Source Code Setup Variation: While most tables just insert a record with empty primary key in codeunit 2, table 242 (“Source Code Setup”) offers an example of inserting default values into all fields of the table (method “InitSourceCodeSetup”). This practice, wherever feasible, is likely to reduce the effort during implementation.\nRelated resources: Considerations on optimizing the Singleton Table, by Søren Klemmensen.\n","categories":"","description":"","excerpt":"By Abhishek Ghosh, at Microsoft Development Center Copenhagen\n\nThis is …","ref":"/docs/navpatterns/patterns/singleton/singleton-table/setup-table/","tags":"","title":"Setup Table"},{"body":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract This pattern is about silently handing file transfers between NAV Service Tier and the NAV client. By “silently” we mean: without showing a dialog box at upload or download time.\nDescription As a terminology clarification [1], note that both “upload” and “download” are named as seen from the clients point of view:\n Download\" defines transferring a file from the server to the client. “Upload” transfers the file from the client to the server. \nSometimes, files must be transferred to or from known locations without triggering file-save or file-load dialogs.\nIn the following, both the historical and the recommended ways of silently transferring files are described. Since we keep both implementations possible for the sake of backward compatibility, we strongly recommend that you use the file-transfer API provided that is provided with the File Management codeunit (419).\nThe legacy API for file transfers [2]:\n[Ok:=]UPLOAD(DialogTitle,FromFolder,FromFilter,FromFile,ToFile) [Ok:=]DOWNLOAD(FromFile,DialogTitle,ToFolder,ToFilter,ToFile) As you can see, this historical API leaves no place for turning off the functionality for showing a dialog. Historically, NAV offered a remedy to this, namely by using the “Magicpath” string, which is the constant \u003cTEMP\u003e. Under this condition, the way to invoke silent file upload or download becomes:\n[Ok:=]UPLOAD(DialogTitle,Magicpath,FromFilter,FromFile,ToFile) [Ok:=]DOWNLOAD(FromFile,DialogTitle,Magicpath,ToFilter,ToFile) This remedy introduced an issue: If we use “Magicpath” instead of FromFolder and ToFolder specifications, then where do we upload from and where do we download to? The answer is that they are uploaded to and downloaded from the NAV servers temporary folder. The path to the temporary file can be obtained when this file is created, by using the following function in File Management: \u003ctempFileName\u003e := ServerTempFileName(\u003cfileExtension\u003e).\nThe new API for file transfers in the File Management codeunit:\n[Text :=] UploadFileSilent(ClientFilePath)\n[Text :=] DownloadTempFile(ServerFileName)\nUsing the API in the File Management codeunit instead of the historical API is recommended for all file transferring and file management in NAV implementations.\nUsage The following describes a scenario for the silent file upload/download pattern, both from the users point of view and from the NAV developers point of view.\nThe NAV User The production manager at CRONUS needs an XML file in a specific format containing his latest product list with description, prices, and quantities. He wants to import the list into his web shop to keep product information updated with data in NAV.\n\nThe production manager wants to have the file in a predefined location on his hard drive. The location has been defined in a NAV setup table.\nThe NAV Developer The NAV developer has written a module to query the CRONUS database and to export the product list in the pre-described XML format required by the web shop. He saves the data in a temporary server file created with this code:\nServerFileName:=FileManagement.ServerTempFileName('xml');When the file has been populated with the latest product data, the NAV developer uses the following call to download the file from the temporary location on the server to the predefined location on the client:\nFileManagement.DownloadToFile(ServerFileName,ClientFileName);The call to DownloadToFile is part of the File Management codeunit, and it embeds the silent download offered by DownloadTempFile:\nPROCEDUREDownloadToFile@13(ServerFileName@1002:Text;ClientFileName@1000:Text);VARTempClientFileName@1001:Text;BEGINValidateFileNames(ServerFileName,ClientFileName);TempClientFileName:=DownloadTempFile(ServerFileName);MoveFile(TempClientFileName,ClientFileName);ENDConsequences Even today, there is no fully silent up or download. The user will get a warning stating the system is trying to run a client side .NET component. However when dismissing this warning, the user can show to not see it again. Due to client side .NET interop and of security concerns, silently downloading/uploading files on the web is disabled. Therefore, this pattern is recommended for implementation with Windows clients only. ","categories":"","description":"","excerpt":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/silent-file-upload-and-download/","tags":"","title":"Silent File Upload and Download"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: The pattern described in this article applies to Dynamics NAV only. For the general definition of the Singleton pattern, see for example this link.\nProblem: As a C/AL developer, you need to coordinate action (through a codeunit) or store information (in a table) that is unique across the system.\nForces:\n Lost reference to centralizer: An instance of a relevant object could attempt to centralize control or data in the system. However, once this object is no longer in scope, the reference to it is lost and cannot be retrieved for later coordination Cannot rebuild the initial state: A new instance of the same object could be created, however the last known state of the lost instance cannot be known anymore. Solution: create an object which resides in memory in a single copy (instance). Have a way to retrieve this unique object from code. This object can either be a Singleton Table, or a Singleton Codeunit.\nThe implementation varies depending on the technology and language used. In object-oriented (OO) languages like C#, C++ or Java, the Singleton uses static classes and class members to instantiate. There is a mechanism to ensure only one instance of the object can exist. This mechanism is many times explicit (like in OO languages) and sometimes implicit as part of the compiler or platform (as it is in NAV).\nBenefits:\n Centralization: the setup information is stored in a single well-known place and easily retrievable from anywhere in the application code, by invoking a Record.GET. In case of a single-instance codeunit, any reference to it will retrieve the same instance, so the context will be preserved. Persistence: information remains even after the instance goes out of scope, because it continues to live in memory. Limitation: The generic object-oriented Singleton pattern permits instantiation of a limited number n of objects (where usually n=1, but it can have other positive values too). However, in Dynamics NAV, the Singleton patterns are limited: n is always 1.\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nContext: …","ref":"/docs/navpatterns/patterns/singleton/","tags":"","title":"Singleton"},{"body":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nProblem: In some situations, global state needs to be preserved at runtime throughout a session.\nThere are functionality areas in NAV where centralized application management code is needed, like for example managing permissions, notifications, the debugger etc. State needs to be preserved across calls to the management codeunit.\nFor example:\n The debugger needs to remember the session which is being debugged The permission manager has a testability function, where it can be set to emulate that its running as a SaaS (Software As A Service the cloud) platform, even when the tests run in a “on-premise” local lab. Take for example the following test of Azure ML (Azure Machine Learning) integration with NAV.\nContext: Azure Machine Learning services are paid. However, Dynamics NAV includes a monthly pre-paid quota of Azure ML, which can be used for free by the users. There is an upper limit to this quota, and when it is reached, Azure ML services are turned off until the next month starts and a new quota becomes available for consumption.\nThe test below checks that, when the monthly quota is exceeded, then the function IsAzureMLLimitReached returns TRUE.\n[Test]PROCEDUREAzureMLProcessingTimeExceedsLimit@11();VARAzureMachineLearningUsage@1004:Record2002;ProcessingTime@1000:Decimal;BEGIN// [SCENARIO] Azure Machine Learning Processing time exceeds AzureML limit // [GIVEN] AzureMachineLearningUsage \u003e 0 Initialize;// calls PermissionManager.SetTestabilitySoftwareAsAService(TRUE); ProcessingTime:=LibraryRandom.RandDec(1000,2);AzureMachineLearningUsage.IncrementTotalProcessingTime(ProcessingTime);// [WHEN] When IsAzureMLLimitReached is invoked with Limit more than Processing time // [THEN] HasAzureLimitReached returns TRUE Assert.IsTrue(AzureMachineLearningUsage.IsAzureMLLimitReached(ProcessingTime-1),'HasAzureLimitReached returns wrong value when Processing time exceeds Limit.');PermissionManager.SetTestabilitySoftwareAsAService(FALSE);END;The figure below explains what happens when the Permission Manager is not a singleton. When it is invoked from different places (first from the test, second from the production code), then different instances of the Permission Manager will fire up and answer. In detail:\n The test calls Initialize which sets SaaS=TRUE in codeunit Permission Manager The test calls into production code to validate it works as expected. It calls AzureMachineLearningUsage codeunit to find out if the monthly quota has been reached. The function IsAzureMLLimitReached in AzureMachineLearningUsage codeunit is designed only for SaaS. If the code doesnt run in SaaS, then it always returns FALSE. Therefore, a call to PermissionManager is made, to find out if the environment is SaaS. However, a different instance of Permission Manager is reached and instance where SaaS was never set to TRUE. This is a mistake the test intended to simulate SaaS, but the state it set in the beginning is not reachable from production code. The production code will assess (wrongly) that its not running SaaS, and say that the Azure ML limit has not been reached (incorrect and the test fails). \nSolution: restrict the number of instantiations of a codeunit to only one, by setting the codeunit property SingleInstance to Yes.\nReturning to the previous example, lets analyze the case when the codeunit Permission Manager is a singleton codeunit:\n\nWhen the codeunit Permission Manager is a singleton, then no matter from where it is invoked, the same instance will be reached. Therefore, the status set by the test (SaaS = TRUE) will be reachable from the production code, and the test will pass, as seen in the figure below.\n\nConsequences\n1. Use Singleton Codeunit with care and only when there is no other solution. Preserving a global state could often enough be more harmful than useful. One risk is that tests might fail apparently non-deterministically.\nFor example, a problem we have met in the development team for Madeira release, was that the singleton codeunit function PermissionManager.SetSoftwareAsAService(TRUE) is often used to emulate and test SaaS conditions. However, if a test forgets to reset the state to default (FALSE), then another codeunit which is not supposed to emulate SaaS, will suddenly run as SaaS and will fail. Even if the test has code that resets the state to FALSE, this code might never be reached because of an earlier failure or other error in the test which would stop execution.\n2. The singleton codeunit is only “alive” for the current session. If the user logs out, the old session is closed and the singleton cleared out so any values stored in the old sessions singleton will be lost when the session was closed. When the user logs in again, a new session (with a new fresh instance of the singleton) will be created.\nNAV Usages\nMost of the usages in NAV refer to the so-called “management codeunits”. The management codeunits are needed to run, in a centralized way, various modular parts of the application (features), like the CRM integration, Permissions, Workflows etc. Some of the Singleton Codeunits in NAV are listed below:\n Codeunit 423 Change Log Management Codeunit 1503 Workflow Record Management Codeunit 1511 Notification Lifecycle Mgt. Codeunit 1629 Office Attachment Manager Codeunit 1632 Office Error Engine Codeunit 5150 Integration Management Codeunit 9002 Permission Manager Etc. Note: while the object-oriented Singleton pattern can restrict the number of instantiations of the singleton to an integer n \u003e 0, in Dynamics NAV the Singleton Codeunit can only have n=1.\n","categories":"","description":"","excerpt":"By Bogdana Botez at Microsoft Development Center Copenhagen\n\nProblem: …","ref":"/docs/navpatterns/patterns/singleton/singleton-codeunit/","tags":"","title":"Singleton Codeunit"},{"body":"Singleton Table By Elly Nkya at Microsoft Development Center Copenhagen\n\nProblem: The developer needs to define a single record that can contain a set of rules and behavior (optional, mandatory, or defaulting mechanisms), that apply to a functionality, and can be configured by a user.\nForces\n You want a central place to define the address and logo of your company (see Company Information table). You want to define the no. series that should be used for your sales documents (see Sales \u0026 Receivables Setup table). You want to know whether your sales documents should be archived (see Sales \u0026 Receivables Setup table). You want to define the rounding accuracy your system should (see General Ledger Setup table). Solution: Define a single record that can contain a set of rules and behavior (optional, mandatory, or defaulting mechanisms), that apply to a functionality, and can be configured by a user.\nIn a functionality that is large enough (such as sales, inventory, fixed) you may want to define a global set of rules, that are configurable by the user.\nImplementation\n1. Define: Create a Setup Table with Dummy a Primary Key. Typically with type Code=10. Then add fields to define the global rules.\n2. Instantiate: Place the instantiation code in a central place where it is guaranteed to be invoked before the functionality uses it. This is done in Codeunit 2.\n3. Enforce: Give the user access to the record so that he can change the default setup, by creating a Card page. On the page, enforce the singleton to prevent deletion of the record or insertion of a new record\n4. Use: Access the rule in code and use it\nNAV Usages\nRounding rules for Unit-Amounts and Amounts are implemented using the Singleton pattern.\n1. Define: The General Ledger Setup is used for this.\n2. Instantiate: In codeunit 2, the following code is invoked\nWITHGLSetupDOIFNOTFINDFIRSTTHENBEGININIT;INSERT;END;3. Enforce: On the General Ledger Setup. The following properties are setup:\nDeleteAllowed=false,InsertAllowed=false4. Use: Access the rounding rules are used\n... GLSetup.GET;UnitCostCurrency:=ROUND(...,GLSetup.\"Unit-Amount Rounding Precision\");... Or if accessing the rule multiple times and performance is a consideration, use lazy instantiation:\n... GetGLSetup;UnitCostCurrency:=ROUND(...,GLSetup.\"Unit-Amount Rounding Precision\");... LOCALGetGLSetup() IFNOTGLSetupReadTHENGLSetup.GET;GLSetupRead:=TRUE;Related topics\nSingleton design pattern.\nThe Singleton Table has two established applications in Dynamics NAV:\n Setup Tables which are commonly storing user setup data in NAV, Cue Tables used to calculate values for the visual representation of Cues on the NAV role center pages. YouTube Video of NAV Singleton:\n ","categories":"","description":"","excerpt":"Singleton Table By Elly Nkya at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/singleton/singleton-table/","tags":"","title":"Singleton Table"},{"body":"There must be exactly one space character on each side of a binary operator such as = + - AND OR =. The parameter comma operator however, should have no spaces.\nBad code\n\"Line Discount %\":=\"Line Discount Amount\"/\"Line Value\"*100Good code\n\"Line Discount %\":=\"Line Discount Amount\"/\"Line Value\"*100;Bad code\nStartDate:=CALCDATE('\u003c+'+FORMAT(Days+i)+'D\u003e',StartDate);Good code\nStartDate:=CALCDATE('\u003c+'+FORMAT(Days+i) +'D\u003e',StartDate);Bad code\nStartDate:=0D;// Initialize Good code\nStartDate:=0D;// Initialize ","categories":"","description":"","excerpt":"There must be exactly one space character on each side of a binary …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/spacing-binary-operators/","tags":"","title":"Spacing Binary Operators"},{"body":"There must be no spaces characters before and after [] dimension brackets symbols or :: option symbols.\nBad code\nA[i][j]:=Amt;Good code\nA[i][j]:=Amt;Bad code\n\"Currency Exchange Rate\".\"Fix Exchange Rate Amount\"::Currency:Good code\n\"Currency Exchange Rate\".\"Fix Exchange Rate Amount\"::Currency:Bad code\nIFFIND(Which) THENGood code\nIFFIND(Which) THEN","categories":"","description":"","excerpt":"There must be no spaces characters before and after [] dimension …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/spacing-brackets-and/","tags":"","title":"Spacing Brackets and ::"},{"body":"There must be no space between a unary operator and its argument (except for the NOT keyword).\nBad code\nIFNOT(Type=Type::Item) THENGood code\nIFNOT(Type=Type::Item) THENBad code\nDiscAmt:=-\"Discount Amount\";Good code\nDiscAmt:=-\"Discount Amount\";","categories":"","description":"","excerpt":"There must be no space between a unary operator and its argument …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/spacing-unary-operators/","tags":"","title":"Spacing Unary Operators"},{"body":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nMeet the Standard Journal pattern, which gives the NAV user the advantage of storing transaction details and reusing them multiple times at later dates. For example, this is how to pay a monthly bill.\nAbstract If the journal data can be reused later, the user has the possibility to save the current temporary transaction details. One example can be the case of monthly electricity payments. The user will manually enter the details for the first payment, of the current month. Next month, a part of the data will be the same, such as the vendor and transaction details. If the user has saved the initial monthly payment as a standard journal, then they can now reuse it to create the draft of the next monthly payment. Once the draft journal lines are created, they can be updated with the current month information.\nDescription When a journal is created, the user can invoke the Save as Standard Journal action to save the current journal for later use. When saving the journal as a standard journal, the user is required to choose a code, which is later used to identify the saved journal. The journal lines are stored in a separate table. There can be one standard journal saved per journal type and code.\nLater, the user can create new journal lines by using the Get Standard Journals action. This action restores the saved journal into the new journal lines.\nScenario Step 1: The data entered by the user through the Journal page is stored temporarily in the Journal Line table. The data is available for editing or deleting. The journal line data will be stored in this table until it is either deleted or posted.\nStep 2: The user decides to save the current journal line entries for later use. If this is the monthly rent, the user may want to use similar entries next month when a new payment is due. On the Journal page, the user invokes the Save as Standard Journal action. This triggers the Save as Standard Journal report, which copies the entries from the Journal Line table to the Standard Journal Line table. When saving, the user will be asked for an identifier, a code, which will be used to later uniquely identify the saved entries.\nStep 3: When the user invokes the Get Standard Journal action, a list of codes are presented to the user so that they can decide which standard journal to restore and copy in the Journal Line table.\n\n\nThe sequence flow of the three steps is described in the following diagram.\n\nNAV Specific Example In the standard version of NAV, the Standard Journal functionality is implemented in the following journals:\n Item Journal, which saves data to the Standard Item Journal General Journal, which saves data to the Standard General Journal General Journal The user enters data in the General Journal page (39) and invokes the Save/Get actions as illustrated in the following screenshot:\n\nWhen saving the journal lines, the Save as Standard Gen. Journal report (750) is invoked. The report saves the entries in the Standard General Journal Line table (751).\nNAV Usages Standard General Journal Standard Item Journal ","categories":"","description":"","excerpt":"By Bogdana Botez, at Microsoft Development Center Copenhagen\nMeet the …","ref":"/docs/navpatterns/patterns/standard-journal/","tags":"","title":"Standard Journal"},{"body":"Call objects statically whenever possible. It reduces extra noise and removes extra variables. Downside: changing the name of the object which is called statically will need a code update.\nBad code\nLOCAL PROCEDURE Code@1(); VAR CAJnlPostBatch@1001 : Codeunit 1103; BEGIN CAJnlPostBatch.Run(CostJnlLine); END; Good code\nLOCAL PROCEDURE Code@1(); BEGIN CODEUNIT.RUN(CODEUNIT::\"CA Jnl.-Post Batch\",CostJnlLine); END; ","categories":"","description":"","excerpt":"Call objects statically whenever possible. It reduces extra noise and …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/static-object-invocation/","tags":"","title":"Static Object Invocation"},{"body":"Suggested Abbreviations Whenever possible, do not use abbreviations in variables, functions and objects names.\nIf there is no other choice, then use the suggestions below.\nAbbreviation\nText\nAbs\nabsence\nAcc\naccount\nAcc\naccounting\nAccum\naccumulated\nAct\naction\nActiv\nactivity\nAdd\nadditional\nAddr\naddress\nAdj\nadjust\nAdjd\nadjusted\nAdjmt\nadjustment\nAgrmt\nagreement\nAlloc\nallocation\nAllow\nallowance\nAlt\nalternative\nAmt\namount\nAmts\namounts\nAns\nanswer\nAppl\napplies\nAppln\napplication\nArriv\narrival\nAsm\nassembly\nATO\nassemble to order\nAssgnt\nassignment\nAssoc\nassociated\nAttmt\nattachment\nAuth\nauthorities\nAuto\nautomatic\nAvail\navailability\nAvg\naverage\nBA\nba db.\nBal\nbalance\nBOM\nbill of materials\nBlnkt\nblanket\nBudg\nbudget\nBuf\nbuffer\nBus\nbusiness\nBIM\nbusiness interaction management\nBuy\nbuying\nCalc\ncalculate\nCalcd\ncalculated\nCalcu\ncalculation\nCal\ncalendar\nCap\ncapacity\nCRP\ncapacity requirements planning\nCF\ncash flow\nCF\ncashflow\nctlg\ncatalog\nCat\ncategory\nCPU\nCentral Processing Unit\nCtr\ncenter\nChg\nchange\nChgs\nchanges\nChar\ncharacter\nChars\ncharacters\nChrg\ncharge\nChrgs\ncharges\nChk\ncheck\nClass\nclassification\ncoll\ncollection\ncol\ncolumn\nCmt\ncomment\nCo\ncompany\nComp\ncomponent\nCmpltn\ncompletion\nComps\ncomponents\nCompn\ncomposition\nCompr\ncompression\nConcrnt\nconcurrent\nConf\nconfidential\nCnfrmn\nconfirmation\nConfl\nconflict\nConsol\nconsolidate\nConsolid\nconsolidation\nConsump\nconsumption\nCont\ncontact\nCntr\ncontainer\nContr\ncontract\nContrd\ncontracted\nCtrl\ncontrol\nCtrls\ncontrols\nConv\nconversion\nCor\ncorrection\nCorres\ncorrespondence\nCorresp\ncorresponding\nCst\ncost\nCOGS\nsold\nCr\ncredit\nCumul\ncumulate\nCurr\ncurrency\nCrnt\ncurrent\nCust\ncustomer\nCV\ncustomer/vendor\nDly\ndaily\nDamp\ndampener\nDBMS\ndatabase management system\nD\ndate\nDef\ndefinition\nDemo\ndemonstration\nDept\ndepartment\nDP\ndepartment/project\nDepr\ndepreciation\nDesc\ndescription\nDtl\ndetail\nDtld\ndetailed\nDtls\ndetails\nDev\ndeviation\nDiff\ndifference\nDim\ndimension\nDir\ndirect\nDisc\ndiscount\nDiscr\ndiscrete\nDistr\ndistribute\nDistrd\ndistributed\nDistbtr\ndistributor\nDistrn\ndistribution\nDoc\ndocument\nDupl\nduplicate\nEntrd\nentered\nEngin\nengineering\nExch\nexchange\nExcl\nexcluding\nExec\nexecute\nExpd\nexpected\nExped\nexpedited\nExp\nexpense\nExpr\nexpression\nExpir\nexpiration\nExt\nextended\nExpl\nexplode\nExpt\nexport\nFnl\nfinal\nFin\nfinance\nFisc\nfiscal\nFnshd\nfinished\nFA\nfixed asset\nFwd\nforward\nFrt\nfreight\nGen\ngeneral\nGL\ngeneral ledger\nGr\ngroup\nHdr\nheader\nHist\nhistory\nHol\nholiday\nHR\nhuman resource\nID\nidentification\nImp\nimport\nInbnd\ninbound\nIncl\nincluding\nIncld\nincluded\nIncmg\nincoming\nISV\nindependent software vendor\nIndust\nindustry\nInfo\ninformation\nInit\ninitial\nIntra\nIntrastat\nInteract\ninteraction\nIntegr\nintegration\nInt\ninterest\nIntm\nInterim\nIP\ninternal protocol\nInvt\ninventory\nInvtbl\ninventoriable\nInv\ninvoice\nInvd\ninvoiced\nIT\nitem tracking\nJnl\njournal\nLang\nlanguage\nLedg\nledger\nLvl\nlevel\nLn\nline\nLt\nlist\nLCY\nlocal currency\nLoc\nlocation\nMail\nmailing\nMaint\nmaintenance\nMgt\nmanagement\nMan\nmanual\nMfg\nmanufacturing\nMfr\nmanufacturer\nMat\nmaterial\nMktg\nmarketing\nMax\nmaximum\nMeas\nmeasure\nMsg\nmessage\nMin\nminimum\nMisc\nmiscellaneous\nMod\nmodify\nMth\nmonth\nNeg\nnegative\nNonInvtbl\nnon-inventoriable\nNotif\nnotification\nNo\nnumber\nNos\nnumbers\nObj\nobject\nOper\noperating\nOpp\nopportunity\nOrd\norder\nOrds\norders\nOrig\noriginal\nOrg\norganization\nOutbnd\noutbound\nOutg\nOutgoing\nOut\noutput\nOutstd\noutstanding\nOvhd\noverhead\nPmt\npayment\nPct\npercent\nPersnl\npersonnel\nPhys\nphysical\nPic\npicture\nPlng\nplanning\nPstd\nposted\nPost\nposting\nPos\npositive\nPrec\nprecision\nPrepmt\nprepayment\nProd\nproduct\nProd\nproduction\nProdOrd\nproduction order\nProj\nproject\nProp\nproperty\nPrspct\nprospect\nPurch\npurchase\nPurch\npurchases\nPurchr\npurchaser\nPurchOrd\npurchase order\nQlty\nquality\nQty\nquantity\nQuestn\nquestionnaire\nQte\nquote\nRF\nradio frequency\nRng\nrange\nRcpt\nreceipt\nRcd\nreceived\nRec\nrecord\nRecs\nrecords\nRecncl\nreconcile\nRecon\nreconciliation\nRecur\nrecurring\nRef\nreference\nReg\nregister\nRegn\nregistration\nRegd\nregistered\nRel\nrelation\nRels\nrelations\nRlshp\nrelationship\nRlse\nrelease\nRlsd\nreleased\nRem\nremaining\nRmdr\nreminder\nRepl\nreplacement\nRplnsh\nreplenish\nRplnsht\nreplenishment\nRpt\nreport\nRep\nrepresent\nRepd\nrepresented\nRqst\nrequest\nReqd\nrequired\nReqt\nrequirement\nReqts\nrequirements\nReq\nrequisition\nRsv\nreserve\nRsvd\nreserved\nReserv\nreservation\nResol\nresolution\nRes\nresource\nRsp\nresponse\nResp\nresponsibility\nRtn\nretain\nRtnd\nretained\nRet\nreturn\nRets\nreturns\nRevaln\nrevaluation\nRev\nreverse\nRvw\nreview\nRnd\nround\nRndd\nrounded\nRndg\nrounding\nRte\nroute\nRtng\nrouting\nRout\nroutine\nSales\nsales \u0026 receivables\nSaf\nsafety\nSched\nschedule\nSec\nsecond\nSeg\nsegment\nSel\nselect\nSelctn\nselection\nSeq\nsequence\nSer\nserial\nSN\nserial number\nServ\nservice\nSh\nsheet\nShpt\nshipment\nSrc\nsource\nSpcl\nspecial\nSpec\nspecification\nSpecs\nspecifications\nStd\nstandard\nSF\nfrequency\nStmt\nstatement\nStat\nstatistical\nStats\nstatistics\nStk\nstock\nSKU\nstockkeeping unit\nStm\nstream\nSQL\nstructured query language\nSubcontr\nsubcontract\nSubcontrd\nsubcontracted\nSubcontrg\nsubcontracting\nSub\nsubstitute\nSubst\nsubstitution\nSug\nsuggest\nSugd\nsuggested\nSugn\nsuggestion\nSum\nsummary\nSuspd\nsuspended\nSympt\nsymptom\nSynch\nsynchronize\nTemp\ntemporary\nTot\ntotal\nTransac\ntransaction\nTrans\ntransfer\nTransln\ntranslation\nTrkg\ntracking\nTblsht\ntroubleshoot\nTblshtg\ntroubleshooting\nUOM\nunit of measure\nUT\nunit test\nUnreal\nunrealized\nUnrsvd\nunreserved\nUpd\nupdate\nValn\nvaluation\nVal\nvalue\nVAT\nvalue added tax\nVar\nvariance\nVend\nvendor\nWhse\nwarehouse\nWS\nweb shop\nWksh\nworksheet\nGL\ng/l\nPct\n%\nThree-Tier\n3-tier\nOsynch\nOutlook Synch\n ","categories":"","description":"","excerpt":"Suggested Abbreviations Whenever possible, do not use abbreviations in …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/suggested-abbreviations/","tags":"","title":"Suggested Abbreviations"},{"body":"This is a guideline, some parts are optional (if theres no content, remove the whole paragraph).\n\u003cYour name here in italics, plus your company name\u003e\n«Pattern Title\u003e\u003e Short, descriptive and easy to remember.\nPattern Logo Black \u0026 white, no text on it.\n\nContext: Sets the stage where the pattern takes place. 1-2 sentences.\nProblem: What happens before this pattern is used? How can it go wrong? 1-5 lines.\nForces: (explain why the problem is difficult to solve; state the considerations that must be taken into account when choosing a solution to a problem)\n «**Force 1: **short description (What is the impact of not using this pattern? Or using only partially?) \u003e\u003e «**Force 2: **short description \u003e\u003e … Solution: 1-2 sentences. The full description will come below.\n«Solution descriptions\u003e\u003e\n«Diagrams. Please add numbers and captions to both figures and tables\u003e\u003e\nUsage: «short usage description\u003e\u003e\n«Examples\u003e\u003e\n«Where its used in Dynamics NAV\u003e\u003e\nBenefits:\n **« Benefit 1: **solves Force 1, short description\u003e\u003e **« Benefit 2: **solves Force 2, short description\u003e\u003e … Consequences:\n **«Consequence 1: **are there any drawbacks? Is there anything the developer needs to be aware of when implementing this pattern? Any known limitations? \u003e\u003e … List of references\n","categories":"","description":"","excerpt":"This is a guideline, some parts are optional (if theres no content, …","ref":"/docs/navpatterns/4-get-involved/template-for-writing-nav-design-patterns/","tags":"","title":"Template for writing Nav Design Patterns"},{"body":"This is a guideline, some parts are optional (if theres no content, remove the whole paragraph).\n\u003cCreated by (company), Described by (company)\u003e\nDescription In depth description on what this Pattern is all about\n basic components how the interact steps to implement considerations to take Bad code PutCodeblocksHere() Good code PutCodeblocksHere() Discussions \u003cPlease replace the “TITLEOFYOURGUIDELINEGOESHERE” in the link above, with the Title+of+the+Guideline (indeed, with “space” replaced by a “+\") - and remove this line. \u003e\nYou can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":"","description":"","excerpt":"This is a guideline, some parts are optional (if theres no content, …","ref":"/docs/contributing/templates/guidelines/","tags":"","title":"Title of the Guideline"},{"body":"This is a guideline, some parts are optional (if theres no content, remove the whole paragraph).\n\u003cCreated by (company), Described by (company)\u003e\nAbstract Short, descriptive and easy to remember description of this pattern.\nContext Sets the stage where the pattern takes place. 1-2 sentences.\nProblem What happens before this pattern is used? How can it go wrong? 1-5 lines.\nDescription In depth description on what this Pattern is all about\n basic components how the interact steps to implement considerations to take Usage If applicable: where is it used in an app. You can refer to any app, BaseApp, or a (public) ISV app.\nBenefits 1-2 sentences: what did you just solve\nWhen not to use Usually, there are occasions where NOT to implement the pattern. List the disadvantages of this pattern here.\nList of references Youtube-link? BaseApp? Tweet? …\nDiscussions Create a discussions-page of your pattern, and add the sentence “You can discuss this pattern here” with the right link to that discussions-page.\n","categories":"","description":"","excerpt":"This is a guideline, some parts are optional (if theres no content, …","ref":"/docs/contributing/templates/patterns/","tags":"","title":"Title of the pattern"},{"body":"Originally by Abhishek Ghosh, at Microsoft Development Center Copenhagen\nAbstract This pattern generates the data to be displayed dynamically by combing/processing several data sources. It then displays the resulting dataset without writing to the database.\n\nDescription While writing reports in NAV, we have the luxury of using a built-in iterator. So, once we define the dataitem and the ordering, the runtime takes care of the iteration.\nThe iterator has one shortcoming: It can only run through records written into the database. There are situations, however, where we want to display temporary datasets created at runtime by processing data from different sources. That is where the Temporary Dataset Report pattern can be used.\nUsage This pattern takes a two-step approach to displaying the data:\n Parse the data sources to create a record buffer in a temporary record variable.\n Iterate through a dataitem of the Integer table and display one record from the temporary recordset in each iteration.\n Step 1: Combining data sources to create a dataset In this step, we would process the existing data to create a temporary recordset. The three most common techniques to do this are discussed in the following paragraphs.\nThe first technique is mostly used when we want to build the report based on one or more source tables. A lot of processing is required, and we therefore want to store and display information from a temporary recordset. With this technique, we create a dataitem of the source record and then iterate through this dataitem to create the temporary recordset. An advantage of this technique is that it allows the user to perform additional filtering on the data source tables since they are added as additional dataitems and therefore will have their tabs on the request page by default.\n\nThe second technique was made available with NAV 2013 when queries were introduced as a tool to help us combine data from different sources. Instead of writing data into a temporary record variable, we can create a query to combine the data from different sources. This offers better performance than the first technique in almost every situation. However, with a query, we sacrifice the luxury of getting a flexible filtering on the request page for the source dataitem.\nThe third technique is to write a function (or a codeunit, if the complexity demands so) that will crunch the data and create the temporary record variable. This function must be invoked from the OnPreReport trigger (or the OnPreDataItem trigger of the Integer dataitem).\n\nThe following table summarizes when to use each of the three techniques:\n Technique When to Use Source Record DataItem When it is important to offer flexible filtering possibilities on the source data. Query When performance is critical. Populating temporary table in a function Only when the source dataset is too complex to use either of the other techniques. Step 2: Iterating through the Integer dataitem When you have created the dataset as a temporary record variable or a query, the next step is to iterate through them to display the information. However, the report controller in NAV cannot iterate through temporary records or through the results of a query. This is where the Integer table comes into use.\nThe Integer table is a virtual table with only one field, Number, which is an integer field. For all practical purposes, we can assume that this table has pre-inserted records with value of Number, starting from 1 and ending with the highest integer value. So, if we keep iterating through this dataitem, the value of the Number field will be 1 for the first iteration and will keep increasing by 1 for every iteration.\nThere are two ways to use the Integer dataitem to iterate through the temporary recordset:\n Loop for an indeterminate number of times until you reach the end of the recordset.\n Calculate the number of records in the temporary recordset in advance and then iterate that many number of times.\n With the first approach, in the Integer-OnAfterGetRecord trigger, you must make the temporary record variable move to the next record, follow that up with a check if you have reached the end of the recordset, and then use CurrReport.BREAK if you have reached the end.\nWith the second approach, you must limit the number of times the report iterates through the Integer dataitem. The Number field in the Integer table will have a value of 1 in the first iteration and will increment automatically by 1 on every subsequent iteration. To ensure that the report iterates through the Integer dataitem “n” times, you must, therefore, filter the Integer dataitem on Number = 1..n. You must also move the temporary record variable to the next record in every iteration of the Integer-OnAfterGetRecord trigger. NOTE: This technique cannot be used if you use queries as the temporary data source, since queries do not (in NAV 2013) return the number of records.\nExample Goal: To print a report that lists all contacts that have open documents (both sales and purchase) and displays those documents in chronological order\nA contact can be connected to a vendor or a customer using the Create As Customer/Vendor function on the Contact Card. When a sales/purchase document is created for this customer/vendor, the Contact No. is stored in the Sell-to Contact No. or Buy-from Contact No. fields of the sales and purchase documents. The obvious choice would be to display the data directly from the Sales Header and Purchase Header records. However, the requirement is to display all of them together chronologically, which means they will need to be stored in, and be read from, one common dataset.\nStep 1: Design a new table that will hold the temporary dataset.\nThe UI must display the Document Type, Document No., Document Date, Amount Incl. VAT and the name of the salesperson or purchaser. The table is designed as follows.\n\nSince this table is used to sort the data by Document Date, a “Document Date” key is added to the table.\n\nSome additional properties to note:\n Sales Header dataitem should be linked to the Contact dataitem through the DataItemLink property “Sell-to Contact No.=FIELD(No.)”\n Purchase Header dataitem should be linked to the Contact dataitem through the DataItemLink property “Buy-from Contact No.=FIELD(No.)”\n Step 2: In the Sales Header OnAfterGetRecord, write the following code to populate the data buffer:\n\nWhere:\n ContactDocumentBuffer is a temporary global variable of the buffer table created.\n SalesPerson is a local record variable for table 13.\n SalesTxt is a text constant denoting “Sales” in ENU.\n Similar code must be written in Purchase Header OnAfterGetRecord to store data from the purchase documents into the buffer.\nStep 3: Iterate through the temporary records in the Integer dataitem.\nSince the requirement is to sort the data by Document Date, we must sort the ContactDocumentBuffer table by this key. Also, by the time the execution of Integer OnPreDataItem begins, the number of records in the temporary buffer should be known already. Therefore, we can limit the number of times to repeat the Integer dataitem to the number of records in the buffer.\nWe meet both requirements with the following lines of code in Integer - OnPreDataItem:\nContactDocumentBuffer.SETCURRENTKEY(\"Document Date\");SETRANGE(Number,1,ContactDocumentBuffer.COUNT);Lastly, we must move the record pointer by 1 record every time we loop through the Integer dataitem. So, in Integer OnAfterGetRecord, we add the following lines of code:\nIFNumber=1THENContactDocumentBuffer.FINDFIRSTELSEContactDocumentBuffer.NEXT;Now, the only task that remains is to design the RDLC layout. (Not part of this application pattern description.)\nNAV Usages\nThis is a commonly used pattern in several reports, such as:\n Report 204 Sales Quote\n Report 205 Order Confirmation\n Report 206 Sales Invoice\n ","categories":"","description":"","excerpt":"Originally by Abhishek Ghosh, at Microsoft Development Center …","ref":"/docs/navpatterns/patterns/temporary-dataset-report/","tags":"","title":"Temporary Dataset Report"},{"body":"The name of a temporary variable must be prefixed with the word Temp and not otherwise.\nBad code\nJobWIPBuffer@1002:TEMPORARYRecord1018;Good code\nTempJobWIPBuffer@1002:TEMPORARYRecord1018;Bad code\nTempJobWIPBuffer@1002:Record1018;Good code\nCopyOfJobWIPBuffer@1002:Record1018;","categories":"","description":"","excerpt":"The name of a temporary variable must be prefixed with the word Temp …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/temporary-variable-naming/","tags":"","title":"Temporary Variable Naming"},{"body":"TextConst variable names should have a suffix (an approved three-letter suffix: Msg, Tok, Err, Qst, Lbl, Txt) describing usage.\nBad code\nCannotDeleteLine@1005:TextConst'ENU=You cannot delete this line because one or more rating values exists.';... ERROR(CannotDeleteLine,TABLECAPTION);Good code\nCannotDeleteLineErr@1005:TextConst'ENU=You cannot delete this line because one or more rating values exists.';... ERROR(CannotDeleteLineErr,TABLECAPTION);Bad code\nText000@1011:TextConst'ENU=\"has been changed (initial a %1: %2= %3, %4= %5)\"';... SalesLine.FIELDERROR(Type,STRSUBSTNO(Text000,...);... Good code\nTypeHasBeenChangedErr@1011:TextConst'ENU=\"has been changed (initial a %1: %2= %3, %4= %5)\"';... SalesLine.FIELDERROR(Type,STRSUBSTNO(TypeHasBeenChangedErr,...);... Bad code\nText004@1004:TextConst'ENU=Indenting the Job Tasks \\#1\\#\\#\\#\\#\\#\\#\\#\\#\\#\\#.';... Window@1007:Dialog;... Window.OPEN(Text004);Good code\nIndentingMsg@1004:TextConst'ENU=Indenting the Job Tasks \\#1\\#\\#\\#\\#\\#\\#\\#\\#\\#\\#.';... Window@1007:Dialog;... Window.OPEN(IndentingMsg);Bad code\nText002@1005:TextConst'ENU=You cannot delete a %1 that is used in one or more setup windows.\\\\ Do you want to open the G/L Account No. Where-Used List Window?';... IFCONFIRM(Text002,TRUE,GLAcc.TABLECAPTION) THENGood code\nOpenWhereUsedWindowQst@1005:TextConst'ENU=You cannot delete a %1 that is used in one or more setup windows.\\\\ Do you want to open the G/L Account No. Where-Used List Window?';... IFCONFIRM(OpenWhereUsedWindowQst,TRUE,GLAcc.TABLECAPTION) THENBad code\nSelection:=STRMENU(Text003,2);... Text003@1002:TextConst'ENU=\u0026Copy dimensions from BOM,\u0026Retrieve dimensions from components';Good code\nSelection:=STRMENU(CopyFromQst,2);... CopyFromQst@1002:TextConst'ENU=\u0026Copy dimensions from BOM,\u0026Retrieve dimensions from components';Bad code\nDATASET{... {1;1;Column;Chart_of_AccountsCaption;SourceExpr=Chart_of_AccountsCaption}... Chart_of_AccountsCaption@9647:TextConst'ENU=Chart of Accounts';Good code\nDATASET{... {1;1;Column;Chart_of_AccountsCaption;SourceExpr=ChartOfAccountsLbl}... ChartOfAccountsLbl@9647:TextConst'ENU=Chart of Accounts';","categories":"","description":"","excerpt":"TextConst variable names should have a suffix (an approved …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/textconst-suffixes/","tags":"","title":"TextConst Suffixes"},{"body":"By Nikola Kukrika at Microsoft Development Center Copenhagen\nAbstract To increase discoverability and productivity, critical information, such as statistics, can be moved from separate pages onto the document where it is needed.\nFor example, documents should clearly display totals and discounts information to provide quick overview, make it easy to relate the amounts to the document currency, and to allow the user to see and apply discounts directly on the document.\nDescription Before Microsoft Dynamics NAV 2015, totals and discount information was scattered between the document and the Statistics page, which made it less discover-able and less usable for new users. It was difficult to see the discount amounts, relate the amounts to the currency of the invoice, and it was not-intuitive that you had to update the Statistics page to see updates on the document. In addition, the result of the update was not visible on the main document, which added to the confusion.\nTotals and discount information logically belongs on the document, as is the case on many competitor products.\nThe Statistics page contains too much information for most common scenarios, and only a part of the information is visible on the related document. See the following example for sales order statistics.\n\nWith the pattern implemented, selected statistics fields are placed on the sales order, as in the following example.\n\nThis new layout gives precise and complete information about totals and discounts, with discounts on the left side and totals on the right side. The currency is clearly shown, and the layout resembles a printed document. The values are always updated (with some exceptions that are explained in the next following sections), and the user can apply a discount directly on the document.\nOptions considered when deciding on the layout:\n A new FactBox A new FastTab On the Lines subpage The Lines subpage option was chosen because:\n Can be made with cleaner code Is always visible, not collapsible, as opposed to FactBox and FastTab options Less chrome in the UI Usages Concerning update of totals and discounts, the following were considered:\n All code should be in one place Existing VAT, invoice discount calculation, etc. should be reused and not re-implemented. The presentation layer should be separated from the logic. Presentation layer should have simple (one liner) calls to the logic System responsiveness should not be significantly affected Totals and discounts should be updated “on-the-fly” on any change that affects amounts The following artifacts were implemented to achieve the desired functionality.\nFlags That Totals Are Not Updated In order to always update the totals, the system must have a way to mark that a specific change should trigger a recalculation of the totals. To achieve this, the following was implemented.\n On the lines: A new field, Recalculate Invoice Discount, was added and set to FALSE by default. The UpdateAmounts function sets the new field to TRUE for any execution. This function was chosen as it is a central entry point for any amount-related change.\n\n On the header: A new FlowField, Recalculate Invoice Discount was added. This field is TRUE if at least one line (that relates to the header) has been marked as “dirty”, meaning that totals must be recalculated. \nUpdate diagram\n\nTotal Calculation and Update Logic The following new codeunits were added:\n COD56 and COD66 (one for sales and one for purchase) are responsible for the “heavy” tasks of calculating/applying totals and discounts by calling into existing code, similarly to how the Statistics page works. After recalculation, the flag field is reset on all the lines related to a specific header. These calculations, in the existing implementation, are triggered ONLY in case of UI scenarios. Non-UI scenarios are not affected. Note: In case of web-service implementations that do not use the existing pages, the total calculation and the invoice discount logic should be called specifically to display similar functionality.\nUI-Related Updates A new CU, COD57 has been added and it contains the logic used to update the fields that will, in the end, be displayed in the UI. Decision was to merge both the sales and purchase functionality into one place.\nUpdate Controls The pattern is applied to both non-posted documents (orders, invoices, etc.) and posted documents (posted Invoice, etc.). Because the posted document is a document that does not change, the implementation is simplified as follows.\nSubpage - Non-posted documents The OnAfterGetCurrRecord function call is responsible for updating the totals- and discount-related controls.\nTo avoid duplicating lots of code in many places, a single function with more parameters “pattern” was chosen. The function returns all the controls updated in a single call, as follows.\n\nManual invoice discount. One function call when applying a manual invoice discount, as follows.\n\nNote: After applying the manual discount, the lines should be refreshed as they will be changed in batch mode.\nThe following “decorators” were added to recalculate amounts on the fly:\n Totals should always be updated as soon as the user leaves the field. Code should be added to the validate triggers of the controls that are changing the amounts in order to refresh the total controls.\nNote: Amounts will not always be up to date because of the following:\n Performance. The update must be triggered manually if the number of lines is above 100. (100 was chosen because performance measurements have demonstrated that with more than 100 lines, the performance was worse than 0.5-1s in update time.) Missed/customized triggers or header changes - cannot trigger lines update from header. Likewise, lines cannot trigger the header to update. In the above cases, a link next to the totals will be displayed informing user that totals/discounts might not be updated and they can be updated by selecting the link Subpage Posted Documents Only the _OnAfterGetCurrRecord _function will have code because posted documents cannot be changed. Therefore, totals do not need to be updated.\n\nUI Presentation Layer: After Platform added support for this specific case, the layout is very simple, as follows.\n\nThis will produce the layout we wanted:\n\nUI Manual Totals Update As mentioned before, there are cases when the user is informed that totals/discounts might not be up to date and that it should select a link in order to get the updated values.\nThe link is part of the sub-part where totals and discounts are added. The visibility is controlled by actually controlling the text (message, or empty), because Platform does not support making only one visible/invisible (it must be a group). When the link is displayed, the styling is also changed for the total/discount controls, and the values are set to 0.\n\nNAV Usages We have implemented these scenarios for sales and purchase documents (order, invoice, quote, credit memos, return orders, including posted documents). Note that the implementation in NAV 2015 is a bit different than the one in NAV 2014 C5 objects (1300 range). It was decided not to merge the two implementations, among other reasons because the NAV 2014 C5 implementation does not fit the full application.\nThe pattern can easily be extended to new sales and purchase documents. If the pattern is followed, it can also be extended to other types of documents, such as in services, jobs, etc.\nNote: This new pattern is not implemented in the North America and India versions. This is due to special local features in the two versions regions and the multitude of sales tax/vat options that would make the solution non-user friendly and not optimized for performance.\nIdeas for Improvement Platform support to be able to trigger full-page update from the lines. Support does exist today, but it is not programmatically controlled at design time. This means that it cannot be used in all cases.\n ","categories":"","description":"","excerpt":"By Nikola Kukrika at Microsoft Development Center Copenhagen\nAbstract …","ref":"/docs/navpatterns/patterns/totals-and-discounts-on-subpages-sales-and-purchases/","tags":"","title":"Totals and Discounts on Subpages Sales and Purchases"},{"body":" ","categories":"","description":"","excerpt":" ","ref":"/docs/navpatterns/patterns/transfer-custom-fields/","tags":"","title":"Transfer Custom Fields"},{"body":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen\nAbstract When there is a need to use .NET classes within C/AL, one of the main challenges is to handle the exceptions the methods of these .NET classes may throw. Eventually, if not handled, they will basically bubble up as runtime errors, halting the current operation a user is doing without having a chance to properly display errors in a user-friendly format.\nDescription Using the .NET classes in order to extend NAVs functionality usually triggers the need to create an add-on assembly. This is a pretty powerful approach and opens the door for empowering NAV with new and extra functionality while harnessing the full power of .NET.\nFor example, integration with a Web service into NAV can be done to extend NAVs functionality or benefit from a service model offered through a 3rd party. To do so, it is possible to write a .NET add-in to handle the required bi-directional communication between NAV and the Web service. Alternatively, the implementation itself can be done in C/AL, with no add-in dependency. The latter option simplifies customization, deployment and upgradeability. Additionally, it builds up on the knowledge NAV developers have with C/AL programming.\nOn the other hand, not using an add-in exposes NAV to runtime errors due to unhandled exceptions that get thrown at different levels. The first is the communication layer, in which HTTP requests and responses are exchanged. The second is the business logic layer, at which the content of the requests and response is being prepared and groomed using XML Elements and being retrieved or edited based on the respective XPaths.\nWhen to Use It When .NET classes are used, they may throw exceptions upon failure. Some of these exceptions cannot pre-checked (e.g. like existence of a file on disk) and will only be figured out at runtime. Eventually, to present the error reason to a user and explain what needs to be done to address it, the exception needs to be handled gracefully. This also protects the client for unexpected crashes that may deteriorate the user experience.\nDiagram \nUsage A Try-Catch-Finally statement does not exist in C/AL. The alternative is to run the code consuming .NET objects within a TryFunction, and handle the runtime errors, as follows:\n Write the code that uses the .NET classes in a procedure whose TryFunction property is set to Yes. Invoke the TryFunction like any other procedure within the code. Handle the return value of the TryFunction within an IF..THEN statement. Write the exception handling code in a function, and call it when the return value for the TryFunction is FALSE. The exception handling function should determine which exception to handle, and pass this over to the COD1291 DotNet Exception Handler codeunit. When an exception is thrown, it is already wrapped up within an NAV exception. This means the real exception to look for is retrievable through the InnerException property of the NAV exception. Then, the next step would be to properly determine the type of that exception, and act accordingly. The COD1291 DotNet Exception Handler codeunit takes care of looping through the nested levels of inner exceptions, digging for an exception with the expected type. If found, it is retrieved; otherwise, the main (outer) exceptions message is retrieved.\nNAV Specific Example Overview The exception handling pattern is implemented in the integration with a web service for bank file format conversion. Within the respective “External Data Handling Codeunit” for that web service, communication through SOAP requests is required. Eventually, the HTTP web request and response .NET classes are used for that purpose.\nFor instance, if a failure to establish a connection to the web service due to lack of Internet access, a WebException is thrown with the relevant error details. COD1290 Web Service Mgt. codeunit wraps up the required functionality to interact with a web service in C/AL, handling all the required plumping work to send web requests, receive web responses, and extract valid and error details from the web response.\nCode Sample The “External Data Handling Codeunit” is a consumer of COD1290 Web Service Mgt. codeunit. If a runtime exception occurs, it gets handled as follows:\n[TryFunction]PROCEDURESendRequestToWebService@17();VARWebRequestHelper@1000:Codeunit1299;HttpWebRequest@1007:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpWebRequest\";HttpStatusCode@1002:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpStatusCode\";ResponseHeaders@1001:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Collections.Specialized.NameValueCollection\";ResponseInStream@1006:InStream;BEGINCheckGlobals;BuildWebRequest(GlobalURL,HttpWebRequest);ResponseInStreamTempBlob.INIT;ResponseInStreamTempBlob.Blob.CREATEINSTREAM(ResponseInStream);CreateSoapRequest(HttpWebRequest.GetRequestStream,GlobalRequestBodyInStream,GlobalUsername,GlobalPassword);WebRequestHelper.GetWebResponse(HttpWebRequest,HttpWebResponse,ResponseInStream,HttpStatusCode,ResponseHeaders,GlobalProgressDialogEnabled);ExtractContentFromResponse(ResponseInStream,ResponseBodyTempBlob);END;LOCALPROCEDURESendDataToConversionService@1(VARPaymentFileTempBlob@1003:Record99008535;BodyTempBlob@1004:Record99008535;PostingExch@1007:Record1220);VARBankDataConvServiceSetup@1000:Record1260;WebServiceRequestMgt@1001:Codeunit1290;BodyInStream@1005:InStream;ResponseInStream@1002:InStream;BEGINIFNOTBodyTempBlob.Blob.HASVALUETHENERROR(NoRequestBodyErr);PrepareSOAPRequestBody(BodyTempBlob);COMMIT;BankDataConvServiceSetup.GET;BodyTempBlob.Blob.CREATEINSTREAM(BodyInStream);WebServiceRequestMgt.SetGlobals(BodyInStream,BankDataConvServiceSetup.\"Service URL\",BankDataConvServiceSetup.\"User Name\",BankDataConvServiceSetup.GetPassword);IFNOTWebServiceRequestMgt.SendRequestToWebServiceTHENWebServiceRequestMgt.ProcessFaultResponse;WebServiceRequestMgt.GetResponseContent(ResponseInStream);CheckIfErrorsOccurred(ResponseInStream,PostingExch);ReadContentFromResponse(PaymentFileTempBlob,ResponseInStream);END;PROCEDUREProcessFaultResponse@15();VARXMLDOMMgt@1006:Codeunit6224;DotNetExceptionHandler@1000:Codeunit1291;WebException@1005:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.WebException\";WebExceptionStatus@1004:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.WebExceptionStatus\";XmlDoc@1003:DotNet\"'System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument\";HttpWebResponseError@1007:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpWebResponse\";HttpStatusCode@1008:DotNet\"'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpStatusCode\";ResponseInputStream@1002:InStream;BEGINDotNetExceptionHandler.Collect;IFNOTDotNetExceptionHandler.CastToType(WebException,GETDOTNETTYPE(WebException)) THENDotNetExceptionHandler.Rethrow;IFNOTWebException.Status.Equals(WebExceptionStatus.ProtocolError) THENERROR(WebException.Message);ResponseInputStream:=WebException.Response.GetResponseStream;DebugLogStreamToTempFile(ResponseInputStream,'WebExceptionResponse',TempDebugLogTempBlob);HttpWebResponseError:=WebException.Response;IFNOT(HttpWebResponseError.StatusCode.Equals(HttpStatusCode.Found) ORHttpWebResponseError.StatusCode.Equals(HttpStatusCode.InternalServerError)) THENERROR(WebException.Message);XmlDoc:=XmlDoc.XmlDocument;XmlDoc.Load(ResponseInputStream);ERROR(XMLDOMMgt.FindNodeTextWithNamespace(XmlDoc.DocumentElement,FaultStringXmlPathTxt,'soap',SoapNamespaceTxt));END;OBJECTCodeunit1291DotNetExceptionHandler{OBJECT-PROPERTIES{Date=;Time=;VersionList=;}PROPERTIES{OnRun=BEGINEND;}CODE{VAROuterException@1000:DotNet\"'mscorlib'.System.Exception\";PROCEDURECatch@3(VARException@1002:DotNet\"'mscorlib'.System.FormatException\";Type@1007:DotNet\"'mscorlib'.System.Type\");BEGINCollect;IFNOTCastToType(Exception,Type) THENRethrow;END;PROCEDURECollect@1();BEGINOuterException:=GETLASTERROROBJECT;END;PROCEDURETryCastToType@5(Type@1000:DotNet\"'mscorlib'.System.Type\") :Boolean;VARException@1001:DotNet\"'mscorlib'.System.FormatException\";BEGINEXIT(CastToType(Exception,Type));END;PROCEDURECastToType@2(VARException@1002:DotNet\"'mscorlib'.System.FormatException\";Type@1007:DotNet\"'mscorlib'.System.Type\") :Boolean;BEGINException:=OuterException;REPEATIFType.Equals(Exception.GetType()) THENEXIT(TRUE);Exception:=Exception.InnerException;UNTILISNULL(Exception);EXIT(FALSE);END;PROCEDURERethrow@4();BEGINIFNOTISNULL(OuterException.InnerException) THENERROR(OuterException.InnerException.Message);ERROR(OuterException.Message);END;BEGINEND. }}NAV Usages The CO1291 DotNet Exception Handler codeunit has been used for the Web service integration required for:\n Payment Export from the Payment Journal for creating bank-specific payment files. Bank Statement Import on the Bank Acc. Reconciliation card for importing the content of bank-specific statements. Bank name lookup on the Bank Account card for dynamically identifying the format to use to generate a bank-specific payment file. ","categories":"","description":"","excerpt":"Originally by Mostafa Balat, Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/net-exception-handling-in-cal/tryfunction-net-exception-handling-in-cal/","tags":"","title":"TryFunction NET Exception Handling in CAL"},{"body":"Do not end a line with unary operator.\nBad code\n\"Quantity Handled (Base)\":=-\"Quantity Handled (Base)\");Good code\n\"Quantity Handled (Base)\":=-\"Quantity Handled (Base)\");","categories":"","description":"","excerpt":"Do not end a line with unary operator.\nBad code\n\"Quantity Handled …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unary-operator-line-end/","tags":"","title":"Unary Operator Line End"},{"body":"Use parenthesis only to enclose compound expressions inside compound expressions.\nBad code\nIF(\"Costing Method\"=\"Costing Method\"::Standard) THENGood code\nIF\"Costing Method\"=\"Costing Method\"::StandardTHENBad code\nProfitPct=-(Profit) /CostAmt*100;Good code\nProfitPct=-Profit/CostAmt*100;","categories":"","description":"","excerpt":"Use parenthesis only to enclose compound expressions inside compound …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unnecessary-compound-parenthesis/","tags":"","title":"Unnecessary Compound Parenthesis"},{"body":"ELSE should not be used when the last action in the THEN part is an EXIT, BREAK, SKIP, QUIT, ERROR.\nBad code\nIFIsAdjmtBinCodeChangedTHENERROR(AdjmtBinCodeChangeNotAllowedErr,...) ELSEERROR(BinCodeChangeNotAllowedErr,...);Good code\nIFIsAdjmtBinCodeChangedTHENERROR(AdjmtBinCodeChangeNotAllowedErr,...) ERROR(BinCodeChangeNotAllowedErr,...);","categories":"","description":"","excerpt":"ELSE should not be used when the last action in the THEN part is an …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unnecessary-else/","tags":"","title":"Unnecessary ELSE"},{"body":"Do not use parenthesis in a function call if the function does not have any parameters.\nBad code\nIFReservMgt.IsPositive() THENGood code\nIFReservMgt.IsPositiveTHENBad code\nIFChangeStatusForm.RUNMODAL() \u003c\u003eACTION::YesTHENGood code\nIFChangeStatusForm.RUNMODAL\u003c\u003eACTION::YesTHEN","categories":"","description":"","excerpt":"Do not use parenthesis in a function call if the function does not …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unnecessary-function-parenthesis/","tags":"","title":"Unnecessary Function Parenthesis"},{"body":"There should be no unnecessary separators.\nBad code\nIFCustomer.FINDFIRSTTHEN;;Good code\nIFCustomer.FINDFIRSTTHEN;","categories":"","description":"","excerpt":"There should be no unnecessary separators.\nBad code …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unnecessary-separators/","tags":"","title":"Unnecessary Separators"},{"body":"Do not use TRUE or FALSE keywords unnecessarily if the expression is already an logical expression.\nBad code\nIFIsPositive() =TRUETHENGood code\nIFIsPositiveTHENBad code\nIF Complete \u003c\u003e TRUE THEN Good code\nIFNOTCompleteTHEN","categories":"","description":"","excerpt":"Do not use TRUE or FALSE keywords unnecessarily if the expression is …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/unnecessary-truefalse/","tags":"","title":"Unnecessary TRUE/FALSE"},{"body":"Do not write code that will never be hit.\nIt affects code readability and can lead to wrong assumptions.\nBad code\nIF Type \u003c\u003e Type::FIELD THEN BEGIN ... ERROR(...); RecRef.CLOSE; END; Good code\nIF Type \u003c\u003e Type::FIELD THEN BEGIN ... RecRef.CLOSE; ERROR(...); END; ","categories":"","description":"","excerpt":"Do not write code that will never be hit.\nIt affects code readability …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/unreachable-code/","tags":"","title":"Unreachable Code"},{"body":"The value assigned to a variable must be used. Else the variable is not necessary.\nBad code\nPROCEDURE AddEntities@1(FilterStr@1000 : Text[250]); VAR Vendor@1001 : Record 23; Count@1002 : Integer; BEGIN Count := 0; Vendor.SETFILTER(\"No.\",FilterStr); IF Vendor.FINDSET THEN REPEAT \"User ID\" := USERID; \"Vendor No.\" := Vendor.\"No.\"; IF INSERT THEN Count += 1; UNTIL Vendor.NEXT = 0; END; Good code\nPROCEDURE AddEntities@1(FilterStr@1000 : Text[250]); VAR Vendor@1001 : Record 23; BEGIN Vendor.SETFILTER(\"No.\",FilterStr); IF Vendor.FINDSET THEN REPEAT \"User ID\" := USERID; \"Vendor No.\" := Vendor.\"No.\"; IF INSERT THEN; UNTIL Vendor.NEXT = 0; END; ","categories":"","description":"","excerpt":"The value assigned to a variable must be used. Else the variable is …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/unused-initialized-variables/","tags":"","title":"Unused Initialized Variables"},{"body":"Do not declare variables that are unused.\nUnused variables affect readability.\nBad code\nPROCEDURE CheckPostingDate@23(CaptionEntryNo@1005 : Text[50]); BEGIN IF GenJnlCheckLine.DateNotAllowed(PostingDate) THEN ERROR(DateNotAllowedErr,Caption,EntryNo) IF PostingDate \u003e MaxPostingDate THEN MaxPostingDate := PostingDate; END Good code\nPROCEDURE CheckPostingDate@23(); BEGIN IF GenJnlCheckLine.DateNotAllowed(PostingDate) THEN ERROR(DateNotAllowedErr,Caption,EntryNo); IF PostingDate \u003e MaxPostingDate THEN MaxPostingDate := PostingDate; END; Bad code\nPROCEDURE IsReturned@14(EntryNo@1002 : Integer) : Decimal; VAR ItemEntry@1000 : Record 32; Quantity@1003 : Integer; BEGIN EXIT(-OutboundApplied(EntryNo,TRUE) - InboundApplied(EntryNo,TRUE)); END; Good code\nPROCEDURE IsReturned@14(EntryNo@1002 : Integer) : Decimal; BEGIN EXIT(-OutboundApplied(EntryNo,TRUE) - InboundApplied(EntryNo,TRUE)); END; ","categories":"","description":"","excerpt":"Do not declare variables that are unused.\nUnused variables affect …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/unused-variables/","tags":"","title":"Unused Variables"},{"body":"Originally by Abshishek Ghosh and Bogdan Sturzoiu at Microsoft Development Center Copenhagen\nAbstract This pattern uses queries to create an efficient way to detect duplicate entries in a table. This is, for example, useful when trying to find out which customers or contacts have the same names, so we can merge them later.\nDescription Duplicate detection has several requirements in Microsoft Dynamics NAV. One method to eliminate duplication is by defining the relevant field as the primary key. However, this method is not always practical either due to the size of the field or due to business requirements that dictate how duplicates are detected but not necessarily how they are eliminated. An example of this method is to detect contacts with the same name and take action to merge them if they are.\nBefore Dynamics NAV 2013, the only possibility was to iterate through the table in a loop and then create a sub-loop where another instance of the same table is filtered to check for duplicates. For example, to check for duplicate names in the Customer table, the code would look like this:\nPROCEDUREHasDuplicateCustomers@26() :Boolean;VARCustomer@1000:Record18;Customer2@1001:Record18;BEGINIFCustomer.FINDSETTHENREPEATCustomer2.SETRANGE(Name,Customer.Name);IFCustomer2.COUNT\\\u003e1THENEXIT(TRUE);UNTILCustomer.NEXT=0;EXIT(FALSE);END;This code would involve setting filters on the Customer table as many times as there are records in the table. This is an expensive operation.\nStarting with Dynamics NAV 2013, we can use queries to create a more efficient implementation of the same logic.\nUsage The solution involves that you create a query to return duplicates, and then invoke it from a method that would test the value of the query to identify if duplicates were found.\nStep 1 Creating the Query\n The query must be created with the table we want to search in as the dataitem. The field we want to search for must be created as a grouped field. Create a totaling field on the count, and add a filter for Count \u003e 1. This ensures that only records with more than one instance of the field that we selected in the previous step are included in the query result. Continuing with our Customer Name example, here is how the query would look:\n\n ELEMENTS { { 1 ; ;DataItem; ; DataItemTable=Table18 } { 2 ;1 ;Column ; ; DataSource=Name } { 3 ;1 ;Column ; ; ColumnFilter=Count_=FILTER(\\\u003e1); MethodType=Totals; Method=Count } } Step 2 Invoking the Query to Check for Duplicates\nNow that the query is created, all we need to do is to invoke the query and check if any records are returned, which would mean that there are duplicates.\nHere is an alternate implementation of the HasDuplicateCustomers method using the query that we created:\nPROCEDUREHasDuplicateCustomersWithQuery@27() :Boolean;VARCustomerDuplicate@1000:Query70000;BEGINCustomerDuplicate.OPEN;EXIT(CustomerDuplicate.READ);END;Examples\n Acc. Sched. Chart Management codeunit (762),\nmethods CheckDuplicateAccScheduleLineDescription and CheckDuplicateColumnLayoutColumnHeader Analysis Report Chart Mgt. codeunit (770),\nmethods CheckDuplicateAnalysisLineDescription and CheckDuplicateAnalysisColumnHeader Consequences A new query object is needed for every type of duplicate check. This could easily explode and create a maintenance problem.\n","categories":"","description":"","excerpt":"Originally by Abshishek Ghosh and Bogdan Sturzoiu at Microsoft …","ref":"/docs/navpatterns/patterns/queries/use-queries-to-detect-duplicate-records/","tags":"","title":"Use Queries to Detect Duplicate Records"},{"body":"Originally by Bogdan Sturzoiu, Microsoft Development Center Copenhagen\nAbstract This pattern shows how the new query object type introduced in NAV 2013 allows you to replace costly loops when inspecting data from two or more tables.\nDescription One of the core operations in a relational database is joining two or more tables. For example, you might need to extract all sales lines in the database together with information regarding the related sales header. This requires joining the Sales Header and Sales Line tables using Sales Header No. as the connecting field.;\nThe join operation has traditionally been done in C/AL by record looping. When NAV 2013 introduced the query object, it allowed us to produce a data set that is the result of a join operation between two or more tables. This simplifies the problem of finding related records in two tables linked through a foreign key.\nPattern Elements Two or more tables that contain records linked through a foreign key: Table 1, Table 2, Table n. A query object Query X, that joins Table 1, Table 2, etc. based on the connecting key. A processing codeunit that loops through the query records (or any other code-bearing object). Pattern Steps Run the query on the connected tables. Loop through the records returned by the query. Process the records. \nFigure 1. The pattern elements\nUsage Sample Problem The Bank Acc. Reconciliation Line table (274) and the Bank Account Ledger Entry table (271) are connected through the Bank Account No. field. Identify the matching pairs of records based on having the same remaining amount and transaction date.\nSolution Using Nested Loops The classic C/AL approach is to:\n Set the necessary filters on the left table, i.e. table 274. Loop through the filtered records. For each record in the filter, find the related records in the right table (table 271) and set the required filters on it. For each pair of records from the left and right table, decide if they are a solution and if so, apply them to each other. PROCEDUREMatchSingle@5(BankAccReconciliation@1003:Record273);VARBankAccRecLine@1005:Record274;BankAccLedgerEntry@1006:Record271;BankAccEntrySetReconNo@1007:Codeunit375;BEGINBankAccRecLine.SETRANGE(\"Bank Account No.\",BankAccReconciliation.\"Bank Account No.\");BankAccRecLine.SETRANGE(\"Statement No.\",BankAccReconciliation.\"Statement No.\");BankAccRecLine.SETFILTER(Difference,'\u003c\u003e%1',0);BankAccRecLine.SETRANGE(Type,BankAccRecLine.Type::\"Bank Account Ledger Entry\");IFBankAccRecLine.FINDSETTHENREPEATBankAccLedgerEntry.SETRANGE(\"Bank Account No.\",BankAccRecLine.\"Bank Account No.\");BankAccLedgerEntry.SETRANGE(Open,TRUE);BankAccLedgerEntry.SETRANGE(\"Statement Status\",BankAccLedgerEntry.\"Statement Status\"::Open);BankAccLedgerEntry.SETFILTER(\"Remaining Amount\",'\u003c\u003e%1',0);IFBankAccLedgerEntry.FINDSETTHENREPEATIF(BankAccRecLine.Difference=BankAccLedgerEntry.\"Remaining Amount\") AND(BankAccRecLine.\"Transaction Date\"=BankAccLedgerEntry.\"Posting Date\") THENBankAccEntrySetReconNo.ApplyEntries( BankAccRecLine,BankAccLedgerEntry,Relation::\"One-to-One\");UNTILBankAccLedgerEntry.NEXT=0;UNTILBankAccRecLine.NEXT=0;END;Solution Using Query\nThe new query-based approach involves:\n Define a query that returns the full filtered join of tables 271 and 274. Loop through the records returned by the query. For each query record, decide if it represents a solution and then connect the two table records that formed it through an application. PROCEDUREMatchSingle@5(BankAccReconciliation@1003:Record273);VARBankRecMatchCandidates@1001:Query1252;BankAccEntrySetReconNo@1007:Codeunit375;BEGINBankRecMatchCandidates.SETRANGE(Rec_Line_Bank_Account_No,BankAccReconciliation.\"Bank Account No.\");BankRecMatchCandidates.SETRANGE(Rec_Line_Statement_No,BankAccReconciliation.\"Statement No.\");IFNOTBankRecMatchCandidates.OPENTHENEXIT;WHILEBankRecMatchCandidates.READDOBEGINBankAccLedgerEntry.GET(BankRecMatchCandidates.Entry_No);BankAccRecLine.GET(BankAccRecLine.\"Statement Type\"::\"Bank Reconciliation\",BankRecMatchCandidates.Rec_Line_Bank_Account_No,BankRecMatchCandidates.Rec_Line_Statement_No,BankRecMatchCandidates.Rec_Line_Statement_Line_No);BankAccEntrySetReconNo.ApplyEntries(BankAccRecLine,BankAccLedgerEntry,Relation::\"One-to-One\");END;END;where the query 1252 is defined as:\nOBJECTQuery1252BankRec. MatchCandidates{OBJECT-PROPERTIES{Date=;Time=;VersionList=;}PROPERTIES{}ELEMENTS{{1;;DataItem;;DataItemTable=Table274;DataItemTableFilter=Difference=FILTER(\u003c\u003e0),Type=FILTER(=BankAccountLedgerEntry) }{2;1;Column;Rec_Line_Bank_Account_No;DataSource=BankAccountNo. }{3;1;Column;Rec_Line_Statement_No;DataSource=StatementNo. }{4;1;Column;Rec_Line_Statement_Line_No;DataSource=StatementLineNo. }{5;1;Column;Rec_Line_Transaction_Date;DataSource=TransactionDate}{6;1;Column;Rec_Line_Difference;DataSource=Difference}{7;1;DataItem;;DataItemTable=Table271;DataItemTableFilter=RemainingAmount=FILTER(\u003c\u003e0),Open=CONST(Yes),StatementStatus=FILTER(Open);DataItemLink=BankAccountNo.=Bank_Acc_Reconciliation_Line.\"Bank Account o.\",RemainingAmount=Bank_Acc_Reconciliation_Line.Difference,PostingDate=Bank_Acc_Reconciliation_Line.\"Transaction Date\"}{8;2;Column;;DataSource=EntryNo. }{9;2;Column;Bank_Account_No;DataSource=BankAccountNo. }{10;2;Column;;DataSource=PostingDate}{11;2;Column;;DataSource=RemainingAmount}{12;2;Column;Bank_Ledger_Entry_Open;DataSource=Open}{13;2;Column;;DataSource=StatementStatus}}CODE{BEGINEND. }When comparing the two implementations, we notice the following advantages of using a query instead of two loops:Comparison\n A query produces the Cartesian product of tables 1 and 2 faster than by looping through both of them. The advantage grows as there are more tables linked. The query object leverages the power of SQL Server (as it basically executes a SQL query directly against the database server), and as such it only requires one trip to the database to fetch the data, instead of getting the related records on the right side of the join one by one.\n A query is scalable in the sense that it allows reusing its definition by applying filters when looping through its dataset. So a generic query can be reused for a variety of purposes just by adapting the filters to the programming need. Duplicating traditional record loops in different functions, on the other side, requires extensive code copy-pasting, which can introduce code defects. Using a query only requires one loop, whereas joining two or more tables requires multiple code loops that quickly become difficult to read and follow. Queries are easy to create and maintain and generally provide a cleaner design. NAV Specific Examples In Microsoft Dynamics NAV 2013 R2, we can see the query object used in the bank account reconciliation matching algorithm. The object is query Bank Rec. Match Candidates query (1252), and it is called by the matching engine in the Match Bank Rec. Lines codeunit (1252).\nIdeas for Improvement The query object type could be improved to allow the passing of parameters at runtime, or, in general, being built dynamically at runtime. This will remove the need for multiple static definitions of the same base query used in slightly different contexts.\n","categories":"","description":"","excerpt":"Originally by Bogdan Sturzoiu, Microsoft Development Center Copenhagen …","ref":"/docs/navpatterns/patterns/queries/use-queries-to-replace-nested-loops/","tags":"","title":"Use Queries to Replace Nested Loops"},{"body":"Pass user messages using Text Constants. It makes translation easy.\nBad code\nImportAttachmentQst@1021:TextConst'ENU=\"Import attachment \"';... IFCONFIRM(ImportAttachmentQst+Caption+'?',TRUE) THENBEGINGood code\nImportAttachmentQst@1021:TextConst'ENU=\"Import attachment %1?\"';... IFCONFIRM(STRSUBSTNO(ImportAttachmentQst,Caption),TRUE) THENBEGINBad code\n... IFNOTCONFIRM( STRSUBSTNO( 'Difference on Periodic entries: %1 on %2'+'Do you want to continue?',Balance,Date),TRUE) THENERROR('Program terminated by the user');Good code\nDiffOnPeriodEntiesQst@100:TextConst'ENU=\"Difference on Periodic entries: %1 on %2\\\\ Do you want to continue?\"';ProgramTerminatedErr@200:TextConst'ENU=\"Program terminated by the user\"';... IFNOTCONFIRM(STRSUBSTNO(DiffOnPeriodEntiesQst,Balance,Date),TRUE) THENERROR(ProgramTerminatedErr);","categories":"","description":"","excerpt":"Pass user messages using Text Constants. It makes translation easy. …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/use-text-constants/","tags":"","title":"Use Text Constants"},{"body":"CALCDATE should only be used with DateFormula variables. Alternatively the string should be enclosed using the \u003c\u003e symbols.\nBad code\nIF ReservEntry.\"Expected Receipt Date\" \u003e CALCDATE('-' + FORMAT(\"Dampener (Time)\") + FirstDate) THEN Good code\nIF ReservEntry.\"Expected Receipt Date\" \u003e CALCDATE('\u003c-' + FORMAT(\"Dampener (Time)\") + FirstDate + '\u003e') THEN ","categories":"","description":"","excerpt":"CALCDATE should only be used with DateFormula variables. Alternatively …","ref":"/docs/navpatterns/3-cal-coding-guidelines/internationalization/using-calcdate/","tags":"","title":"Using Calcdate"},{"body":"The OptionCaptionML should be filled in for sourceexpression using option data types.\nBad code\n{ 30 ;TextBox ;17850;0 ;150 ;423 ;Name=Selection; SourceExpr=Selection; DataSetFieldName=Selection } ... Selection@1008 : 'Open,Closed,Open and Closed'; ... Good code\n{ 30 ;TextBox ;17850;0 ;150 ;423 ;Name=Selection; OptionCaptionML=ENU=Open,Closed,Open and Closed; SourceExpr=Selection; DataSetFieldName=Selection } ... Selection@1008 : 'Open,Closed,Open and Closed'; ","categories":"","description":"","excerpt":"The OptionCaptionML should be filled in for sourceexpression using …","ref":"/docs/navpatterns/3-cal-coding-guidelines/localizability/using-optioncaptionml/","tags":"","title":"Using OptionCaptionML"},{"body":"C/AL Coding Guidelines User eXperience Find the C/AL guidelines by expanding the menu in the left.\n","categories":"","description":"","excerpt":"C/AL Coding Guidelines User eXperience Find the C/AL guidelines by …","ref":"/docs/navpatterns/3-cal-coding-guidelines/ux/","tags":"","title":"UX"},{"body":"Do not use scope .'' qualifier unnecessarily when a variable is already implicitly or explicitly scoped. It keeps the code simpler.\nBad code\nReturnRcptHeader.SETRANGE(ReturnRcptHeader.\"Return Order No.\",\"Document No.\");Good code\nReturnRcptHeader.SETRANGE(\"Return Order No.\",\"Document No.\");Bad code\nWITHChangeLogSetupTableDOBEGIN... IFChangeLogSetupTable.DELETETHEN... END;Good code\nWITHChangeLogSetupTableDOBEGIN... IFDELETETHEN... END;","categories":"","description":"","excerpt":"Do not use scope .'' qualifier unnecessarily when a variable is …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/variable-already-scoped/","tags":"","title":"Variable Already Scoped"},{"body":"Do not assign a value to a variable whose capacity is smaller.\nIt will throw an error at runtime.\nBad code\nFileName@1010 : Text[250]; ... UploadedFileName@1016 : Text[1024]; ... FileName := UploadedFileName; Good code\nFileName@1010 : Text[1024]; ... UploadedFileName@1016 : Text[1024]; ... FileName := UploadedFileName; Bad code\nFileName@1010 : Text[250]; ... UploadedFileName@1016 : Text[1024]; ... FileName := UploadedFileName; Good code\nFileName@1010 : Text[250]; ... UploadedFileName@1016 : Text[1024]; ... FileName := COPYSTR(UploadedFileName,1,250); // In case only the first 250 chars are needed. Similar for fields Bad code\nVAR ExceededNumberTxt@001 : 'ENU=Warning: Exceeded number of unsent documents/requests' Subject@1002 : Text[50]; ... BEGIN ... Subject := ExceededNumberTxt; Good code\nVAR ExceededNumberTxt@001 : 'ENU=Warning: Exceeded number of unsent documents/requests' Subject@1002 : Text[100]; ... BEGIN ... Subject := ExceededNumberTxt'; ","categories":"","description":"","excerpt":"Do not assign a value to a variable whose capacity is smaller.\nIt will …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/variable-capacity-mismatch/","tags":"","title":"Variable Capacity Mismatch"},{"body":"Variables that refer to a C/AL object must contain the objects name, abbreviated where necessary.\nA variable must begin with a capital letter.\nBlanks, periods, and other characters (such as parentheses) that would make quotation marks around a variable necessary must be omitted.\nIf a variable is a compound of two or more words or abbreviations, each word or abbreviation should begin with a capital letter.\nBad code\n... WIPBuffer@1002:Record1018... OBJECTTableJobWIPBufferGood code\n... JobWIPBuffer@1002:Record1018... OBJECTTableJobWIPBufferBad code\n... Postline@1004:Codeunit12;... OBJECTCodeunitGen. Jnl.-PostLineGood code\n... GenJnlPostLine@1004:Codeunit12;... OBJECTCodeunitGen. Jnl.-PostLineBad code\nLOCALPROCEDUREHandleCustDebitCredit@17(...;\"Amount (LCY)\"@1001:Decimal;...);BEGINIF((... (\"Amount (LCY)\"\\\u003e0)) ...) OR((... (\"Amount (LCY)\"\u003c0)) ...) THENBEGIN... Good code\nLOCALPROCEDUREHandleCustDebitCredit@17(...;AmountLCY@1001:Decimal;...);BEGINIF((... (AmountLCY\\\u003e0)) ...) OR((... (AmountLCY\u003c0)) ...) THENBEGIN... ","categories":"","description":"","excerpt":"Variables that refer to a C/AL object must contain the objects name, …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/variable-naming/","tags":"","title":"Variable Naming"},{"body":"Variables declarations should be ordered by type. In general, object and complex variable types are listed first followed by simple variables. The order should be the same as the object list in the object designer for C/AL objects. Afterwards come the complex variables like RecordRef, .NET, FieldRef etc. At the end come all the simple data types in no particular order.\nBad code\nStartingDateFilter@1002:Text[30];Vend@1003:Record23;Good code\nVend@1003:Record23;StartingDateFilter@1002:Text[30];","categories":"","description":"","excerpt":"Variables declarations should be ordered by type. In general, object …","ref":"/docs/navpatterns/3-cal-coding-guidelines/readability/variables-declarations-order/","tags":"","title":"Variables Declarations Order"},{"body":"By Nikola Kukrika, waldo and Gary Winter\nAbstract The Variant façade provides a single interface that can take any Record, RecordRef or RecordID as an argument. With this pattern the code is encapsulated within the single object, with clear separation between common and table specific code.\n\nProblem Since NAV is strongly typed, developers often need to duplicate functionality in order to add support for a new table. The developer would typically start by duplicating the function, changing the record type and implement slight modifications to the code if needed.\nThe problem with this approach is that code duplication is one of the worst things in software development it makes code harder to understand, maintain, extend and test.\nOne of the good examples of this approach and the resulting duplication is codeunit 229, Document-Print:\n\n\nAfter reading the code from the two code snippets above, it is very hard to see the differences. The most of the code is duplicated (more than 95%). To make the matters worse the codeunit itself has 10 additional methods that are used to print different records, some are similar to the ones above while others are completely different.\n\n\nFigure: the entire code of the codeunit 229, Document Print, 12 methods\n\nFigure: Visualization how it would look like with 20 methods\nProblems arising from this way of implementing code are:\nUnderstanding of the code is very hard, since the developer needs to read blocks of code that look similar and try to understand what exactly the differences are.\nMaintaining and Extending the code is hard, since every fix or a new behavior that needs to be implemented multiple times (in this case probably 12 times).\nUpgradability is low each conflict needs to be resolved many times. The hook pattern is hard to implement since it needs to be implemented for every function. Evening suffers the same problem - cannot use the evening easily since it needs to be raised from multiple places in the code.\nTesting the code is hard since the tests need to be replicated.\nConstant cost of adding support for new tables when the new record type needs to be supported, it has a constant cost. Adding a support for a new record will increase the Maintenance tax and it will make the code harder to understand and extend.\nConclusion - If the functionality needs to be used for many records the approach of duplicating the functions should be avoided.\nSolution The Variant façade pattern provides a single interface that would not need to be changed in the future. It will be able to take any record as a parameter. Common code should be kept separately from record specific code and both must be very visible so the developers can easily see what the differences are.\nThe Key components of the pattern are:\nSignature Instead of hardcoding a record type a variant is used as an argument. A Variant Façade function can receive three types of data: Record, RecordID, or RecordRef. This way, it can be reused anywhere in the product and the code will still work.\nA good practice is to combine this pattern with the Argument Table pattern to make sure that the signature does not change (Additional parameters can be added to the argument table without impacting existing code.). If the Argument Table is not needed, it should not be placed in the signature - it is always possible to add it at a latter point and have two public functions (one with and one without arguments).\nExample - For codeunit 229, Document-Print all of the public methods can be simply replaced with a single public method like this:\nWith this approach the façade function can serve all of the record types and will not need to change in the future.\nCasting to a record ref After the signature it is necessary to decide if the function will support passing of the Record ID and the RecordRef. Code tends to be easier to understand and maintain if only the records are passed as the arguments, however in some cases it is needed to support the other two types.\n Support for Record, Record ID and RecordRef: After the signature if the function supports passing of the RecordID or RecordRef as a parameter it is a good practice to cast them to a RecordRef. Codeunit Data Type Management is used to do this:\nDataTypeManagement.GetRecordRef(RecRelatedVariant,RecordRef)\n Support Records only - If the function supports only passing in the record, it is a good practice to check if the variant is a record: IFNOTRecordVariant.ISRECORDTHENERROR(NotARecordErr);Using the variant The variant can be passed instead of record when calling the Page.RUN, Codeunit.RUN or Report.RUN statically:\nFor example:\nPage.RUN(PageID,Variant);Codeunit.RUN(CodeunitID,Variant);Report.RUN(ReportID,Variant);These calls are identical to using an actual instance of the record, since the variant will be casted to the record automatically, with all filters, markings and values preserved.\nIn case the variant was casted to the RecordRef (by using DataTypeManagement.GetRecordRef(RecRelatedVariant,RecordRef)), it is still possible to invoke the functions statically.\nThe RecordRef simply needs to be casted into a variant and passed as a parameter, for example:\nVariantArgument:=RecordRef;Page.RUN(PageID,VariantArgument);Variant can always casted back to the original record in the table specific code, exact process is described below.\nTable specific code To do table-specific processing, it is necessary to get the RecordRef first, since NUMBER parameter will tell us which table it is. In the table-specific code, it is possible to cast the variant back to the original record type, so data is accessible and it is possible to invoke functions.\nTo do this, the best practice is to use the COPY function to preserve filters:\nSalesHeader.COPY(RecordVariant);Assigning directly such as SalesHeader := RecordVariant, is possible, however all filters will be lost.\nExample of table specific code:\nCASERecordRef.NUMBEROFDATABASE::\"Sales Header\":BEGINSalesHeader.COPY(RecordVariant);SalesHeader.PrintDocument;END;DATABASE::\"Purchase Header\":BEGINPurchaseHeader.COPY(RecordVariant) ... END;.... It is a good practice to try to avoid the table specific code if possible.\nOne of the issues with table specific code is that the CASE statement can easily explode when large number of records are supported.\nThere are two possible solutions:\n Move the calculations outside of the façade code unit and pass it in as part of the argument table. For example, instead of having a case like this within DocumentPrint codeunit:\nCASERecordRef.NUMBEROFDATABASE::\"Sales Header\":BEGINSalesHeader.COPY(RecordVariant);CASESalesHeader.\"Document Type\"OFSalesHeader.\"Document Type\"::Quote:ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Quote\");SalesHeader.\"Document Type\"::\"Blanket Order\":ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Blanket\");SalesHeader.\"Document Type\"::Order:ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Order\");SalesHeader.\"Document Type\"::\"Return Order\":ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Return\");SalesHeader.\"Document Type\"::Invoice:ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Invoice\");SalesHeader.\"Document Type\"::\"Credit Memo\":ReportSelections.SETRANGE(Usage,ReportSelections.Usage::\"S.Cr.Memo\");END;If the ReportSelections.Usage is simply passed into the function from outside, then the case statement is not needed at all. For example:\nPrintDocumentArguments.\"Report Selection Usage\":=SalesHeader.GetReportSelectionUsage;DocumentPrint.PrintDocument(SalesHeader,PrintDocumentArguments);Where GetReportSelection usage is coded like this:\nCASESalesHeader.\"Document Type\"OFSalesHeader.\"Document Type\"::Quote:EXIT(ReportSelections.Usage::\"S.Quote\");SalesHeader.\"Document Type\"::\"Blanket Order\":EXIT(ReportSelections.Usage::\"S.Blanket\");SalesHeader.\"Document Type\"::Order:EXIT(ReportSelections.Usage::\"S.Order\");SalesHeader.\"Document Type\"::\"Return Order\":EXIT(ReportSelections.Usage::\"S.Return\");SalesHeader.\"Document Type\"::Invoice:EXIT(ReportSelections.Usage::\"S.Invoice\");SalesHeader.\"Document Type\"::\"Credit Memo\":EXIT(ReportSelections.Usage::\"S.Cr.Memo\");This way the code is much more reusable and simpler to read.\n Use Rules Table to replace the code with data-driven approach. Setup table would contain the list of the reports and their usages. Based on Table ID and usage it is possible to set filters on the setup table and run the object ID from the result.\nFor example:\nReportSelectionSetup.SETRANGE(\"Table ID\",RecordRef.NUMBER);ReportSelectionSetup.SETRANGE(\"Usage Type\",RecordRef.FieldValue(ArgumentTable.\"Usage Type\");ReportSelectionSetup.FINDFIRST;REPORT.RUN(ReportSelectionSetup.\"Report ID\",VariantRecord);Example The following code illustrates how the Variant Façade pattern can be used to implement the Document-Print Codeunit.\n\n\nFrom the PrintDocument signature it is clear that it will not need to be changed in the future.\nCode duplication is avoided, specific code is isolated in the PrepareRecord function, there is clear extension point to add support for new records in the future. Since code is not duplicated and there is a single flow through the method, inserting hooks and events in the future will be straightforward.\nWhen adding the support for new records in most cases it is not need to change any code within the method, thus the cost of extending the usage is minimal.\nNote - PrepareRecord function is placed for the illustrational purposes. An improvement would be to move all of the code from the PrepareRecord function before calling the function. So for the SalesHeader and PurchaseHeaders discounts should be calculated before invoking the function. For passing of the argument it should be one of the fields in the Argument Table, thus the entire specific code would be eliminated.\nConsequences Not needed if the functionality needs to support few tables. Dont use it as a hammer Strongly typing the records has it benefits since it is easier to find usages, errors will be visible at the compilation time. Code becomes harder to debug within the variant façade Be careful with filters and marks, if the function needs to support multiple records. Test these cases thoughtfully because with bad placement of code the filters can easily be lost. Case statements can explode if there are too many tables that require specific processing. Then it is a must to find a way to keep the number of options in the CASE statement low. The Rules Table pattern and adding specifics to the Argument Table before invoking the code could help with keep the list shorter. NAV usages Codeunit 452 - Report Distribution Management Codeunit 700 - Page Management Codeunit 701 - Data Type Management Codeunit 1268 - Export Launcher Codeunit 1410 - Doc. Exch. Service Mgt. Codeunit 1501 - Workflow Management Codeunit 1521 - Workflow Response Handling Codeunit 1531 - Workflow Change Rec Mgt. Codeunit 1535 - Approvals Mgmt. Related Topics OO Facade https://en.wikipedia.org/wiki/Facade_pattern\nArgument Table pattern - https://community.dynamics.com/nav/w/designpatterns/245.argument-table-pattern\nRules Table pattern\n","categories":"","description":"","excerpt":"By Nikola Kukrika, waldo and Gary Winter\nAbstract The Variant façade …","ref":"/docs/navpatterns/patterns/variant-facade/","tags":"","title":"Variant Facade"},{"body":"Do not use the WITH scope when it has a variable whose name is the same as a local variable. This can lead to wrong code assumptions.\nGiven that “Contract Type” is a field on table ServiceContractHeader, then in the following example there is a parameter name clash with the field name. Which one will be used?\nBad code\nPROCEDURE InsertData@1(\"Contract Type\"@1000 : Option...); ... BEGIN ... WITH ServiceContractHeader DO BEGIN ... DimMgt.InsertServContractDim(...,\"Contract Type\",\"Contract No.\",0,...); END; Good code\nPROCEDURE InsertData@1(ContractType@1000 : Option...); ... BEGIN ... WITH ServiceContractHeader DO BEGIN ... DimMgt.InsertServContractDim(...,ContractType,\"Contract No.\",0,...); END; ","categories":"","description":"","excerpt":"Do not use the WITH scope when it has a variable whose name is the …","ref":"/docs/navpatterns/3-cal-coding-guidelines/design/with-scope-name-collision/","tags":"","title":"WITH Scope Name Collision"},{"body":"Guidelines and Patterns\nfor Development for\nMicrosoft Dynamics 365 Business Central    Watch the Launch Design Patterns? A \"Design Pattern\" is a software design template to solve common development needs. This site is community run and Microsoft endorsed. Learn More Benefits Repeatability By using consistent patterns and best practices, code is far more reusable across diverse projects. Teamwork If all code uses design patterns and best practices, it's simpler for new team members to ensure that code is correct, as well as making it easier to jump into a project. Performance Many design patterns and best practices are also heavily focused on ensuring compliance with the latest performance recommendations to get the most out of every system. What's New PATTERN Event Bridge In the world of interfaces, it is important to preserve (certain) events over multiple implementation of the interface. Read Now BEST PRACTICE CASE Action on next line A CASE action should start on a line after the possibility. Read Now PATTERN Façade The intent of this pattern is to provide a unified API to a single or a collection of potentially complex subsystems. Read Now Join the Community Discord Join the BC Community to engage with other BC Professionals. GitHub Dive into the code. Submit PRs and collaborate with other like-minded contributors. Twitter Chat about this with the #bcalhelp hashtag. Discord Join the BC Community to engage with other BC Professionals. GitHub Dive into the code. Submit PRs and collaborate with other like-minded contributors. Twitter Chat about this with the #bcalhelp hashtag. ","categories":"","description":"Design Patterns and Guidelines for AL development for Microsoft Dynamics 365 Business Central","excerpt":"Design Patterns and Guidelines for AL development for Microsoft …","ref":"/","tags":"","title":"ALGuidelines.dev"},{"body":"","categories":"","description":"","excerpt":"","ref":"/categories/archived-pattern/","tags":"","title":"Archived Pattern"},{"body":"","categories":"","description":"","excerpt":"","ref":"/author/","tags":"","title":"Author"},{"body":"Created by Microsoft, Described by waldo\nDescription When begin follows then, else, do, it should be on the same line, preceded by one space character.\nBad code ifICPartnerRefType=ICPartnerRefType::\"Common Item No.\"thenbegin... end;Good code ifICPartnerRefType=ICPartnerRefType::\"Common Item No.\"thenbegin... end;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription When begin …","ref":"/docs/bestpractices/begin-as-an-afterword/","tags":["Readability"],"title":"begin as an afterword"},{"body":"Created by Microsoft, Described by waldo\nOnly use begin..end to enclose compound statements.\nBad code ifFindSet() thenbeginrepeat... untilnext() =0;end;Good code ifFindSet() thenrepeat... untilnext() =0;Bad code ifIsAssemblyOutputLinethenbeginTestField(\"Order Line No.\",0);end;Good code ifIsAssemblyOutputLinethenTestField(\"Order Line No.\",0);Exception // Except for this case ifXthenbeginifYthen//DO SOMETHING; endelse(notX) Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nOnly use begin..end to …","ref":"/docs/bestpractices/begin-end/","tags":["Readability"],"title":"Begin-End - Compound Only"},{"body":"","categories":"","description":"","excerpt":"","ref":"/categories/best-practice/","tags":"","title":"Best Practice"},{"body":"Created by Microsoft, Described by waldo\nDescription Do not start a line with a binary operator.\nBad code \"Quantity to Ship\":=Quantity-\"Quantity Shipped\"Good code \"Quantity to Ship\":=Quantity-\"Quantity Shipped\"Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Do not start a …","ref":"/docs/bestpractices/binary-operator-line-start/","tags":["Readability"],"title":"Binary Operator to Start Line"},{"body":"","categories":"","description":"","excerpt":"","ref":"/blog/","tags":"","title":"AL Guidelines Blog"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/c/al/","tags":"","title":"C/AL"},{"body":"Created by Microsoft, Described by waldo\nDescription A CASE action should start on a line after the possibility.\nBad code caseLetterof'A':Letter2:='10';'B':Letter2:='11';end;Good code caseLetterof'A':Letter2:='10';'B':Letter2:='11';end;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription A CASE action …","ref":"/docs/bestpractices/case-actions/","tags":["Readability"],"title":"CASE Action on next line"},{"body":"","categories":"","description":"","excerpt":"","ref":"/categories/","tags":"","title":"Categories"},{"body":"Created by Microsoft, Described by waldo\nDescription Always start comments with // followed by one space character.\nBad code RowNo+=1000;//Move way below the budget Good code RowNo+=1000;// Move way below the budget Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Always start …","ref":"/docs/bestpractices/comments-spacing/","tags":["Readability"],"title":"Comment Spacing"},{"body":"\u003cCreated by waldo, Described by waldo\u003e\nDescription When you perform a “DeleteAll” when there is nothing to delete, it will still perform a lock. When you for example perform a DeleteAll on an empty table, it will result in a table lock. Therefore its good practice to always check if the table is empty when performing a DeleteAll.\nBad code EmptyTableWLD.SetRange(Code,'AJ');EmptyTableWLD.DeleteAll(true);Good code EmptyTableWLD.SetRange(Code,'AJ');ifnotEmptyTableWLD.IsEmpty() thenEmptyTableWLD.DeleteAll(true);Discussions You can discuss the guideline here\nYou can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"\u003cCreated by waldo, Described by waldo\u003e\nDescription When you perform a …","ref":"/docs/bestpractices/deleteall/","tags":["Performance"],"title":"DeleteAll"},{"body":"Created by Microsoft, Described by waldo\nDescription The end else pair should always appear on the same line.\nBad code ifOppEntry.Find('-') thenifSalesCycleStage.Find('-') thenbegin... endelsebegin... end;Good code ifOppEntry.Find('-') thenifSalesCycleStage.Find('-') thenbegin... endelsebegin... end;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription The end else pair …","ref":"/docs/bestpractices/end-else-pair/","tags":["Readability"],"title":"end else pair"},{"body":"Created by waldo \u0026 Arend-Jan Kauffmann, Described by waldo\nAbstract In the world of interfaces, it is important to preserve (certain) events over multiple implementation of the interface.\nContext An app can have interfaces. It makes it possible for other apps to extend/change the implementations of a certain part of the business logic.\nLike in this example, we have an interface, to implement different ways for getting weights from scales:\ninterface\"IScale\"{procedureGetWeight():Decimal;procedureTare();}Problem Multiple apps can subscribe to certain events of the app. When a new implementation is created, we need to make sure that these events are raised at the right times. If those events were published on the implementation codeunit, it might very well be that those events will not be raised, hard to find, or whatever.\nSo, if we would implement it like this, it isnt really extensible, as a different implemention would implement different events .. and its not possible to subscribe to all of them (including future implementations)\ncodeunit50407\"Scale Wrong\"implementsIScale{procedureGetWeight() Result:Decimal;begin//TODO: Implement Bar GetWeight OnAfterGetWeight(Result);end;procedureTare();begin//TODO: Implement Bar Tare OnAfterTare();end;[IntegrationEvent(false,false)]procedureOnAfterGetWeight(varResult:Decimal) beginend;[IntegrationEvent(false,false)]procedureOnAfterTare() beginend;}Description To mitigate this problem, we can work with a new, dedicated and isolated codeunit, with publisher events to be able to raise them from different places.\ncodeunit50406\"IScale Triggers\"{[IntegrationEvent(false,false)]procedureOnAfterGetWeight(varResult:Decimal) beginend;[IntegrationEvent(false,false)]procedureOnAfterTare() beginend;}This way, its possible to raise the events in all the implementations:\ncodeunit50405\"Scale Bar\"implementsIScale{varIScaleTriggers:Codeunit\"IScale Triggers\";procedureGetWeight() Result:Decimal;begin//TODO: Implement Bar GetWeight IScaleTriggers.OnAfterGetWeight(Result);end;procedureTare();begin//TODO: Implement Bar Tare IScaleTriggers.OnAfterTare();end;}Benefits This new codeunit, with public events, makes the events accessible from all places, including new apps that are dependent from this app, and wants to extend the\nThe naming convention (both starting with “IScale”) also makes it very easy to find that corresponding events for the interface.\nWhen not to use Obviously, the events should be carefully considered: only the events that make sense to “share” over all implementations, need this approach.\nDiscussions You can discuss this pattern here\n","categories":["Pattern"],"description":"","excerpt":"Created by waldo \u0026 Arend-Jan Kauffmann, Described by waldo\nAbstract In …","ref":"/docs/patterns/event-bridge-pattern/","tags":["Interface"],"title":"Event Bridge"},{"body":"Created by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Gang of Four), Described by Jesper Schulz-Wedde (Microsoft)\nAbstract The intent of this pattern is to provide a unified API to a single or a collection of potentially complex subsystems. If you apply this pattern as a general pattern, you will ensure improved:\n Decoupling Encapsulation Readability Testability Maintainability Context Whenever you want to write an isolated piece of business logic, from now on referred to as subsystem, this pattern should be applicable.\nProblem The facade pattern addresses two main problems:\n Over time as systems grow, they tend to become complex and harder to comprehend. By adding a facade on top of the subsystem, that complexity is hidden, and a clear API is defined. Any object or method which is publicly accessible, may not receive breaking changes in future releases without announced deprecation. This complicates maintainability of the system. By adding a facade, you ensure that the subsystem is inaccessible to the outside systems, enabling you to change the implementation details of the subsystem at will. Description The facade pattern is one of the most commonly used and known patterns, first described the book Design Patterns: Elements of Reusable Object-Oriented Software. It is classified as a structural pattern. While it originates from the object-oriented world, it for sure also applies to AL. The power of a facade is that it:\n Improves the readability of your subsystems API, as it acts as an entry point to your subsystem. This also allows for easier documentation of your API, as you can focus it to a few public objects. Improves the maintainability of your subsystem, as the internal subsystem can be modified or even completely replaced freely, without risking to break the public API - as long as the facade remains intact. Ensures that your code remains loosely coupled and encapsulated, as no other subsystem can take dependencies on your internal implementation details. This also fosters the reusability of your code. Suggests what needs most attention in your tests, as you would want to make sure that your subsystems public API behaves as designed. Whenever you develop a functional group or an independent system, which has a clear API, you should add a facade to achieve the above-mentioned benefits.\nWhat is a subsystem? A subsystem is a group of objects, which together provide a set of capabilities. Libraries are excellent examples of such subsystems. In Business Central, all modules in the System Application are subsystems. Examples are hence every module you will find in the system application, such as:\n Azure Blob Services API Barcode Cryptography Management Encoding Image RegEx … If you can describe a set of capabilities out of context of the rest of the system, chances are you are looking at a subsystem.\nThe Pattern This is arguably one of easiest patterns to understand and implement. Loosely speaking, you simply need to smack a wrapper on top of your implementation and hide away your implementation details from the outside world.\nTo achieve this, we are using access modifiers. Lets try to take a look at an example, taken from the system application: the Image module. Im using this very simplified example for illustration purposes. Notice, that even the full subsystem at time of writing isnt complex - it merely has a single codeunit containing the implementation details. However, as it is expected that the complexity will increase over time or that the implementation details can change, the subsystem is already equipped with a facade from the beginning.\nThe Facade\ncodeunit3971Image{Access=Public;varImageImpl:Codeunit\"Image Impl.\";/// \u003csummary\u003e /// Creates an image from the specified data stream. /// \u003c/summary\u003e /// \u003cparam name=\"InStream\"\u003eA Stream that contains the image data.\u003c/param\u003e procedureFromStream(InStream:InStream) beginImageImpl.FromStream(InStream);end;/// \u003csummary\u003e /// Gets the width in pixels. /// \u003c/summary\u003e /// \u003creturns\u003eThe width in pixels.\u003c/returns\u003e procedureGetWidth():Integerbeginexit(ImageImpl.GetWidth());end;}The facade codeunit above has some characteristics:\n Access is explicitly set to Public, to underline that this is a facade. All methods are public. All methods are documented. No methods contain any logic. They merely point to implementation details. The object naming suggests that it will get referenced from the outside. Anyone who wants to access the subsystem, will only have to take a dependency on the facade; the implementation details are not needed nor accessible.\nAnyone who wants to access the subsystem, will only have to relate to this one public facade; the documentation makes it easy-to-understand the subsystems capabilities.\nTest of the subsystem can be limited to testing the facade - it is strictly speaking the only thing that needs verification, that it functions as designed. It is the contract of the subsystem.\nThe Subsystem\ncodeunit3970\"Image Impl.\"{Access=Internal;varTempBlob:Codeunit\"Temp Blob\";procedureFromStream(InStream:InStream) varOutStream:OutStream;beginTempBlob.CreateOutStream(OutStream);CopyStream(OutStream,InStream);end;procedureGetWidth():IntegervarImage:DotNetImage;InStream:InStream;beginTempBlob.CreateInStream(InStream);Image:=Image.FromStream(InStream);exit(Image.Width());end;}There are no rules for the subsystem, except that access needs to be internal. How you implement, how much you document, how you test, is entirely up to you and not the business of the outside caller. Of course, you should apply all of the best practices and patterns anyway, as you and possibly other developers will have to understand, extend and maintain the subsystem too. But from the view of this pattern, the complexity of the subsystem is irrelevant - just as long as its not accessible.\nUsage The facade pattern is one of the most prominent patterns in the system application. You will find plenty of examples here.\nBenefits The benefits of this rather simple pattern should be abundantly clear by now. But lets go over them once more, structured by the advantages this patterns brings:\nDecoupling As the entire subsystem is inaccessible to outside systems, no dependencies can be taken. Hence this patterns strongly promotes the decoupling of objects.\nEncapsulation The entire purpose of this very pattern is to encapsulate complexity; you hide away the implementation details behind an easy to understand facade.\nReadability If done right, the developer doesnt need to be able to understand the details of the subsystem. Everything relevant to using the subsystem is described in the facade.\nTestability Ensuring the correct behaviour of the subsystem can be done by testing the facade. The facade defines the contract of your subsystem - what does it expose and how should it behave. That contract should be covered with adequate tests, which will ensure that it is upheld, even if you decide to change the implementation of the subsystem.\nMaintainability The one thing you may not change freely, is the facade and the test of the facade. It can be extended, but you should not break any existing APIs. But that leaves the entire subsystem to be completely rewritten, if you desire to do so. As no external dependencies can exist, there is no risk of introducing any syntactical breaking changes to the outside world. And as the tests of the public facade remain, there is no risk of introducing semantical breaking changes either - the contract is upheld, as long as your tests pass.\nWhen not to use This is a very applicable pattern, which can be used in most cases. While it may appear to be overkill at the beginning of the design of your subsystem, chances are your subsystem will evolve in complexity over time. The pattern may complicate implementation of extensibility, as you hide away all implementation details and hence also take away the opportunity to extend those, but that does not mean that extensibility cannot be achieved - but it requires more careful designing for extensibility. Extensibility with facades could be a topic of its own, which for now isnt covered by this pattern description. As always, use your common sense when to use and when not to use this pattern.\nSnippets Given the simplicity of this pattern, there are no snippets available at the moment.\nList of references This is one of the most commonly used and discussed, initially described here:\nDesign Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 185ff. ISBN 0-201-63361-2.\nIt is also a key pattern in the design of our system application modules, which is described here:\nModule Architecture\nDiscussions You can discuss this pattern here\n","categories":["Pattern"],"description":"","excerpt":"Created by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides …","ref":"/docs/patterns/facade-pattern/","tags":[""],"title":"Façade"},{"body":"Created by Gary Winter (Cloud Ready Software), Described by waldo (iFacto Business Solutions | Dynex)\nAbstract The goal of this pattern is to facilitate a lot of things in one single awesome way of writing code. If you apply this pattern as a general pattern, youll implement:\n Extensibility Decoupling Readability Testability Encapsulation Context Whenever you have to write an isolated piece of business logic, this pattern should be applicable.\nProblem Usually, when you ask people where to place code, they all have their own opinion: on a table or page, or in some kind of codeunit library where lots of functions will be placed, or .. . In fact, does it matter? It sure does, because in many cases, the code simply isnt maintainable, let alone extendable or testable.\nDescription What if we have some kind of “standard way” to always write our code. The Generic Method Pattern is kind of like what it says: a generic way to implement a method.\nWhat is a method? Well, a method is a significant piece of business logic - maybe best explained by some examples:\n Posting a document Any button on a page that executes business logic a batch run to send emails … In a way, except “data validation”, most of the things we write in our daily life, are methods.\nThe Pattern One method, one codeunit The idea is to put the code in one encapsulated codeunit with the purpose to have all the code in that one codeunit function for that one method. This way, the codeunit will stay relatively small and readable.\nLet me start by showing an example, so you can refer to this complete example during the rest of the article:\ncodeunit53100\"WLD BlockCustomer Meth\"{internalprocedureBlockCustomer(varCust:RecordCustomer;HideDialog:Boolean) varIsHandled:Boolean;beginifnotConfirmBlockCustomer(HideDialog) thenexit;OnBeforeBlockCustomer(Cust,IsHandled);DoBlockCustomer(Cust,IsHandled);OnAfterBlockCustomer(Cust);AcknowledgeBlockCustomer(HideDialog) end;localprocedureDoBlockCustomer(varCust:RecordCustomer;IsHandled:Boolean);beginifIsHandledthenexit;Cust.Blocked:=Cust.Blocked::All;Cust.Modify(true);end;localprocedureConfirmBlockCustomer(HideDialog:Boolean):BooleanvarConfirmManagement:Codeunit\"Confirm Management\";ConfirmQst:Label'Are you sure?';DefaultAnswer:Boolean;beginDefaultAnswer:=true;ifHideDialogthenexit(DefaultAnswer);exit(ConfirmManagement.GetResponseOrDefault(ConfirmQst,DefaultAnswer));end;localprocedureAcknowledgeBlockCustomer(HideDialog:Boolean) varAcknowledgeMsg:Label'You successfully executed \"BlockCustomer\"';beginifnotGuiAllowedorHideDialogthenexit;Message(AcknowledgeMsg);end;[IntegrationEvent(false,false)]localprocedureOnBeforeBlockCustomer(varCust:RecordCustomer;varIsHandled:Boolean);beginend;[IntegrationEvent(false,false)]localprocedureOnAfterBlockCustomer(varCust:RecordCustomer);beginend;}Within that codeunit, the pattern is always the same:\n One public (internal) procedure The rest is always local So, from outside the codeunit, there is only one clear entrypoint: that one (public) internal function with its parameters.\nThe pattern within the codeunit exists of a few layers:\n The UI layer The Event layer The method layer The UI layer The UI layer takes care of the UI, obviously. What is important in this case, is that you always make sure that there is a “HideDialog” parameter that the business logic can use to still decide whether to use the dialog or not.\nThese are the UI Layer parts, where you see the public function gets the HideDialog, and passes it to the UI-related procedures, where the business logic for showing the UI takes place. Also, the default answer of the confirmation is handled there as well (what if the business logic calls this method with HideDialog to “true”).\ncodeunit53100\"WLD BlockCustomer Meth\"{internalprocedureBlockCustomer(varCust:RecordCustomer;HideDialog:Boolean) varIsHandled:Boolean;beginifnotConfirmBlockCustomer(HideDialog) thenexit;... AcknowledgeBlockCustomer(HideDialog) end;... localprocedureConfirmBlockCustomer(HideDialog:Boolean):BooleanvarConfirmManagement:Codeunit\"Confirm Management\";ConfirmQst:Label'Are you sure?';DefaultAnswer:Boolean;beginDefaultAnswer:=true;ifHideDialogthenexit(DefaultAnswer);exit(ConfirmManagement.GetResponseOrDefault(ConfirmQst,DefaultAnswer));end;localprocedureAcknowledgeBlockCustomer(HideDialog:Boolean) varAcknowledgeMsg:Label'You successfully executed \"BlockCustomer\"';beginifnotGuiAllowedorHideDialogthenexit;Message(AcknowledgeMsg);end;... }The Event layer This layer is going to add flexibility to any app that has a dependency on this app. By default, the pattern always foresees an OnBefore and an OnAfter event.\nThis is the relevant code for the event layer:\ncodeunit53100\"WLD BlockCustomer Meth\"{internalprocedureBlockCustomer(varCust:RecordCustomer;HideDialog:Boolean) varIsHandled:Boolean;begin... OnBeforeBlockCustomer(Cust,IsHandled);... OnAfterBlockCustomer(Cust);... end;... [IntegrationEvent(false,false)]localprocedureOnBeforeBlockCustomer(varCust:RecordCustomer;varIsHandled:Boolean);beginend;[IntegrationEvent(false,false)]localprocedureOnAfterBlockCustomer(varCust:RecordCustomer);beginend;}The method layer The last layer is obviously where the business logic will be written.\nThe relevant part is:\ncodeunit53100\"WLD BlockCustomer Meth\"{internalprocedureBlockCustomer(varCust:RecordCustomer;HideDialog:Boolean);varIsHandled:Boolean;begin... DoBlockCustomer(Cust,IsHandled);... end;localprocedureDoBlockCustomer(varCust:RecordCustomer;IsHandled:Boolean);beginifIsHandledthenexit;Cust.Blocked:=Cust.Blocked::All;Cust.Modify(true);end;... }Usually indicated with a “do”-function, the business logic takes place in that procedure. Obviously, when you have a decent amount of code, its recommended that you make it readable by applying all the Best Practices in terms of readability in the codeunit. Though, a few pointers here:\n keep the cyclomatic complexity low one line (function call) after an IF-clause one line (function call) after a repeat readable function calls … Call out to the method from a table\nNow, there is a reason that the one global procedure in the method-codeunit is internal. We shouldnt be calling this procedure directly. We should be calling it through its “class” (usually, a table can be seen as a class). That means, we would have to create a public (not internal) procedure on table-level, which can be used in the business logic.\nIn our example above, this could be that table extension:\ntableextension53100\"Customer Ext BASE\"extendsCustomer{procedureBlockCustomer(HideDialog:Boolean) varWLDBlockCustomerMeth:Codeunit\"WLD BlockCustomer Meth\";beginWLDBlockCustomerMeth.BlockCustomer(Rec,HideDialog);end;procedureBlockCustomer() beginBlockCustomer(false);end;}This practice improves readability. In fact, by doing this, you just extended the suggestions-list in VSCode (IntelliSense) indicating a new method that your class can do. This is very convenient for the developer that might need your new method.\nNote - it could very well be that there simply isnt any table that can act as a class for our method. In that case, you could use a codeunit as well.\nNaming Conventions\nYou might have noticed that the naming of our method is quite strict:\n codeunit name: WLD BlockCustomer Meth internal proc: BlockCustomer do-procedure: DoBlockCustomer It is important to align these namings. It indicates that the codeunit only does one thing (remember: encapsulation), and it improves searchability from outside the codeunit (for example when youre searching symbols or something).\nUsage Currently, there is no usage of this pattern in the BaseApp.\nThe pattern has a main advantage in an ISV product, just because of the decoupling and extensibility. Although, I have seen many occasions where parts of the pattern was useful on PTEs as well. You simply never know if ever at the customer site, there is going to be another partner that needs to create its own PTE, and has to depend on yours. So Id say, this pattern is everywhere applicable, no matter the type of the app.\nBenefits As I said, it will facilitate a lot of advantages. Lets explain a bit more in depth:\nExtensibility Thanks to the event layer, by applying this pattern for all methods, we will automatically have the bare minimum of events that we need to hook into a method: the OnBefore- and the OnAfter. Of course it would make sense to even add more events to the method when appropriate (eg, when youre inserting a record in a table, it might be interesting to also raise an event just before you call the insert).\nDecoupling Thanks to these same events, and the fact the pattern foresees a handler as well, we are able to “decouple” our method as well. What do I mean with that? Well, we can simply subscribe to the OnBeforeevent, and set IsHandled to true. This means it will never execute the do-procedure, which means, the original procedure/method/business logic is “decoupled”.\nWe can use this obviously for implementing our own method (a new way to accomplish this method), or to disable the method by simply subscribing to it, and only providing the IsHandled := true in our subscriber. However, there are many more usages where we can use this for.\nMaybe one more example: if you would apply this pattern to your product, at the customer, youll be able to hotfix your methods simply by decoupling them and fixing the method instead of waiting for a hotfix from the hotfix-departement.\nThis gives a lot of flexibility.\nReadability When we talk about readability, we actually talk about the part where we expose our method on the class. The rule is: never call the codeunit, but only from one place: from its “class” - or in BC terms: its table (or codeunit).\nIn terms of readability, that means that intellisense comes into play. In stead of:\nCodeunit.Run(Codeunit::\"Sales-Post\",SalesHeader);you simply get\nSalesHeader.Post();THAT is readable. The previous is not! That is just something we got used to.\nTestability There are two things in terms of testability where this pattern helps a lot.\nUnit testing You can interpret “unit testing” very broadly. But just imagine: when youre building your software entirely out of “methods” - which means: when youd build your software entirely with this “Generic Method Pattern”. Now, the list of methods, are all the units that you need to test: if you test all your methods, you kind of like test the majority of your software, right?\nSo you could simply set up rules in your company like: EVERY method needs a test-codeunit. And even more: since every method only has one global function - its pretty easy to know the context, and all the flavors to test your method.\nThe pattern describes the tests that needs to be written.\nDisabling methods Coming back to the “decoupling” part - in tests, you actually might need it more than you realize. Just imagine: you want to test method 1, but method 2 comes in the way by interfering with configurations that you need to do, or UI that is popping up, while it could be completely pointless.\nSolution: simply - within your test-codeunit - subscribe (with a manual subscriber) to method 2, set IsHandled to false - done!\nEncapsulation Dont underestimate the power of the encapsulation part of this pattern. One of the first questions that people ask themselves when reading into this pattern is: “isnt it going to consume all my codeunit-ids” or “so many codeunits, that cant be readable, right?”.\nThe fact that the functionality of one method is encapsulated in one codeunit is very powerful. Youll avoid Boat anchors simply because because, thanks to the encapsulation, there is a limited amount of code in the codeunit, of course.\nAnd because of that, it so much more maintainable, upgradable, readable, .. . Only advantages.\nWhen not to use However, there are occasions where you cant use this pattern. Just imagine if youd put EVERY SINGE LINE of code in a method, including the simple validation code on a table, or library-functions like in helper codeunits. That would obviously not make any sense.\nSo all I can say is: use your common sense.\nOne example: set the bar at “validation code”: any code that is solely there to facilitate data integrity doesnt belong in method codeunits.\nAnother tip might be: dont let the amount of codelines trick you in deciding to not use this pattern: when its a method, its a method. When it makes sense to be able to extend, decouple, .. then this pattern can help.\nSnippets waldos CRS AL Language Extension contains snippets that help you in setting up the boiler plate code in a matter of seconds.\nThe snippets are:\n tcodeunitMethodWithoutUIwaldo tcodeunitMethodWithUIwaldo List of references There have been a number of occasions where people have been sharing this pattern. Here is one:\n Discussions You can discuss this pattern here\n","categories":["Pattern"],"description":"","excerpt":"Created by Gary Winter (Cloud Ready Software), Described by waldo …","ref":"/docs/patterns/generic-method-pattern/","tags":[""],"title":"Generic Method"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/interface/","tags":"","title":"Interface"},{"body":"Created by Microsoft, Described by waldo\nDescription The if..then pair, while..do pair, and for..do pair must appear on the same line or the same level of indentation. If possible, you can align the lines it is even much more readable.\nBad code if(x=y) and(a=b) thenGood code if(x=y) and(a=b) thenDiscussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription The if..then …","ref":"/docs/bestpractices/keyword-pairs-indentation/","tags":["Readability"],"title":"Keyword Pairs - Indentation"},{"body":"\u003cCreated by Microsoft, Described by waldo\u003e\nDescription The end, if, repeat, for, while, else and case statement should always start a line.\nBad code ifIsContactNamethenValidateContactName() elseifIsSalespersonCodethenValidateSalespersonCode() elseifIsSalesCycleCodethenValidatSalesCycleCode();Good code ifIsContactNamethenValidateContactName() elseifIsSalespersonCodethenValidateSalespersonCode() elseifIsSalesCycleCodethenValidatSalesCycleCode();Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"\u003cCreated by Microsoft, Described by waldo\u003e\nDescription The end, if, …","ref":"/docs/bestpractices/line-start-keywords/","tags":["Readability"],"title":"Line Start Keywords"},{"body":"Created by Microsoft, Described by waldo\nDescription The repeat statement should always be alone on a line.\nBad code ifReservEntry.FindSet() thenrepeatGood code ifReservEntry.FindSet() thenrepeatDiscussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription The repeat …","ref":"/docs/bestpractices/lonely-repeat/","tags":["Readability"],"title":"Lonely Repeat"},{"body":"Created by Microsoft, Described by waldo\nDescription When calling an object statically use the Object Name, not the Object Id.\nBad code Page.RunModal(525,SalesShptLine);Good code Page.RunModal(Page::\"Posted Sales Shipment Lines\",SalesShptLine);Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription When calling an …","ref":"/docs/bestpractices/named-invocations/","tags":["Readability"],"title":"Named Invocations"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/nav/","tags":"","title":"NAV"},{"body":"Created by Microsoft, Described by waldo\nDescription A line of code should not have more than one statement.\nBad code ifOppEntry.Find('-') thenexit;Good code ifOppEntry.Find('-') thenexit;Bad code TotalCost+=Cost;TotalAmt+=Amt;Good code TotalCost+=Cost;TotalAmt+=Amt;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription A line of code …","ref":"/docs/bestpractices/one-statement-per-line/","tags":["Readability"],"title":"One Statement per Line"},{"body":"","categories":"","description":"","excerpt":"","ref":"/categories/pattern/","tags":"","title":"Pattern"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/performance/","tags":"","title":"Performance"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/readability/","tags":"","title":"Readability"},{"body":"","categories":"","description":"","excerpt":"","ref":"/search/","tags":"","title":"Search Results"},{"body":"Created by Microsoft, Described by waldo\nDescription if and else statements should be on separate lines.\nBad code ifAtom='\\\u003e'thenHasLogicalOperator:=trueelsebegin... end;Good code ifAtom='\\\u003e'thenHasLogicalOperator:=trueelsebegin... end;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription if and else …","ref":"/docs/bestpractices/separate-if-and-else/","tags":["Readability"],"title":"Seperate if and else"},{"body":"Created by Microsoft, Described by waldo\nDescription There must be exactly one space character on each side of a binary operator such as = + - AND OR =. The parameter comma operator however, should have a space after the comma.\nBad code \"Line Discount %\":=\"Line Discount Amount\"/\"Line Value\"*100;Good code \"Line Discount %\":=\"Line Discount Amount\"/\"Line Value\"*100;Bad code StartDate:=CalcDate('\u003c+'+Format(Days+i)+'D\\\u003e',StartDate);Good code StartDate:=CalcDate('\u003c+'+Format(Days+i) +'D\\\u003e',StartDate);Bad code StartDate:=0D;// Initialize Good code StartDate:=0D;// Initialize ","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription There must be …","ref":"/docs/bestpractices/spacing-binary-operators/","tags":["Readability"],"title":"Spacing Binary Operators"},{"body":"Created by waldo, Described by waldo\nDescription In general, subscribers have to be put in codeunits. There are a few performance considerations that you should keep in the back of your minds, when designing such a codeunit.\n Keep the codeunit as small as possible Work with a single instance codeunit only subscribe when necessary Avoid generic OnInsert/OnModify/OnDelete Lets discuss all points\nKeep the codeunit as small as possible Every time a subscriber gets called, a new instance of the codeunit is being loaded in memory, which takes memory and processing power. The smaller the codeunit, the less memory, and the faster it is.\nTherefore, its suggested to split the subscribers by functionality and avoid putting business logic in the actual codeunit. Tip: put all business logic in an “Method Codeunit”.\nExamples:\n if you app does things on Sales and Purchase, create a Sales-subs codeunit, and a Purchase-subs. if you have multiple functionalities in your app (lets callm modules), create a subs-codeunit per module, and only add the subscribers in there that are necessary for that module. Bad code codeunit2037325\"Setup Subs\"{SingleInstance=true;[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varAppId:ModuleInfo;NameListLbl:Label'Linked Texts Framework - List',Locked=true;DescriptionListLbl:Label'Edit linked texts',Locked=true;KeyWordListLbl:Label'LT,Distri,Technical,Functional,Reports',Locked=true;NameReportLbl:Label'Linked Texts Framework - Reports',Locked=true;DescriptionReportLbl:Label'View linked texts reports',Locked=true;KeyWordReportLbl:Label'LT,Distri,Technical,Functional,Reports',Locked=true;beginnavapp.GetCurrentModuleInfo(AppId);Sender.Insert(NameListLbl,DescriptionListLbl,KeyWordListLbl,page::\"LTE Linked Text List\",AppId.Id(),\"Manual Setup Category\"::General);Sender.Insert(NameReportLbl,DescriptionReportLbl,KeyWordReportLbl,page::\"LTE Linked Texts Reports\",AppId.Id(),\"Manual Setup Category\"::General);end;[EventSubscriber(ObjectType::Codeunit,codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varAppId:ModuleInfo;NameLayoutLbl:Label'Report Helper - Layout',Locked=true;DescriptionLayoutLbl:Label'Set up or update report layout list',Locked=true;KeyWordLayoutLbl:Label'RH,Distri,Technical,Functional,Reports,Layout',Locked=true;NameCaptionsLbl:Label'Report Helper - Captions',Locked=true;DescriptionCaptionsLbl:Label'Set up or update captions list',Locked=true;KeyWordCaptionsLbl:Label'RH,Distri,Technical,Functional,Reports,Captions',Locked=true;NameFunctionsLbl:Label'Report Helper - Functions',Locked=true;DescriptionFunctionsLbl:Label'Set up or disable functions',Locked=true;KeyWordFunctionsLbl:Label'RH,Distri,Technical,Functional,Reports,Functions',Locked=true;NameDFCLbl:Label'Report Helper - Default Footer',Locked=true;DescriptionDFCLbl:Label'Set up or update default footer',Locked=true;KeyWordDFCLbl:Label'RH,Distri,Technical,Functional,Reports,Default,Footer',Locked=true;beginnavapp.GetCurrentModuleInfo(AppId);Sender.Insert(NameLayoutLbl,DescriptionLayoutLbl,KeyWordLayoutLbl,page::\"RHE Report Layout List\",AppId.Id(),\"Manual Setup Category\"::General);Sender.Insert(NameCaptionsLbl,DescriptionCaptionsLbl,KeyWordCaptionsLbl,page::\"RHE Captions\",AppId.Id(),\"Manual Setup Category\"::General);Sender.Insert(NameFunctionsLbl,DescriptionFunctionsLbl,KeyWordFunctionsLbl,page::\"RHE Functions\",AppId.Id(),\"Manual Setup Category\"::General);Sender.Insert(NameDFCLbl,DescriptionDFCLbl,KeyWordDFCLbl,page::\"RHE Default Footer Card\",AppId.Id(),\"Manual Setup Category\"::General);end;}Good code Split into 2 codeunits, and move the business logic out.\ncodeunit2037325\"LTE Setup Subs\"{SingleInstance=true;[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varRegisterLTEManualSetup:codeunit\"Register LTE Manual Setup\";beginRegisterLTEManualSetup.RegisterLTEManualSetup();end;}codeunit2037324\"RHE Setup Subs\"{SingleInstance=true;[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varRegisterRHEManualSetup:codeunit\"Register RHE Manual Setup\";beginRegisterRHEManualSetup.RegisterRHEManualSetup();end;}Work with a single instance codeunit To avoid the extra “loading of the content” while a subscriber is being executed, use Single Instance codeunit for subscribers. Do take into account, of course, that it would share the state across the entire session.\nBad code codeunit2037324\"RHE Setup Subs\"{[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varRegisterRHEManualSetup:codeunit\"Register RHE Manual Setup\";beginRegisterRHEManualSetup.RegisterRHEManualSetup();end;}Good code codeunit2037324\"RHE Setup Subs\"{SingleInstance=true;[EventSubscriber(ObjectType::Codeunit,Codeunit::\"Manual Setup\",'OnRegisterManualSetup','',false,false)]localprocedureOnRegisterManualSetup(sender:Codeunit\"Manual Setup\") varRegisterRHEManualSetup:codeunit\"Register RHE Manual Setup\";beginRegisterRHEManualSetup.RegisterRHEManualSetup();end;}only subscribe when necessary If possible, only execute the subscriber when really necessary by using Manual Binding.\nBad code //subscriber - code should actually only run when Color=Red. [EventSubscriber(ObjectType::Table,Database::\"Just Some Table WLD\",'OnAfterValidateEvent','Message 2',false,false)]localprocedureJustDoSomthing(varRec:Record\"Just Some Table WLD\";varxRec:Record\"Just Some Table WLD\") beginifRec.color\u003c\u003e'RED'thenexit;//only execute when necessary ... end;//business logic ifJustSomeTable.FindSet() thenrepeatJustSomeTable.Validate(\"Message 2\",format(Random(1000)));untilJustSomeTable.Next() \u003c1;Good code ifJustSomeTable.FindSet() thenrepeatifJustSomeTable.Color='RED'thenBindSubscription(DemoSubs);JustSomeTable.Validate(\"Message 2\",format(Random(1000)));ifJustSomeTable.Color='RED'thenUnbindSubscription(DemoSubs);untilJustSomeTable.Next() \u003c1;Avoid OnInsert/OnModify/OnDelete The reason for this is, that it breaks the batch-calls:\n Any “OnInsert” subscriber breaks the bulk inserts, simply because it needs to perform an operation after every record that was inserted Any “OnModify” subscriber slows down the “ModifyAll”, simply because it needs to perform an operation after every record that was modified. I fact: 1 SQL call is turned into a loop of SQL calls. Any “OnDelete” subscriber slows down the “DeleteAll”, simply because it needs to perform an operation after every record that was deleted. I fact: 1 SQL call is turned into a loop of SQL calls. Avoid subscribers to these events.\nDiscussions You can discuss this guidelines here.\nYou can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\nReferences The Generic Method Pattern\n","categories":["Best Practice"],"description":"","excerpt":"Created by waldo, Described by waldo\nDescription In general, …","ref":"/docs/bestpractices/subscribercodeunits/","tags":["Performance"],"title":"Subscriber Codeunits"},{"body":"Created by Microsoft, Described by waldo\nDescription Whenever possible, do not use abbreviations in variables, functions and objects names.\nIf there is no other choice, then use the suggestions below.\n word Abbreviation absence Abs account Acc accounting Acc accumulated Accum action Act activity Activ additional Add address Addr adjust Adj adjusted Adjd adjustment Adjmt agreement Agrmt allocation Alloc allowance Allow alternative Alt amount Amt amounts Amts answer Ans applies Appl application Appln arrival Arriv assembly Asm assemble to order ATO assignment Assgnt associated Assoc attachment Attmt authorities Auth automatic Auto availability Avail average Avg ba db. BA balance Bal bill of materials BOM blanket Blnkt budget Budg buffer Buf business Bus business interaction management BIM buying Buy calculate Calc calculated Calcd calculation Calcu calendar Cal capacity Cap capacity requirements planning CRP cash flow CF cashflow CF catalog ctlg category Cat Central Processing Unit CPU center Ctr change Chg changes Chgs character Char characters Chars charge Chrg charges Chrgs check Chk classification Class collection coll column col comment Cmt company Co component Comp completion Cmpltn components Comps composition Compn compression Compr concurrent Concrnt confidential Conf confirmation Cnfrmn conflict Confl consolidate Consol consolidation Consolid consumption Consump contact Cont container Cntr contract Contr contracted Contrd control Ctrl controls Ctrls conversion Conv correction Cor correspondence Corres corresponding Corresp cost Cst sold COGS credit Cr cumulate Cumul currency Curr current Crnt customer Cust customer/vendor CV daily Dly dampener Damp database management system DBMS date D definition Def demonstration Demo department Dept department/project DP depreciation Depr description Desc detail Dtl detailed Dtld details Dtls deviation Dev difference Diff dimension Dim direct Dir discount Disc discrete Discr distribute Distr distributed Distrd distributor Distbtr distribution Distrn document Doc duplicate Dupl entered Entrd engineering Engin exchange Exch excluding Excl execute Exec expected Expd expedited Exped expense Exp expression Expr expiration Expir extended Ext explode Expl export Expt final Fnl finance Fin fiscal Fisc finished Fnshd fixed asset FA forward Fwd freight Frt general Gen general ledger GL group Gr header Hdr history Hist holiday Hol human resource HR identification ID import Imp inbound Inbnd including Incl included Incld incoming Incmg independent software vendor ISV industry Indust information Info initial Init Intrastat Intra interaction Interact integration Integr interest Int Interim Intm internal protocol IP inventory Invt inventoriable Invtbl invoice Inv invoiced Invd item tracking IT journal Jnl language Lang ledger Ledg level Lvl line Ln list Lt local currency LCY location Loc mailing Mail maintenance Maint management Mgt manual Man manufacturing Mfg manufacturer Mfr material Mat marketing Mktg maximum Max measure Meas message Msg minimum Min miscellaneous Misc modify Mod month Mth negative Neg non-inventoriable NonInvtbl notification Notif number No numbers Nos object Obj operating Oper opportunity Opp order Ord orders Ords original Orig organization Org outbound Outbnd Outgoing Outg output Out outstanding Outstd overhead Ovhd payment Pmt percent Pct personnel Persnl physical Phys picture Pic planning Plng posted Pstd posting Post positive Pos precision Prec prepayment Prepmt product Prod production Prod production order ProdOrd project Proj property Prop prospect Prspct purchase Purch purchases Purch purchaser Purchr purchase order PurchOrd quality Qlty quantity Qty questionnaire Questn quote Qte radio frequency RF range Rng receipt Rcpt received Rcd record Rec records Recs reconcile Recncl reconciliation Recon recurring Recur reference Ref register Reg registration Regn registered Regd relation Rel relations Rels relationship Rlshp release Rlse released Rlsd remaining Rem reminder Rmdr replacement Repl replenish Rplnsh replenishment Rplnsht report Rpt represent Rep represented Repd request Rqst required Reqd requirement Reqt requirements Reqts requisition Req reserve Rsv reserved Rsvd reservation Reserv resolution Resol resource Res response Rsp responsibility Resp retain Rtn retained Rtnd return Ret returns Rets revaluation Revaln reverse Rev review Rvw round Rnd rounded Rndd rounding Rndg route Rte routing Rtng routine Rout sales \u0026 receivables Sales safety Saf schedule Sched second Sec segment Seg select Sel selection Selctn sequence Seq serial Ser serial number SN service Serv sheet Sh shipment Shpt source Src special Spcl specification Spec specifications Specs standard Std frequency SF statement Stmt statistical Stat statistics Stats stock Stk stockkeeping unit SKU stream Stm structured query language SQL subcontract Subcontr subcontracted Subcontrd subcontracting Subcontrg substitute Sub substitution Subst suggest Sug suggested Sugd suggestion Sugn summary Sum suspended Suspd symptom Sympt synchronize Synch temporary Temp total Tot transaction Transac transfer Trans translation Transln tracking Trkg troubleshoot Tblsht troubleshooting Tblshtg unit of measure UOM unit test UT unrealized Unreal unreserved Unrsvd update Upd valuation Valn value Val value added tax VAT variance Var vendor Vend warehouse Whse web shop WS worksheet Wksh g/l GL % Pct 3-tier Three-Tier Outlook Synch Osynch Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Whenever …","ref":"/docs/bestpractices/suggested-abbreviations/","tags":["Readability"],"title":"Suggested Abbreviations"},{"body":"","categories":"","description":"","excerpt":"","ref":"/tags/","tags":"","title":"Tags"},{"body":"Created by Microsoft, Described by waldo\nDescription else should not be used when the last action in the then part is an exit, break, skip, quit, error.\nBad code procedureSomeProcedure() beginifIsAdjmtBinCodeChanged() thenError(AdjmtBinCodeChangeNotAllowedErr,...) elseError(BinCodeChangeNotAllowedErr,...);end;Good code procedureSomeProcedure() beginifIsAdjmtBinCodeChanged() thenError(AdjmtBinCodeChangeNotAllowedErr,...) Error(BinCodeChangeNotAllowedErr,...);end;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription else should not …","ref":"/docs/bestpractices/unnecessary-else/","tags":["Readability"],"title":"Unnecessary else"},{"body":"Created by Microsoft, Described by waldo\nDescription Do not use true or false keywords unnecessarily if the expression is already an logical expression.\nBad code ifIsPositive() =truethenGood code ifIsPositive() thenBad code ifComplete\u003c\u003etruethenGood code ifnotCompletethenDiscussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Do not use true …","ref":"/docs/bestpractices/unnecessary-truefalse/","tags":["Readability"],"title":"Unnecessary true/false"},{"body":"Created by Microsoft, Described by waldo\nDescription Variables that refer to a AL object must contain the objects name, abbreviated where necessary.\nA variable must begin with a capital letter.\nBlanks, periods, and other characters (such as parentheses) that would make quotation marks around a variable necessary must be omitted.\nIf a variable is a compound of two or more words or abbreviations, each word or abbreviation should begin with a capital letter.\nBad code WIPBuffer:Record\"Job WIP Buffer\"Good code JobWIPBuffer:Record\"Job WIP Buffer\"Bad code Postline:Codeunit\"Gen. Jnl.-Post Line\";Good code GenJnlPostLine:Codeunit\"Gen. Jnl.-Post Line\";Bad code \"Amount (LCY)\":Decimal;Good code AmountLCY:Decimal;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Variables that …","ref":"/docs/bestpractices/variable-naming/","tags":["Readability"],"title":"Variable Naming"},{"body":"Created by Microsoft, Described by waldo\nDescription Variables declarations should be ordered by type. In general, object and complex variable types are listed first followed by simple variables. The order should be:\n Record Report Codeunit XmlPort Page Query Notification BigText DateFormula RecordId RecordRef FieldRef FilterPageBuilder (Ref: Microsoft Docs)\nBad code StartingDateFilter:Text;Vendor:RecordVendor;Good code Vendor:RecordVendor;StartingDateFilter:Text;Discussions You can find discussions on all “Best Practices” here.\nIf you dont find the discussion of this guideline, please feel free to create a new one with the same title as this article.\n","categories":["Best Practice"],"description":"","excerpt":"Created by Microsoft, Described by waldo\nDescription Variables …","ref":"/docs/bestpractices/variables-declarations-order/","tags":["Readability"],"title":"Variables Declarations Order"}]