Reorganizing
|
|
@ -1,4 +1,5 @@
|
|||
+++
|
||||
chapter = true
|
||||
title = "1-patterns.md"
|
||||
weight = 110
|
||||
+++
|
||||
BIN
content/NAVPatterns/1-patterns/activity-log/Activity-Log-NAV.jpg
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
content/NAVPatterns/1-patterns/activity-log/Activity-Log.jpg
Normal file
|
After Width: | Height: | Size: 16 KiB |
112
content/NAVPatterns/1-patterns/activity-log/index.md
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
+++
|
||||
title = "Activity Logs"
|
||||
weight = 210
|
||||
+++
|
||||
## _by Ciprian Iordache at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Activity Log
|
||||
|
||||
**Abstract**
|
||||
|
||||
The Activity Log pattern tracks execution of activities. This is a Dynamics NAV specific implementation of the [Audit Log][anchor0] pattern.
|
||||
|
||||
[![ ][image0]][anchor1]
|
||||
|
||||
**Problem**
|
||||
|
||||
In general, integrating with external systems can be very challenging, due to the complexity of the situation -- connectivity issues, asynchronous operations, user errors, etc. These challenges require sometimes re-trying several times, polling the external system, re-send/re-get data as all these activities can succeed but can very well fail.
|
||||
|
||||
Similar challenges exist in situations where a lengthy, complex task, composed of different steps is to be executed by various people in various timeframes. In case of errors (but sometimes also in case of success) there will be a need to track these activities to see what happened and the actual person which did a specific step.
|
||||
|
||||
In all these cases, we need to be able to troubleshoot.
|
||||
|
||||
A tracking/logging functionality could be implemented for each activity/step separately, but this would lead to code duplication and problems in maintaining the code in future.
|
||||
|
||||
In NAV there is already the Change Log functionality which can record all the data changes that have been done to specific tables, specific fields. However, this functionality is not available for activities. Also, there are few places where separate logging/tracking implementations were done but the current pattern proposes an unified, central way of data recording and enables the user to track all/most of the activities.
|
||||
|
||||
**Solution**
|
||||
|
||||
The Activity Log pattern tracks specific outcome of the activities, in order to be able to assess what went wrong/fine or who performed a specific activity.
|
||||
|
||||
Activity Log pattern
|
||||
|
||||
* records the activity and its outcome (error or success messages)
|
||||
* assembles all messages in one central view and presents them to the user filtered for the specific activity and ordered in reverse chronological order.
|
||||
|
||||
Figure below illustrates the how the Activity Log manifests in the UI. The figure shows a part of an activity log for a posted document that was sent to the document exchange service and illustrates both successful and failed activities.
|
||||
|
||||
[![ ][image1]][anchor2]
|
||||
|
||||
This functionality is implemented in the following way - Activity Log table (TAB710) contains a simple function that allows you to log the result of a task or activity:
|
||||
|
||||
ActivityLog.LogActivity(ContextRecordID,ActivityLog.Status::Failed,ContextDescription,ActivityDescription,ActivityMessage);
|
||||
|
||||
Similar to TAB700 for Error Messaging, the Activity Log table contains a RECORDID that is a link to the parent/context entity. That permits the Activity Log to be used in a generic way, for any kind of entities (tables) and it also permits filtering the data to a specific related entity only before being presenting to the user.
|
||||
|
||||
The following parameters should be provided to the function:
|
||||
|
||||
* RecordID: The record/context for which the activity is logged
|
||||
* Status: The task/activity outcome
|
||||
* Descriptions/Messages: fields that will clearly describe the state and outcome of the task
|
||||
|
||||
To show the log, add a page action, with the caption including the name "<prefix\> Log" and link it to the image named "Log":
|
||||
|
||||
{ ;1 ;Action ;
|
||||
Name=ActivityLog;
|
||||
CaptionML=ENU=Activity Log;
|
||||
ToolTipML=ENU=View the status and any errors if the document was sent as an electronic document or OCR file through the document exchange service.;
|
||||
ApplicationArea=\#Basic,\#Suite;
|
||||
Image=Log;
|
||||
OnAction=VAR
|
||||
ActivityLog@1000 : Record 710;
|
||||
BEGIN
|
||||
ActivityLog.ShowEntries(RECORDID);
|
||||
END;
|
||||
}
|
||||
|
||||
**NAV usages**
|
||||
|
||||
In Dynamics NAV 2016, there is a new feature for sending documents in electronic format to a document exchange service. In this case, sending documents requires multiple steps as it is an asynchronous activity and as such, in order to keep track of what's happening and when the Activity Log functionality was used. That offers later the possibility to see who sent and when a document was sent, when it was dispatched, if any dispatch errors and how many tries have been made until the document was finally dispatched or rejected.
|
||||
|
||||
So as usages in NAV 2016, we have the document exchange and OCR features plus the related posted documents involved in the document exchange feature.
|
||||
|
||||
* COD1294.TXT
|
||||
* COD1410.TXT
|
||||
* PAG1270.TXT
|
||||
* PAG1275.TXT
|
||||
* PAG143.TXT
|
||||
* PAG144.TXT
|
||||
* PAG189.TXT
|
||||
* TAB112.TXT
|
||||
* TAB114.TXT
|
||||
* TAB130.TXT
|
||||
|
||||
**Ideas for improvement**
|
||||
|
||||
Replace the scattered similar functionality (as mentioned above, we have several places having close functionality or similar requirements) with this new pattern.
|
||||
|
||||
**Consequences**
|
||||
|
||||
* Use with caution, similar to the Change Log functionality, as if the pattern will be used extensively in all the activities/operations within NAV, the table might become large containing many records and might cause some performance issues when presenting the data to the client (filtering on the specific activity).
|
||||
* Do not log private or confidential information (passwords, amounts, salaries, sensitive data), unless you are ok with this data to be showed to all users (even to users which normally would not have access to this data), thus overriding the permission sets.
|
||||
* Log only essential information (quality over quantity). Can the logged data be used to analyze the problem, or is it just junk data?
|
||||
|
||||
**NAV Versions**
|
||||
|
||||
Supported from NAV 2016
|
||||
|
||||
**Related Topics**
|
||||
|
||||
Error Message Processing -- provides a similar view and uses similar concepts: has a generic implementation (uses as link the same RECORDID feature) and uses same filtering functionality when displaying the data to the user.
|
||||
|
||||
Audit Log -- as mentioned in the beginning, this pattern is a NAV specific implementation of the audit log pattern.
|
||||
|
||||
|
||||
|
||||
[anchor0]: http://martinfowler.com/eaaDev/AuditLog.html
|
||||
[anchor1]: Activity-Log.jpg
|
||||
[anchor2]: Activity-Log-NAV.jpg
|
||||
|
||||
|
||||
[image0]: Activity-Log.jpg
|
||||
[image1]: Activity-Log-NAV.jpg
|
||||
|
After Width: | Height: | Size: 32 KiB |
122
content/NAVPatterns/1-patterns/argument-table/index.md
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
+++
|
||||
title = "Argument Table"
|
||||
weight = 220
|
||||
+++
|
||||
# Argument table pattern
|
||||
|
||||
_By Nikola Kukrika and Waldo_
|
||||
|
||||
# Abstract
|
||||
|
||||
The Argument Table pattern is used to provide an extension point for adding new arguments without changing the signature. By grouping multiple arguments into a table the code becomes more readable (function signature and the usage of the function).
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
# Problem
|
||||
|
||||
In CAL overloading function signature is not supported. It is also not possible to provide default values for the function arguments.
|
||||
|
||||
When an argument needs to be added to the function, the existing function needs to be extracted to a new method with an additional argument and the original function will call new method. This will cause an upgrade problem in the future, since the entire body of the method is replaced.
|
||||
|
||||
Second commonly occurring problem is option duplication. In order to pass options often they are duplicated in the signature.
|
||||
|
||||
The last problem that can be solved is high number of arguments. Functions with a high number of arguments are hard to understand. Having arguments grouped within the table with a meaningful name will improve readability and make code easier to understanding.
|
||||
|
||||
Few examples of the bad implementations are as illustrated here:
|
||||
|
||||
## Bad example 1
|
||||
|
||||
|
||||
**PROCEDURE FillInVATReturnData@1200001(VAR DeclarationID@1200000 : Code\[20\];VAR LineID@1200001 :**
|
||||
**Code\[20\];VAR PeerID@1200002 : Code\[20\]; VAR DocumentNo@1200003 : Code\[20\]; VAR NumberOfCopies@1200007 :**
|
||||
**Integer; VAR Uploaded@1200004 : Boolean; VAR Correction@1200005 : Boolean; VAR HasValidationErr@1200006 :**
|
||||
**Boolean);**
|
||||
|
||||
Call
|
||||
|
||||
**FillInVATReturnData(NoSeries, NextLineID, CustomerID, DocumentNo, SingleCopy, ???, ??, ...., ...)**
|
||||
|
||||
In this example the code is hard to read and understand. Adding an additional argument will require refactoring of the existing function. Each time a new argument is added a new function will be created.
|
||||
|
||||
## Bad example 2
|
||||
|
||||
**LOCAL PROCEDURE GetTableSyncSetupW1@3(**
|
||||
**OldTableId@1002 : Integer;**
|
||||
**VAR UpgradeTableId@1001 : Integer;**
|
||||
**VAR TableUpgradeMode@1000 : 'Check, Copy, Move, Force') : Boolean;**
|
||||
BEGIN
|
||||
CASE OldTableId OF
|
||||
DATABASE::"Sales Header":
|
||||
SetTableSyncSetup(0,TableUpgradeMode::Check,UpgradeTableId,TableUpgradeMode);
|
||||
DATABASE::"Posting Exch. Column Def":
|
||||
SetTableSyncSetup(104025,TableUpgradeMode::Copy,UpgradeTableId,TableUpgradeMode);
|
||||
DATABASE::"Payment Export Data":
|
||||
SetTableSyncSetup(0,TableUpgradeMode::Force,UpgradeTableId,TableUpgradeMode);
|
||||
ELSE
|
||||
EXIT(FALSE);
|
||||
END;
|
||||
EXIT(TRUE);
|
||||
END;
|
||||
|
||||
In this example each time a new argument is added all function calls will have to be updated. Option is duplicated in the signature, which will cause issues if a new option is defined or the existing options are renamed.
|
||||
|
||||
# Solution
|
||||
|
||||
By grouping the arguments within the table it is possible to add additional argument and reuse it where it is needed without changing the signature.
|
||||
|
||||
Multiple parameters are grouped within the single object with a meaningful name so the code becomes more readable.
|
||||
|
||||
It is possible to assign default values and to have the code validation.
|
||||
|
||||
Argument table should preferably be a temporary table since the implementation is simpler.
|
||||
|
||||
The examples of usages addressing problems shown above are:
|
||||
|
||||
## Good example 1
|
||||
|
||||
New table
|
||||
TAB 50003 VAT Return Data
|
||||
**PROCEDURE FillInVATReturnData@1200001(VAR VATReturnData@1200000 : Record 50003);**
|
||||
|
||||
****
|
||||
|
||||
VATReturnData.INIT;
|
||||
VATReturnData.NumberOfCopies := GetDefaultNumberOfCopies;
|
||||
VATReturnData.Uploaded := FALSE;
|
||||
|
||||
FillInVATReturnData(VATReturnData);
|
||||
|
||||
By introducing an argument table, code is much more readable since there is a single argument for a function. It is easy to see which arguments are passed in and which are modified in a function.
|
||||
|
||||
## Good example 2
|
||||
|
||||
Good example
|
||||
**PROCEDURE GetTableSyncSetupW1@3(VAR TableSynchSetup@1000 : Record 2000000135);**
|
||||
BEGIN
|
||||
SetTableSyncSetup(DATABASE::"Sales Header",0,TableSynchSetup.Mode::Check);
|
||||
SetTableSyncSetup(DATABASE::"Posting Exch. Column Def",104025,TableSynchSetup.Mode::Copy);
|
||||
SetTableSyncSetup(DATABASE::"Payment Export Data",0,TableSynchSetup.Mode::Force);
|
||||
END;
|
||||
|
||||
Option definition is not encapsulated within the table. Arguments are grouped and we can add additional arguments without the need to change the signature.
|
||||
|
||||
# Downsides
|
||||
|
||||
You need to create one more table
|
||||
|
||||
Complex types can't be embedded as fields in tables (cannot have a record field type etc).
|
||||
|
||||
# NAV Usages
|
||||
|
||||
Upgrade Codeunits
|
||||
|
||||
# Related Patterns
|
||||
|
||||
Posting Routine, Select behavior: Setting fields on existing records in order not to change the signatures.
|
||||
|
||||
|
||||
|
||||
[anchor0]: 0218.Argument-Table-image.png
|
||||
|
||||
|
||||
[image0]: 0218.Argument-Table-image.png
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 107 KiB |
104
content/NAVPatterns/1-patterns/blocked-entity/_index.md
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
+++
|
||||
title = "Blocked Entity.md"
|
||||
weight = 270
|
||||
+++
|
||||
_by Abhishek Ghosh at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
The Blocked Entity is used when it is required to stop transactions for an entity (mostly master data), temporarily or permanently.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## Description
|
||||
|
||||
To block entities through metadata, read this pattern. To do the same thing through data, read [Data Driven Blocked Entity pattern][anchor1].
|
||||
|
||||
The business entity holds a state that controls if a given transaction is allowed. The state is used by the logic controlling transactions.****The change of state could either be temporary or permanent.
|
||||
|
||||
An example of a temporary halt is when a retail chain selling items has received lot of complaints about an item, and the company wants to stop all transactions, both purchase and sale, with that item until the dealer has clarified the issue with his supplier and possibly received a replacement for the defective stock. Another common example is during counting the physical inventory using cycle counting where the counting is done in one section of a warehouse at a time, so that the regular operations can continue in the other parts of the warehouse. In these situations, it is necessary to block all transactions, such as picks and put-aways, for a bin while warehouse counting is in progress for that bin.
|
||||
|
||||
In contrast, a permanent halt to transactions could be required when an item has become obsolete (or is about to become obsolete), and the company wants to stop further purchase or sale of the item. However, the company wants to maintain the transaction history of the item and, therefore, does not want to delete the item record.
|
||||
|
||||
A simple design implementation of such requirements in Microsoft Dynamics NAV is to add a Blocked field in the entity table (and on the associated page). The implementation takes this state into the logic and checks for the value of this field in related transactions. For most simple scenarios, it is sufficient to have two states on the Blocked field, specifying whether it is allowed to perform transactions for the entity or not.
|
||||
|
||||
In certain situations, however, there could be different levels of blocking. For example, the company could block all sales to a customer that has overdue payments, and the company does not want to allow transactions with this customer until the payments are received. In other situations, the customer may have raised objections about an invoice, and the company has decided not to generate new invoices for the customer until the issue has been resolved. However, the company does want to continue shipping goods to the customer so as not to impact the customer's operations. In these scenarios, it may be necessary to have multiple states on the Blocked field depending on the level of restriction that is needed.
|
||||
|
||||
## Usage
|
||||
|
||||
As mentioned in the previous section, there are two implementations depending on business requirements: The 2-state Boolean field for simple implementations and the multi-state option field for more complex requirements. The implementation flow is similar for both patterns, except how the validation is implemented. The following discusses the two scenarios one by one.
|
||||
|
||||
### Boolean Implementation
|
||||
|
||||
Add a Boolean field named Blocked in the table.
|
||||
|
||||
In the relevant logic, add a condition to check the status of the Blocked flag. The cheapest way is to use a TESTFIELD:
|
||||
|
||||
_<rec variable\>.TESTFIELD(Blocked,FALSE);_
|
||||
|
||||
Alternatively, you can throw a custom error message. However, you should only do that if the default error message thrown by TESTFIELD is not sufficient.
|
||||
|
||||
### Option-Field Implementation
|
||||
|
||||
Add an option field named Blocked in the table. The option values will reflect the different blocked states required by the company.
|
||||
|
||||
Add this field on the card page (or on the List page if the entity does not have a card). As with the Boolean implementation, the convention is to add this field in the right-hand column in the General FastTab of the card page.
|
||||
|
||||
Implement a function in the table that takes the transaction context as input and evaluates the Blocked field to decide whether the transaction should be allowed or not. Optionally, the function can be responsible for notifying the user and bubble up an error message straight away.
|
||||
|
||||
Note: the option field assumes that only one of the multiple options can be active at a time. In other words, the options should be mutually exclusive.
|
||||
|
||||
How not to use the option field in this case: if we want to block an item from sale and/or purchase, the 4 combined options would be **Block none** | **Block Sales** | **Block Purchases** | **Block Sales and Purchases**. This doesn't scale, because if now we need to block another transaction, the number of option would grow too fast. In this situations, it is better to use two Boolean fields: **Blocked Sale**: **true|false** and **Blocked Purchase: true|false**.
|
||||
|
||||
A good example of usage would be for varying the behavior depending on the chosen option, for example by displaying a different error message depending on the reason an Item is blocked. In this case we can have the item **Not Blocked** | **Blocked due to defect** | **Blocked waiting for approval**, etc.
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
### Boolean Implementation
|
||||
|
||||
[![ ][image1]][anchor2]
|
||||
|
||||
An example of the Boolean implementation on the Item card.
|
||||
|
||||
In codeunit 22 -- Item Jnl.-Post Line, the following lines of code have implemented a check based on the value of the Blocked field:
|
||||
|
||||
IF NOT CalledFromAdjustment THEN
|
||||
Item.TESTFIELD(Blocked,FALSE);
|
||||
|
||||
### Option-Field Implementation
|
||||
|
||||
[![ ][image2]][anchor3]
|
||||
|
||||
An example of the option field implementation on the Customer card.
|
||||
|
||||
The CheckBlockedCustOnDocs and CheckBlockedCustOnJnls functions in the Customer table are responsible for validating the Blocked state with respect to the input document type. These functions are invoked in several areas, such as posting routines, where a status check on the Blocked field is required. This is a good practice where the Blocked implementation gets more complex, as this encourages reuse and ensures uniformity of implementation.
|
||||
|
||||
## NAV Usages
|
||||
|
||||
Entities where the Blocked Entity has been implemented include:
|
||||
|
||||
* Item
|
||||
* G/L Account
|
||||
* Customer
|
||||
* Vendor
|
||||
* Bin
|
||||
|
||||
## Related Topics
|
||||
|
||||
The [Released Entity][anchor4].
|
||||
|
||||
[watch?v=O2R fTSup1o&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=16][anchor5]
|
||||
|
||||
|
||||
|
||||
[anchor0]: 2260.BlockedEntityPattern.png
|
||||
[anchor1]: /nav/w/designpatterns/247.data-driven-blocked-entity/edit
|
||||
[anchor2]: 8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png
|
||||
[anchor3]: 3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png
|
||||
[anchor4]: /nav/w/designpatterns/115.released-entity.aspx
|
||||
[anchor5]: https://www.youtube.com/watch?v=O2R-fTSup1o&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=16
|
||||
|
||||
|
||||
[image0]: 2260.BlockedEntityPattern.png
|
||||
[image1]: 8637.BlockedEntityPattern_5F00_5F00_5F00_Boolean.png
|
||||
[image2]: 3056.BlockedEntityPattern_5F00_5F00_5F00_Option.png
|
||||
|
After Width: | Height: | Size: 15 KiB |
|
|
@ -0,0 +1,107 @@
|
|||
+++
|
||||
title = "Data Driven Blocked Entity"
|
||||
weight = 470
|
||||
+++
|
||||
_Written by Bogdan Andrei Sturzoiu, at Microsoft Development Center Copenhagen_
|
||||
|
||||
******Abstract**
|
||||
|
||||
This pattern implements a generic mechanism for dynamically restricting and allowing usage of a record by the business process administrator.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
**Problem**
|
||||
|
||||
A NAV record can be used in a number of functionalities across the app. There are situations, however, when the administrator wants to restrict the consumption of such a record, as well as lift the restriction when it is no longer relevant.
|
||||
|
||||
For example, a new customer record should not be used for posting documents until it is approved by the relevant approver.
|
||||
|
||||
We could solve this by using the [Blocked Entity pattern][anchor1], but it requires database schema changes, which have an upgrade impact.
|
||||
|
||||
The blocked entity pattern involves:
|
||||
|
||||
1. Adding a "blocked" status field on the record (either a Boolean or in the more advanced cases, an option field refining the usage).
|
||||
2. Adding specific code for the record in every place where the restriction needs to be enforced.
|
||||
|
||||
In contrast, the Data-driven Blocked Entity pattern involves adding a new record (data change) to mark the restriction, instead of adding a new field (metadata change).
|
||||
|
||||
**Solution**
|
||||
|
||||
This pattern describes a generic mechanism of adding and lifting restrictions for any type of record.
|
||||
|
||||
The restriction mechanism has the following elements:
|
||||
|
||||
1. Adding a restriction record for a specific reason (e.g. the record requires approval), which will act as a surrogate key (unique identifier) for the restricted record. This can be implemented through a workflow response, or directly, by calling the Restriction Management codeunit function.
|
||||
2. Lifting the restriction when it is no longer necessary. Again, this can be done using a workflow response or directly by calling the dedicated function.
|
||||
3. Consuming the restriction in the places of interest for a specific purpose. This is an application feature that requires a call to the Restriction Management codeunit to check for restrictions.
|
||||
|
||||
Currently, the restrictions are record-based and type-less. They act as simple tokens, and they have:
|
||||
|
||||
* A reason (e.g. the record requires approval)
|
||||
* A purpose (e.g. the record cannot be posted).
|
||||
|
||||
You must make sure to differentiate between the reason and the purpose. That is because the restriction can only be added once per record, but consumed in multiple places.
|
||||
|
||||
******Example**
|
||||
|
||||
For example, we want to restrict posting Gen. Journal Lines if a customer has not been added in Account No. field.
|
||||
|
||||
For this, the following components are needed:
|
||||
|
||||
1. When a Gen. Journal Line is inserted, call RestrictRecordUsage in COD1550, either directly in the trigger or using an event subscriber.
|
||||
2. When you validate a Customer No. as Account no. and Customer as Account Type, lift the restrictions by calling AllowRecordUsage in COD1550\.
|
||||
3. The consumption of the restriction at posting is already implemented as an event in TAB81, OnCheckGenJournalLinePostRestrictions. No further action necessary.
|
||||
|
||||
**NAV Usage**
|
||||
|
||||
All the approval workflows include a response that restricts usage of a record, and then, at the end of an approval loop, a response that allows the usage again by lifting the restriction. See responses "Add record restriction" and "Remove record restriction" implemented in COD1521\.[
|
||||
][anchor2]
|
||||
|
||||
The code behind the "Add record restriction" workflow response:
|
||||
|
||||
RecRef.GETTABLE(Variant);
|
||||
Workflow.GET(WorkflowStepInstance."Workflow Code");
|
||||
RecordRestrictionMgt.RestrictRecordUsage(RecRef.RECORDID,STRSUBSTNO(RestrictUsageDetailsTxt,Workflow.Code,Workflow.Description));
|
||||
|
||||
|
||||
The code behind the "Remove record restriction" response:
|
||||
|
||||
RecRef.GETTABLE(Variant);
|
||||
CASE RecRef.NUMBER OF
|
||||
DATABASE::"Approval Entry":
|
||||
BEGIN
|
||||
RecordRestrictionMgt.AllowRecordUsage(RecRef.RECORDID);
|
||||
RecRef.SETTABLE(ApprovalEntry);
|
||||
RecRef.GET(ApprovalEntry."Record ID to Approve");
|
||||
AllowRecordUsage(RecRef);
|
||||
END;
|
||||
DATABASE::"Gen. Journal Batch":
|
||||
BEGIN
|
||||
RecRef.SETTABLE(GenJournalBatch);
|
||||
RecordRestrictionMgt.AllowGenJournalBatchUsage(GenJournalBatch);
|
||||
END
|
||||
ELSE
|
||||
RecordRestrictionMgt.AllowRecordUsage(RecRef.RECORDID);
|
||||
END;
|
||||
|
||||
|
||||
Notice****how lifting a restriction for a Gen. Journal Batch involves lifting all the restrictions for the individual journal lines in the batch (hence the special branching of the code).
|
||||
|
||||
******Consequences**
|
||||
|
||||
Currently, there can only be one restriction per record. There are no restriction types.
|
||||
|
||||
In the future, a type field should be added to the restriction table, to allow adding restrictions for different purposes, and to refine their consumption. For example, a posting restriction might only be enforced for restrictions originating from approvals.
|
||||
|
||||
**NAV** **Versions**
|
||||
|
||||
This pattern has been introduced in Dynamics NAV 2016\.
|
||||
|
||||
|
||||
|
||||
[anchor0]: attention.jpg
|
||||
[anchor1]: /nav/w/designpatterns/79.blocked-entity
|
||||
[anchor2]: https://microsoft.sharepoint.com/teams/DynamicsNAV/Wiki/Nav%20Wiki%20Documents/NAV%20App%20Patterns/NAV%20App%20Patterns%20for%20Review/Data-Driven%20Blocked%20Entity.docx#_msocom_2
|
||||
|
||||
|
||||
[image0]: attention.jpg
|
||||
|
After Width: | Height: | Size: 30 KiB |
110
content/NAVPatterns/1-patterns/cached-web-service-calls/index.md
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
+++
|
||||
title = "Cached Web Server Calls.md"
|
||||
weight = 290
|
||||
+++
|
||||
_by Mostafa Balat, Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
In a service-oriented deployment, web services are used to extend NAV's functionality and reach. Depending on how volatile this data is and the corresponding usage scheme, it is expected to be up-to-date within a pre-defined period of time (e.g. once a day).
|
||||
|
||||
## Description
|
||||
|
||||
When NAV is integrated with external services, then the user scenarios become dependent on the data and functions offered by such services. Eventually, there are different approaches through which the external data can be retrieved, stored and used.
|
||||
|
||||
* Dynamic: either exposed by the external service itself or by a separate catalog that NAV can query.
|
||||
* Advantage: data is always up-to-date
|
||||
* Disadvantage: it requires constant connection to the data source.
|
||||
* Static: hard-coded in the database for the user to benefit from.
|
||||
* Advantage: data is promptly available when needed.
|
||||
* Disadvantage: if data changes at some point, it will require a maintenance effort, which exposes the business process to a risk of failure.
|
||||
* Cached: offered through an external service and gets pulled according to a pre-defined refresh rate or manually.
|
||||
* Advantage: data is 'up-to-date' within the rules acceptable by the business process, without extra load on the network resources or the external service.
|
||||
* Disadvantage: if data changes while the auto-refresh did not happen yet, the user may not have access to the latest data; however, the user can manually force a refresh of the data, if asked to do so.
|
||||
|
||||
### When to Use It
|
||||
|
||||
Offer data in lookups that were cached from an external service.
|
||||
|
||||
### Diagram
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## Usage
|
||||
|
||||
Set up an NAV feature to consume the data from an external service. Refresh the data on a pre-defined refresh rate (e.g. once a day) or when enforced by a power user or an admin. Cache the data in a table and offer it in lookups, as applicable.
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
### Overview
|
||||
|
||||
**PAG1259 Bank Name - Data Conv. List** offers the required functionality to refresh and display the list of bank names needed to specify which file format to convert to. The page can be accessed from **PAG1260 Bank Data Conv. Service Setup** to display all available bank names. It is also used as a lookup on **PAG370 Bank Account Card**, where it offers a filtered view of the cached bank names based on the Country/Region Code field.
|
||||
|
||||
If **PAG1259 Bank Name - Data Conv. List** is being open and the cached data is 'old', it refreshes the cache. The cached data is stored in **TAB1259 Bank Data Conv. Bank**. Meanwhile, the user has the chance to refresh the data using
|
||||
|
||||
### Code Sample
|
||||
|
||||
OnInit=BEGIN
|
||||
ShortTimeout := 5000;
|
||||
LongTimeout := 30000;
|
||||
END;
|
||||
OnOpenPage=VAR
|
||||
BankDataConvBank@1002 : Record 1259;
|
||||
ImpBankListExtDataHndl@1000 : Codeunit 1289;
|
||||
CountryRegionCode@1004 : Text;
|
||||
HideErrors@1003 : Boolean;
|
||||
BEGIN
|
||||
CountryRegionCode := IdentifyCountryRegionCode(Rec,GETFILTER("Country/Region Code"));
|
||||
IF BankDataConvBank.ISEMPTY THEN BEGIN
|
||||
ImpBankListExtDataHndl.GetBankListFromConversionService(HideErrors,CountryRegionCode,ShortTimeout);
|
||||
EXIT;
|
||||
END;
|
||||
RefreshBankNamesOlderThanToday(CountryRegionCode,HideErrors,ShortTimeout);
|
||||
END;
|
||||
OnAction=VAR
|
||||
ImpBankListExtDataHndl@1000 : Codeunit 1289;
|
||||
FilterNotUsed@1001 : Text;
|
||||
ShowErrors@1003 : Boolean;
|
||||
BEGIN
|
||||
ShowErrors := TRUE;
|
||||
ImpBankListExtDataHndl.GetBankListFromConversionService(ShowErrors,FilterNotUsed,LongTimeout);
|
||||
END;
|
||||
LOCAL PROCEDURE IdentifyCountryRegionCode@1(VAR BankDataConvBank@1002 : Record 1259;Filter@1000 : Text) : Text;
|
||||
VAR
|
||||
CompanyInformation@1001 : Record 79;
|
||||
BlankFilter@1003 : Text;
|
||||
BEGIN
|
||||
BlankFilter := '''''';
|
||||
IF Filter = BlankFilter THEN BEGIN
|
||||
CompanyInformation.GET;
|
||||
BankDataConvBank.SETFILTER("Country/Region Code",CompanyInformation."Country/Region Code");
|
||||
EXIT(BankDataConvBank.GETFILTER("Country/Region Code"));
|
||||
END;
|
||||
EXIT(Filter);
|
||||
END;
|
||||
LOCAL PROCEDURE RefreshBankNamesOlderThanToday@5(CountryRegionCode@1000 : Text;ShowErrors@1002 : Boolean;Timeout@1004 : Integer);
|
||||
VAR
|
||||
BankDataConvBank@1001 : Record 1259;
|
||||
ImpBankListExtDataHndl@1003 : Codeunit 1289;
|
||||
BEGIN
|
||||
IF CountryRegionCode <\> '' THEN
|
||||
BankDataConvBank.SETFILTER("Country/Region Code",CountryRegionCode);
|
||||
BankDataConvBank.SETFILTER("Last Update Date",'<%1',TODAY);
|
||||
IF BankDataConvBank.FINDFIRST THEN
|
||||
ImpBankListExtDataHndl.GetBankListFromConversionService(ShowErrors,CountryRegionCode,Timeout);
|
||||
END;
|
||||
|
||||
## NAV Usages
|
||||
|
||||
Bank name lookup on the Bank Account card for dynamically identifying the format to use to generate a bank-specific payment file.
|
||||
|
||||
## Ideas for Improvement
|
||||
|
||||
Expose the refresh rate through a setup table to make it easily configurable without changing the code.
|
||||
|
||||
|
||||
|
||||
[anchor0]: Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png
|
||||
|
||||
|
||||
[image0]: Cached_5F00_Web_5F00_Service_5F00_Calls_5F00_Diagram.png
|
||||
|
After Width: | Height: | Size: 31 KiB |
|
|
@ -0,0 +1,39 @@
|
|||
+++
|
||||
title = "Conditional Cascading Update"
|
||||
weight = 370
|
||||
+++
|
||||
_by Jan Hoek at IDYN _
|
||||
|
||||
## **Abstract**
|
||||
|
||||
The Conditional Cascading Update pattern is used to intelligently populate fields whose values depend on other field values. In this pattern description, the field triggering the update will be called "source field", and the depending field will be called "target field".
|
||||
|
||||
## **Description
|
||||
**
|
||||
|
||||
The value of one table field sometimes depends on the value of another field, typically following an application-defined transformation (note that we're talking about transformations of field values here. This has nothing to do with e.g. form transformation), such as conversion to uppercase, removal of certain characters etc.
|
||||
|
||||
If the target field is non-editable, said transformation is usually the only way for the target field to receive new values, so no irreproducible information can be lost. However, if the target field is editable, the user may have cared enough to override the default (transformed) value, in which case revalidating the source field should not blindly replace the target field's value.
|
||||
|
||||
## **Usage**
|
||||
|
||||
In the OnValidate trigger of the source field, test if the target field value is either blank, or equal to the transformed value of the source field's previous contents. If it is, populate the target field's value with the transformed source field value. If it is not, do nothing (effectively preserving the value set by the user).
|
||||
|
||||
## **NAV Specific Example**
|
||||
|
||||
In the base application, this pattern can be found in Search Name/Search Description fields, which are updated with the uppercase value from the corresponding Name/Description field when the latter is validated, only if the Search Name/Description in question is currently blank, or equal to the (uppercase equivalent) of the previous contents of the Name/Description field.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
In this particular case, the transformation between source and target fields is implicit and due to the different data types of the fields (text vs. code). Note how the field triggers of the Search Name field itself do not contain any logic linked to this pattern.
|
||||
|
||||
## **Consequences**
|
||||
|
||||
There is a case when this pattern should not be used. If the target field is non-editable, this pattern will not add any value, since there won't be any user-overridden values to protect.
|
||||
|
||||
|
||||
|
||||
[anchor0]: 3124.T18_5F00_Name_5F00_OnValidate.png
|
||||
|
||||
|
||||
[image0]: 3124.T18_5F00_Name_5F00_OnValidate.png
|
||||
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 44 KiB |
118
content/NAVPatterns/1-patterns/copy-document/index.md
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
+++
|
||||
title = "Copy Document"
|
||||
weight = 390
|
||||
+++
|
||||
_By Bogdan Sturzoiu at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
The goal of the Copy Document pattern is to create a replica of an existing open or closed document (posted or not posted), by moving the lines and, optionally, the header information from the source document to a destination document.
|
||||
|
||||
## Description
|
||||
|
||||
Documents are widely used by most of our customers. Many times, a significant portion of these documents are similar to each other, either by sharing the same customer, vendor, type, or line structure. Being able to re-use a document as a base for creating a new one is therefore an important means of saving time.
|
||||
|
||||
Other business scenarios require that a newly created document is applied to an existing document. For example, in returns management, a return order can be the reversal of an existing order and can therefore be copied from the original order. Other times, there is even a legal requirement to match the document to its source. For example, credit memos need to be applied to the originating Invoice.
|
||||
|
||||
For these reasons, NAV supports the copying of documents as a method to re-use or link documents.
|
||||
|
||||
The Copy Document functionality is used in the following situations:
|
||||
|
||||
* The user wants to create a new open sales document (Quote, Order, Blanket Order, Invoice, Return Order, Credit Memo) based on an existing posted or non-posted sales document (Quote, Blanket Order, Order, Invoice, Return Order, Credit Memo, Posted Shipment, Posted Invoice, Posted Return Receipt, Posted Credit Memo).
|
||||
* The user wants to create a new open purchase document (Quote, Order, Blanket Order, Invoice, Return Order, Credit Memo) based on an existing posted or non-posted purchase document (Quote, Blanket Order, Order, Invoice, Return Order, Credit Memo, Posted Shipment, Posted Invoice, Posted Return Receipt, Posted Credit Memo).
|
||||
* The user wants to create a new production order (Simulated, Planned, Firm Planned or Released) based on an existing production order (Simulated, Planned, Firm Planned, Released or Finished).
|
||||
* The user wants to create a new assembly order based on an existing assembly document (Quote, Blanket Order, Order and Posted Order).
|
||||
* The user wants to create a new service contract or quote based on an existing service contract or quote.
|
||||
* The user wants to create all relevant return-related documents. For example, from a sales return order, the user can recreate the involved supply chain documentation, by copying the information upwards to a purchase return order (if the items need to be returned to the vendor), purchase order (if the items need to be reordered), and sales order (if the items need to be re-sent to the customer).
|
||||
|
||||
**Note**
|
||||
|
||||
* Not all to and from combinations are allowed. For example, you can only copy to open document types, since the posted documents are not editable.
|
||||
* The destination document needs to have the header fully created. For example, a Sales Order will need to have the Sell-To Customer No. populated.
|
||||
|
||||
## Usage
|
||||
|
||||
The Dynamics NAV application developer can take into account using the Copy Document design pattern when they have requirements such as:
|
||||
|
||||
* To provide a quick and efficient way of moving content from a document to another.
|
||||
* To allow reusing the document history as a template for new documents.
|
||||
* To allow linking of documents that need to be applied to each other.
|
||||
|
||||
The Copy Document pattern involves the following entities:
|
||||
|
||||
1. Source document tables for document header and line. For example,Sales Header/Line.
|
||||
2. Destination document tables for document header and line.
|
||||
|
||||
**Note:**The source document header/line and destination document header/line tables do not need to be the same. For example, you can copy a Sales Shipment Header/Lines into a Sales Header/Lines.
|
||||
3. Copy Document engine: COD6620, Copy Document Mgt.
|
||||
4. Copy Document report for a specific document type. The report requires the following parameters:
|
||||
* Source Document Type
|
||||
* Source Document No.
|
||||
* Include Header (optional)
|
||||
* Recalculate Lines (optional)
|
||||
Example: REP901, Copy Assembly Document
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## Usage Sequence
|
||||
|
||||
**Precondition**: The user creates a new destination document Header, filling up the required information.
|
||||
|
||||
**Step 1**: The user runs the Copy Document report (element no. 4), filling up the parameters:
|
||||
|
||||
* Source Document Type
|
||||
* Source Document No.
|
||||
* Include Header and/or Recalculate Lines (not all Copy Document reports have these).
|
||||
|
||||
**Step 2**: The report copies the information in the source tables (Header and Line) into the destination tables (Header and Line).
|
||||
|
||||
**Post processing**: The user performs additional editing of the destination document.
|
||||
|
||||
The sequence flow of the pattern is described in the following diagram.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
Example: Copy Sales Document for Credit Memos.
|
||||
|
||||
In the standard version of Microsoft Dynamics NAV, the Copy Document functionality is implemented in the Sales Credit Memo window as shown in the following section.
|
||||
|
||||
\*\*\*
|
||||
|
||||
**Precondition**: The user enters data in PAGE44, Sales Credit Memo.
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
**Step 1**: The user runs REP292, Copy Sales Document from the Sales Credit Memo window, populating the required parameters. The Include Header and Recalculate Lines fields are selected.
|
||||
|
||||
[![ ][image3]][anchor3]
|
||||
|
||||
**Step 2**: The Sales Credit Memo window is populated with information from the source sales document.
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
|
||||
**Post processing**: The user can now do additional editing of the sales credit memo.
|
||||
|
||||
# NAV Implementations
|
||||
|
||||
1. Copy Sales Document (REP292)
|
||||
2. Copy Purchase Document (REP492)
|
||||
3. Copy Service Document (REP5979)
|
||||
4. Copy Assembly Document (REP901)
|
||||
|
||||
[watch?v=aTiwroXwW0&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=17][anchor5]
|
||||
|
||||
|
||||
|
||||
[anchor0]: /cfs-file/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image002.gif
|
||||
[anchor1]: /cfs-file/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image004.gif
|
||||
[anchor2]: clip_5F00_image006.jpg
|
||||
[anchor3]: clip_5F00_image008.jpg
|
||||
[anchor4]: clip_5F00_image010.jpg
|
||||
[anchor5]: https://www.youtube.com/watch?v=aTiwroXwW_0&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=17
|
||||
|
||||
|
||||
[image0]: /resized-image/__size/750x0/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image002.gif
|
||||
[image1]: /resized-image/__size/750x0/__key/communityserver-wikis-components-files/00-00-00-00-42/clip_5F00_image004.gif
|
||||
[image2]: clip_5F00_image006.jpg
|
||||
[image3]: clip_5F00_image008.jpg
|
||||
[image4]: clip_5F00_image010.jpg
|
||||
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
|
@ -0,0 +1,231 @@
|
|||
+++
|
||||
title = "Create Data from Templates"
|
||||
weight = 400
|
||||
+++
|
||||
_by Nikola Kukrika at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
For many records, such as Items, Customers, and Vendors, users have to enter the same sets of data again and again. This is tedious, error-prone (users forget to enter a field or they choose the wrong group), and difficult to learn for some users.
|
||||
|
||||
We can group sets of data as templates to speed up and simplify the process of entering data in Microsoft Dynamics NAV. For example, the process of creating a new customer could be simplified so that users only have to enter information that is specific for every individual customer, e.g. Name and Address/Contact.
|
||||
|
||||
## Description
|
||||
|
||||
This pattern solves the problem of creating new records based on their type. You should use it whenever there is a large set of data that could be grouped in a meaningful way.
|
||||
|
||||
In Microsoft Dynamics NAV 2013 R2, we have extended the Configuration Templates feature so that templates can be used in different languages than the language they were created in. We have also added the ability to set related templates so that related records can be inserted, such as dimensions for customers, items, and vendors.
|
||||
|
||||
The pattern consists of two parts:
|
||||
|
||||
1\. Using templates to create new records or applying templates to existing records
|
||||
|
||||
2\. Defining and updating existing templates
|
||||
|
||||
## Usage
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
Using the patterns involves three steps.
|
||||
|
||||
1) As a first step, we must insert a record. This can be done either through C/AL code or by letting the user create a record using the **New** action.
|
||||
|
||||
2) After the record is created, we must apply the template. This is done by using the **UpdateRecord** function in the **Config. Template Management **codeunit (8612).
|
||||
|
||||
**Config. Template Lines** records reference one **Config. Template Header** record (lines pattern). The lines can be of type:
|
||||
|
||||
* **Field** - Stores a field value that will be applied to the record
|
||||
* **Related** Template -- References a Config. Template Header record for a related template.
|
||||
|
||||
The **UpdateRecord** function applies values to the record one line at the time. One of the requirements was to be possible to use configuration templates in different language/regional settings than the template was created in.
|
||||
|
||||
To support this scenario, when applying the**Config. Template Line** record, **GLOBALLANGUAGE** is set to the language ID of the field. This is important because the default value is stored as text, so we need to use the same formatting that NAV was running on when the template was created. Otherwise, data types, such as Boolean, Date, etc., will raise validation errors.
|
||||
|
||||
Any updates to a **Config. Template Line** record will automatically update the language ID to the current one. Since lines are applied one by one, it is supported to have lines with different language IDs belonging to the same template.
|
||||
|
||||
3) After we have applied the template to the record, we can insert related templates. For example, when you insert an item, you may want to insert dimensions as well. You must implement the logic to apply or then modify the related templates, since this depends on the logic and the relationship between the records. Lines with **Type = Related Template** are used to reference related templates.
|
||||
|
||||
Code example (Insert a record, apply a template, and insert the related templates):
|
||||
|
||||
**// First insert a record Customer.INSERT(TRUE);**
|
||||
|
||||
**// Apply a template RecRef.GETTABLE(Customer);**
|
||||
|
||||
ConfigTemplateMgt.UpdateRecord(ConfigTemplateHeader,RecRef);
|
||||
|
||||
RecRef.SETTABLE(Customer);
|
||||
|
||||
**// Insert Dimensions -- related templates**
|
||||
|
||||
MiniDimensionsTemplate.InsertDimensionsFromTemplates(ConfigTemplateHeader,Customer."No.",DATABASE::Customer);
|
||||
|
||||
Code to insert related templates (dimensions):
|
||||
|
||||
**FUNCTION InsertDimensionsFromTemplates(ConfigTemplateHeader : Record "Config. Template Header";MasterRecordNo : Code\[20\];TableID : Integer)**
|
||||
|
||||
**// There are multiple records (multiple dimensions per master record)**
|
||||
|
||||
**// We have to set filter******
|
||||
|
||||
ConfigTemplateLine.SETRANGE(Type,ConfigTemplateLine.Type::"Related Template");****
|
||||
|
||||
ConfigTemplateLine.SETRANGE("Data Template Code",ConfigTemplateHeader.Code);****
|
||||
|
||||
****
|
||||
|
||||
IF ConfigTemplateLine.FINDSET THEN****
|
||||
|
||||
REPEAT****
|
||||
|
||||
ConfigTemplateHeader.GET(ConfigTemplateLine."Template Code");
|
||||
|
||||
**// Ensure that the table where the template belongs to is Dimensions**
|
||||
|
||||
**// We could have other related templates******
|
||||
|
||||
IF ConfigTemplateHeader."Table ID" = DATABASE::"Default Dimension" THEN****
|
||||
|
||||
InsertDimensionFromTemplate(ConfigTemplateHeader,MasterRecordNo,TableID);****
|
||||
|
||||
UNTIL ConfigTemplateLine.NEXT = 0;****
|
||||
|
||||
****
|
||||
|
||||
**// Create a new Dimensions Record and link it to the Master Record******
|
||||
|
||||
**FUNCTION InsertDimensionFromTemplate(ConfigTemplateHeader : Record "Config. Template Header";MasterRecordNo : Code\[20\];TableID : Integer)**
|
||||
|
||||
DefaultDimension.INIT;
|
||||
|
||||
DefaultDimension."No." := MasterRecordNo;****
|
||||
|
||||
DefaultDimension."Table ID" := TableID;****
|
||||
|
||||
DefaultDimension."Dimension Code" := GetDefaultDimensionCode(ConfigTemplateHeader);****
|
||||
|
||||
DefaultDimension.INSERT;****
|
||||
|
||||
****
|
||||
|
||||
RecRef.GETTABLE(DefaultDimension);****
|
||||
|
||||
ConfigTemplateMgt.UpdateRecord(ConfigTemplateHeader,RecRef);****
|
||||
|
||||
RecRef.SETTABLE(DefaultDimension);
|
||||
|
||||
**To surface the action in the product, you have three options:**
|
||||
|
||||
1. **Recommended** - Implement a separate action called **New from Template**.
|
||||
2. **Optional** - Implement the apply template function on the document itself. This is especially good in scenarios where users are allowed to change the template.
|
||||
3. **Alternative** - Remove the new action by configuration or set Insert Allowed to FALSE on the list (this will block the creation of new records from the lookup). Implement an application action named **New** and tie it to your code.
|
||||
|
||||
**Note: ** In Microsoft Dynamics C5 2014, we chose to remove the **New** action with configuration since we wanted to promote the functionality and avoid the confusion in having too many options. However this might be difficult to maintain with a larger set of pages.
|
||||
|
||||
**To view or edit templates, you have two options:**
|
||||
|
||||
1. Use the **Config. Template List** table (8620) and the **Config. Template Header Card **table (8618).
|
||||
|
||||
This is a generic solution that is not very usable and is error-prone (no lookups, checks for length, table relation checks, etc.) The default value is a text field of 250 characters, which might be much more than the field length, and may lead to validation errors when used. Users will most likely not be able to use this page.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
2\. Implement custom pages resembling the document.
|
||||
|
||||
This is optional if you want to enable the users to create and modify templates. In C5 2014, we created temporary tables with the same fields as the main record. Based on this temporary record, we built a page that resembles a document.
|
||||
|
||||
Example of the **Customer Template** page:
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
The goals of this solution were:
|
||||
|
||||
* To make the setup page resemble a document page so that it is easy to use with basic validation and lookups.
|
||||
* To have only one place to store templates and maintain only one business logic for applying them, namely in the **Configuration Template Header** table.
|
||||
* To avoid any lateral effects of doing validation on the temporary master record. Doing validation on fields, even though the record itself is temporary, could permanently modify other data in the database. For example, if you insert a new record in the **Customer** table, even in a temporary table, a Contact record is created, which will not be temporary.
|
||||
* Testability: It is easy to test through RecordRef that the template table matches the main table. We can compare field lengths, data types, table relations, etc. The test is able to detect that they are out of sync, so it is easy to prevent errors.
|
||||
|
||||
One example in the product is the **Mini Customer Template **table (1300).
|
||||
|
||||
The table itself contains very little code. OnModify, OnInsert, and OnDelete triggers update the **Configuration Header** and **Configuration Lines** tables. The following functions in the **Config. Template Management **codeunit (8612), are used for this:
|
||||
|
||||
* ConfigTemplateManagement.CreateConfigTemplateAndLines
|
||||
* ConfigTemplateManagement.UpdateConfigTemplateAndLines
|
||||
* ConfigTemplateManagement.DeleteRelatedTemplates
|
||||
|
||||
The CreateFieldRefArray function is used as an interface function on all the temporary template tables. It builds data to be read/written to the configuration templates.
|
||||
|
||||
To further enhance the usability, we have provided the following additional functionality:
|
||||
|
||||
* Create a template from the existing record: The user opens an existing record and creates a template from that record. All the fields that are defined in the CreateFieldRefArray function are used to create the new template.
|
||||
* Templates list: This page is used by users to select templates or create new ones. Depending on which templates they are working on, we show different template cards.
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
In C5 2014, this is the workflow:
|
||||
|
||||
The user opens the **Customers List** window and selects **New**
|
||||
|
||||
**[![ ][image3]][anchor3]**
|
||||
|
||||
**[][anchor3]**From this page, the user can view the template, edit it, or create a new one. Selecting a template will populate the customer card and open a new record. From the existing record, the user has options to save as a template or opening a list of templates to maintain available templates. Selecting a template will populate the customer card and open a new record. From the existing record, the user has options to save as a template or opening a list of templates to maintain available templates.
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
|
||||
From the **Customer Card Template **window, we can invoke the **Dimensions** action, through which we can define the dimensions that will be inserted together with the template:
|
||||
|
||||
[![ ][image5]][anchor5]
|
||||
|
||||
## NAV Usages
|
||||
|
||||
This pattern is used in Microsoft Dynamics C5 2014 in the following objects:
|
||||
|
||||
* Temporary template tables:
|
||||
* **Mini Customer Template **table (1300)
|
||||
* **Mini Item Template **table (1301)
|
||||
* **Mini Dimensions Template** table(1302)
|
||||
* **Mini Vendor Template** table (1303)
|
||||
|
||||
* Pages to define templates:
|
||||
* **Mini Customer Template Card** page (1341)
|
||||
* **Mini Item Template Card **page (,1342)
|
||||
* **Mini Dimensions Template List** page (1343)
|
||||
* **Mini Vendor Template Card** page (1344)
|
||||
|
||||
* Pages that use the templates:
|
||||
* **Mini Customer List** page (1301)
|
||||
* **Mini Item List** page ( 1303)
|
||||
* **Mini Vendor List** page (1331)
|
||||
|
||||
In the standard version of Microsoft Dynamics NAV, we use the **Apply Template** action on the following pages:
|
||||
|
||||
* **Customer Card** page (21)
|
||||
* **Vendor Card** page (26)
|
||||
* **Item Card** page (30)
|
||||
* **Resource Card** page (, 76)
|
||||
* Other similar cards.
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
Implement the solution in the standard version of Microsoft Dynamics NAV and extend the Apply Template functionality to insert dimensions.
|
||||
|
||||
It is possible that users end up with a large number of templates if they need many different data combinations. An improvement could be to split templates into smaller groups, grouping only part of the fields that are related, and then apply only these.
|
||||
|
||||
[watch?v=F0CTvoyKSmI&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=20][anchor6]
|
||||
|
||||
|
||||
|
||||
[anchor0]: 4118.Picture1.png
|
||||
[anchor1]: 2816.Picture3.png
|
||||
[anchor2]: 7271.Picture4.png
|
||||
[anchor3]: 4341.Picture4.png
|
||||
[anchor4]: 3482.Picture-5.png
|
||||
[anchor5]: 2134.Picture6.png
|
||||
[anchor6]: https://www.youtube.com/watch?v=F0CTvoyKSmI&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=20
|
||||
|
||||
|
||||
[image0]: 4118.Picture1.png
|
||||
[image1]: 2816.Picture3.png
|
||||
[image2]: 7271.Picture4.png
|
||||
[image3]: 4341.Picture4.png
|
||||
[image4]: 3482.Picture-5.png
|
||||
[image5]: 2134.Picture6.png
|
||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
|
@ -0,0 +1,298 @@
|
|||
+++
|
||||
title = "Create URLs to NAV Clients"
|
||||
weight = 410
|
||||
+++
|
||||
_By Mike Borg Cardona and Bogdana Botez at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
This article illustrates NAV platform functionality to be used by C/AL developers.
|
||||
|
||||
The URL builder function, GETURL, is released in Microsoft Dynamics NAV 2013 R2 to reduce coding time for developers who need to create various URL strings to run application objects in either the win client, the web client, or on web services. In addition, the GETURL function makes multitenancy features more transparent to C/AL developers.
|
||||
|
||||
## Description
|
||||
|
||||
Ever had to construct win client URLs like the one below?
|
||||
|
||||
dynamicsnav://myserver:7046/myInstance/myCompany/runpage?page=26
|
||||
|
||||
Today, Microsoft Dynamics NAV also provides a web client. This means that you must update your code to construct web client URLs too. What about multitenancy? The URL Builder should know if it is running in a multitenant setup and it should know how to choose the right tenant. What about maintaining this code?
|
||||
|
||||
The good news is that GETURL has been introduced to handle all URL building for you.
|
||||
|
||||
GETURL automatically handles:
|
||||
|
||||
* Multitenancy
|
||||
* Correct URL format for each client
|
||||
* Publicly accessible hostnames.
|
||||
|
||||
## Usage
|
||||
|
||||
The format is:
|
||||
|
||||
\[String :=\] GETURL(ClientType\[, Company\]\[, Object Type\]\[, Object Id\]\[, Record\])
|
||||
|
||||
Where:
|
||||
|
||||
* **Client Type** can be: Current, Default, Windows, Web, SOAP, or OData. This enables a range of scenarios for the C/AL developer, such as moving to the web client without changing code to decide where the URL should point to. This is done either by setting Client Type to Current, and just ensuring that web is used to invoke the link creation, or by setting Client Type to Default and changing its value to Web when it is ready to move to the web platform.
|
||||
* **Object Type** and **Object ID** define the type of the application object to run (Table, Page, Report, Codeunit, Query, or XMLport) and its ID.
|
||||
* **Record** specifies the actual data to run the URL on, such as:
|
||||
|
||||
Vendor.GET("Account No.");
|
||||
|
||||
GETURL(CLIENTTYPE:WEB,COMPANYNAME, OBJECTTYPE::Page,27,Vendor)
|
||||
|
||||
**Note**: It is currently not possible to set filters on the record that you sent as a last parameter to the GETURL function. However, it is possible to write your own code to compute and append the filter string to the URL that is created by the GETURL function.
|
||||
|
||||
The server name and instance are extracted automatically by GETURL and do not need to be specified by the C/AL developer. Furthermore, the multitenancy setup is transparent to the C/AL developer. No multitenancy parameters are specified when you call GETURL, because the function knows from the server setup if it is running in a multitenant environment and if so, it will add a string like "&tenant=MyTenant" to the URL.
|
||||
|
||||
## When to Use
|
||||
|
||||
The GETURL function can generally be used every time a URL must be created. The following are some scenarios where the function is particularly useful.
|
||||
|
||||
* Document approvals. For more information, see the "NAV Usage Example" section.
|
||||
* Reports containing drill-down links. (Beware of the resource cost of adding a new URL element to the Report dataset.)
|
||||
* When planning to write code for, or migrate to, various display targets (Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV web client, Microsoft Dynamics NAV web services) without having to explicitly specify which client to use.
|
||||
|
||||
## Examples of Usage
|
||||
|
||||
The following are examples of calls to GETURL and their corresponding return value:
|
||||
|
||||
**Command**
|
||||
|
||||
**URL**
|
||||
|
||||
GETURL(CLIENTTYPE::Win)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71//
|
||||
|
||||
GETURL(CLIENTTYPE::Web)
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient
|
||||
|
||||
GETURL(CLIENTTYPE::OData)
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP)
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/Services
|
||||
|
||||
GETURL(CLIENTTYPE::Current) ie. When running this code on a Win client session
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71//
|
||||
|
||||
GETURL(CLIENTTYPE::Default) ie. When the Server config key DefaultClient is set to Windows
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71//
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,'')
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71//
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,'NONEXISTING Corp')
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/NONEXISTING Corp/
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME)
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS
|
||||
|
||||
GETURL(CLIENTTYPE::Web,'')
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient
|
||||
|
||||
GETURL(CLIENTTYPE::Web,'NONEXISTING Corp')
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=NONEXISTING Corp
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME)
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')
|
||||
|
||||
GETURL(CLIENTTYPE::OData,'')
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData
|
||||
|
||||
GETURL(CLIENTTYPE::OData,'NONEXISTING Corp')
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData/Company('NONEXISTING Corp')
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME)
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Services
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,'')
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/Services
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,'NONEXISTING Corp')
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/NONEXISTING Corp/Services
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Table,27)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runtable?table=27
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,27)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=27
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Report,6)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runreport?report=6
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Codeunit,5065)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runcodeunit?codeunit=5065
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Query,9150)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runquery?query=9150
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::XmlPort,5150)
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runxmlport?xmlport=5150
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27) ie. When the Web Service is published
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/PAG27Vendors
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Query,9150) ie. When the Web Service is published
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/QUE9150MyCustomers
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27)Â ie. When the Web Service is published
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Page/PAG27Vendors
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Codeunit,5065) ie. When the Web Service is published
|
||||
|
||||
http://MyServer:7047/DynamicsNAV71/WS/CRONUS/Codeunit/COD5065EmailLogging
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,27,record) List Page
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=27&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw
|
||||
|
||||
GETURL(CLIENTTYPE::Windows,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page
|
||||
|
||||
dynamicsnav://MyServer:7046/DynamicsNAV71/CRONUS/runpage?page=26&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,27,record) List Page
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=27&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,26,record) Card Page
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=26&bookmark=23;FwAAAAJ7/0kAQwAxADAAMwAw
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27,record)
|
||||
|
||||
http://MyServer:7048/DynamicsNAV71/OData/Company('CRONUS')/PAG27Vendors('IC1030')
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Page,27)
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&page=27
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Report,6)
|
||||
|
||||
https://navwebsrvr:443/DynamicsNAV71\_Instance1/Webclient?company=CRONUS&report=6
|
||||
|
||||
If the GETURL function is called with invalid parameters, it will return an empty string. In that case, you can find the related error text by calling the GETLASTERRORTEXT function.
|
||||
|
||||
**Function Call**
|
||||
|
||||
**Error Message**
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Table,27)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Codeunit,5065)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::Query,9150)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::Web,COMPANYNAME,OBJECTTYPE::XmlPort,5150)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Table,27)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Page,27)
|
||||
|
||||
The Page object, 27, that is specified for the GetUrl function has not been published in the Web Services table.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Report,6)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Codeunit,5065)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::Query,9150)
|
||||
|
||||
The Query object, 9150, that is specified for the GetUrl function has not been published in the Web Services table.
|
||||
|
||||
GETURL(CLIENTTYPE::OData,COMPANYNAME,OBJECTTYPE::XmlPort,5150)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Table,27)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27)
|
||||
|
||||
The Page object, 27, that is specified for the GetUrl function has not been published in the Web Services table.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Report,6)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Codeunit,5065)
|
||||
|
||||
The Codeunit object, 5065, that is specified for the GetUrl function has not been published in the Web Services table.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Query,9150)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::XmlPort,5150)
|
||||
|
||||
The specified object type parameter for the GetUrl function is not valid.
|
||||
|
||||
GETURL(CLIENTTYPE::SOAP,COMPANYNAME,OBJECTTYPE::Page,27,record)
|
||||
|
||||
You cannot specify a record parameter for the GetUrl function when the object type is SOAP
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
The following example shows how to use the GETURL function in codeunit 440 to ensure that the notification mail in Document Approvals can link to both the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV web client:
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
This resulting UI looks as follows.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
The first link opens the approval document in the Microsoft Dynamics NAV Windows client. The second link (Web view) opens the same document in the Microsoft Dynamics NAV web client.
|
||||
|
||||
|
||||
|
||||
[anchor0]: 1778.url1.jpg
|
||||
[anchor1]: 7802.url2.jpg
|
||||
|
||||
|
||||
[image0]: 1778.url1.jpg
|
||||
[image1]: 7802.url2.jpg
|
||||
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 49 KiB |
205
content/NAVPatterns/1-patterns/creating-custom-charts/index.md
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
+++
|
||||
title = "Creating Custom Charts"
|
||||
weight = 420
|
||||
+++
|
||||
_by Nikola Kukrika at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
The goal of this solution is to enable you to:
|
||||
|
||||
1. Use charts in the web client.
|
||||
2. Create charts with custom functionality.
|
||||
|
||||
## Description
|
||||
|
||||
This pattern enables you to implement a business chart (Specific Chart type) in a way that is maintainable and reusable on other pages. This also enables you to provide specific functionality that is not possible with the Generic Chart type and it enables you to show charts in the web client.
|
||||
|
||||
The Business Chart add-in is a special because it is a combination of .NET and Javascript add-ins depending on the display target. In the web client, it renders a JavaScript control, while in the win client, it renders a .Net control. Because of this behavior, you can expect minor differences in how the chart is presented in the win client versus in the web client. Note that this implementation is specific to NAV platform code, because it is not possible to create add-ins that combines .NET and JavaScript by using a framework API.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
Example of the same chart in the win client:
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
The most obvious differences in chart rendering in the two clients are: Slightly different line heights, slightly different chart height, legends in web-client charts can be used as toggle filters to show/hide groups (this is not possible in the win client).
|
||||
|
||||
### Implementation Overview
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
### Add-in Buffer Table
|
||||
|
||||
This table is used to encapsulate the logic of the Business Chart Add-in. The table handles the following logic:
|
||||
|
||||
* Storing chart values and conversion from .NET to C/AL and vice versa
|
||||
* Handling of captions: We must use C/AL to provide multilanguage text in add-ins. In addition, the multilanguage text must be encapsulated in a single place, because we pass/read the same dataset from/to the add-in.
|
||||
* DrillDown logic
|
||||
* Other helper data related functions, for displaying date, periods, etc.\[Bogdana1\] \[NK2\] \[NK3\]
|
||||
|
||||
**Note:** It is recommended that you reuse the **Business Chart Buffer **table****(485) as a buffer table or extend. It is a generic table which should cover most of the use cases. Implement a new buffer table only if this table does not meet your needs.
|
||||
|
||||
### CardPart page
|
||||
|
||||
The CardPart page hosts the Business Chart add-in and must use the add-in buffer table as a source table.
|
||||
|
||||
On the page, you must implement the following triggers:
|
||||
|
||||
* **AddInReady** -- Executed when the page is done rendering. Used to initialize the add-in.
|
||||
* **DataPointClicked** -- Single-click on an element on the chart.
|
||||
* **DataPointDoubleClicked** -- Double-click on an element on the chart
|
||||
|
||||
The CardPart usually contains a StatusText variable to provide more information about the chart or dataset and a set of actions to control the chart.
|
||||
|
||||
The most commonly used actions are:
|
||||
|
||||
* **Select Chart**, **Previous Chart**, **Next Chart**
|
||||
* **Set Period**, **Work Date**
|
||||
* Actions to filter the data set
|
||||
* **Refresh**
|
||||
* **Chart Information **-- a tooltip with a description of the chart and how data is calculated.
|
||||
|
||||
### Optional: Preserving User Personalization
|
||||
|
||||
One of the most common functionalities is personalization. If the chart can be customized by the user, you should store the settings that the user has entered and apply them the next time the chart is loaded.
|
||||
|
||||
To do this, you need the following:
|
||||
|
||||
* A setup record to store the data. You can use the **Business Chart User Setup** table (487) or create a new setup table if you need to store more information.
|
||||
* A management codeunit to write/apply the settings to the chart and to encapsulate other logic. Since we should not write code on pages, the code for the actions and other logic that does not apply to the setup record****should go in this codeunit.
|
||||
* Setup pages where users can customize how the chart is shown and set different settings.
|
||||
|
||||
The relation between the components is visualized in the following diagram\[
|
||||
|
||||
[![ ][image3]][anchor3]
|
||||
|
||||
### Optional: Show Multiple Charts within a Single CardPart
|
||||
|
||||
This option is useful on a Role Center where you want to show multiple charts using different datasets within a single part. In that case, you need a record to store the last chart selection, the setup records, and code units for separate charts.
|
||||
|
||||
See, for example, the implementation of the **Mini Generic Chart** page (1390), which uses **MiniChartManagment** CodeUnit to manage separate management codeunits for charts and their setup records. The last selected chart is stored in a separate table, **Mini Chart Definition** (1310).
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
|
||||
## Usage
|
||||
|
||||
To implement the pattern, create a new ChartPart and set the source table to **Business Chart Buffer**.
|
||||
|
||||
Add a field named **BusinessChart** and set the ControlAddIn property to Microsoft.Dynamics.Nav.Client.BusinessChart.
|
||||
|
||||
Then implement the AddInReady event. This event is executed when the page is done rendering. Code within this method must call the Update method from the **Business Chart Buffer** table, Update(CurrPage.BusinessChart) to initialize the chart and assign initial values.
|
||||
|
||||
If you need a setup record and codeunit, then it is a good idea to encapsulate this logic within a method.
|
||||
|
||||
### NAV Specific Example 1
|
||||
|
||||
Implementation of the **Finance Performance Chart** page (762)
|
||||
|
||||
**BusinessChart::AddInReady()**
|
||||
|
||||
UpdateChart(Period::" ");
|
||||
|
||||
**LOCAL UpdateChart(Period : ',Next,Previous')**
|
||||
|
||||
MoveAndUpdateChart(Period,0);
|
||||
|
||||
**LOCAL MoveAndUpdateChart(Period : ',Next,Previous';Move : Integer)**
|
||||
|
||||
AccSchedChartManagement.GetSetupRecordset(AccountSchedulesChartSetup,AccountSchedulesChartSetup.Name,Move);
|
||||
|
||||
AccSchedChartManagement.UpdateData(Rec,Period,AccountSchedulesChartSetup);
|
||||
|
||||
Update(CurrPage.BusinessChart);
|
||||
|
||||
StatusText := GetCurrentSelectionText("Period Filter Start Date","Period Filter End Date");
|
||||
|
||||
In the MoveAndUpdateChart method, the AccSchedChartManagement codeunit gets a setup record and updates it if necessary. Then, it initializes the chart with setup data and sets the StatusText to show the period for which data is displayed. The same method is used by the actions to move and update the chart so that there is no code duplication.
|
||||
|
||||
The following code is used to implement **DataPointClicked**
|
||||
|
||||
******BusinessChart::DataPointClicked(point : DotNet "Microsoft.Dynamics.Nav.Client.BusinessChart.BusinessChartDataPoint")**
|
||||
|
||||
SetDrillDownIndexes(point);
|
||||
|
||||
AccSchedChartManagement.DrillDown(Rec,AccountSchedulesChartSetup);
|
||||
|
||||
SetDrillDownindexes is a method from the **Business Chart Buffer** table that maps the DotNet point variable to C/AL data, so it must be used. The next method that you must implement is the action to be performed on Drilldown.
|
||||
|
||||
The **DataPointDoubleClicked **trigger has the same implementation logic as the DataPointClicked trigger.
|
||||
|
||||
### NAV Specific Example 2
|
||||
|
||||
Implementation of chart part 1390 on the **Small Business Role Center** page (9022)
|
||||
|
||||
[![ ][image5]][anchor5]
|
||||
|
||||
This chart part contains data from multiple charts within a single part. The **Status Text** field shows the name of the chart and the current period. Users can browse through the charts with **Next Chart **and**Previous Chart** or use **Select Chart** to choose from a list of available charts.
|
||||
|
||||
[![ ][image6]][anchor6]
|
||||
|
||||
On this dialog, users can choose if a chart should be enabled or disabled. If the chart is not enabled, it will be skipped on the **Previous Chart **and **Next Chart** actions. Charts used by this part use different codeunits and setup records. If the user changes the selected chart, this option will be saved and applied next time role center is opened.
|
||||
|
||||
Users can also change the period length.
|
||||
|
||||
[![ ][image7]][anchor7]
|
||||
|
||||
Choosing the **Chart Information** button opens a short description of the chart.
|
||||
|
||||
[![ ][image8]][anchor8]
|
||||
|
||||
## NAV Usages
|
||||
|
||||
Implementation of multiple charts within a single part:
|
||||
|
||||
* Page 1390, **Mini Generic Chart**
|
||||
|
||||
Charts that use a setup record and select the chart with **Customize Chart Setup** pages:
|
||||
|
||||
* Page 772, **Inventory Performance**
|
||||
* Page 771, **Purchase Performance**
|
||||
* Page 770, **Sales Performance**
|
||||
* Page 762, **Finance Performance**
|
||||
|
||||
Chart that uses the **Business Chart User Setup** table:
|
||||
|
||||
* Page 768, **Aged Acc. Receivable Chart**
|
||||
|
||||
Other implementations:
|
||||
|
||||
* Page 972, **Time Sheet Chart**
|
||||
* Page 869, **Cash Flow Chart**
|
||||
* Page 760, **Trailing Sales Orders Chart**
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
We should consider making a generic table for the last chart that the user has used.
|
||||
|
||||
We should investigate if we could make generic code for selecting periods and other common functionality by using RecordRefs.
|
||||
|
||||
Add-In improvements -- Different ways to visualize the data and to pick colors for categories.
|
||||
|
||||
As a nice-to-have feature, we could implement functionality to cycle through the charts with a timer.
|
||||
|
||||
|
||||
|
||||
[anchor0]: 5153.Picture1.png
|
||||
[anchor1]: 1411.Picture2.png
|
||||
[anchor2]: 1781.Picture5.png
|
||||
[anchor3]: 0246.Picture6.png
|
||||
[anchor4]: 1803.Picture7.png
|
||||
[anchor5]: 1541.Picture7.png
|
||||
[anchor6]: 2553.Picture8.png
|
||||
[anchor7]: 5545.Picture9.png
|
||||
[anchor8]: 5582.Picture10.png
|
||||
|
||||
|
||||
[image0]: 5153.Picture1.png
|
||||
[image1]: 1411.Picture2.png
|
||||
[image2]: 1781.Picture5.png
|
||||
[image3]: 0246.Picture6.png
|
||||
[image4]: 1803.Picture7.png
|
||||
[image5]: 1541.Picture7.png
|
||||
[image6]: 2553.Picture8.png
|
||||
[image7]: 5545.Picture9.png
|
||||
[image8]: 5582.Picture10.png
|
||||
BIN
content/NAVPatterns/1-patterns/cross-session-events/PubSub.png
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
153
content/NAVPatterns/1-patterns/cross-session-events/index.md
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
+++
|
||||
title = "Cross Session Events"
|
||||
weight = 430
|
||||
+++
|
||||
#### _By Nikolai L'Estrange, from TVision Technology Ltd. in the UK__
|
||||
_
|
||||
|
||||
### Abstract
|
||||
|
||||
Track things that happen in other NAV Sessions.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
### Problem
|
||||
|
||||
In Microsoft Dynamics NAV you can fire a function whenever something changes within your session (and from NAV 2016 this is even easier with the new Event model), however there is not an easy way to know what is happening in other sessions. Sometimes you would like to know what has happened since your last read, without reading everything again, e.g. when you need to pass a large dataset to a Control Add-in.
|
||||
|
||||
A common way of handling this with Ledger Tables is to make note of the last record you read, and continuously poll to see if there are any new records. However this is restricted to strictly sequentially entered tables.
|
||||
|
||||
### Solution
|
||||
|
||||
There is a common pattern in many other languages called [Publish-Subscribe][anchor1] (or PubSub) that solves the same issue. We can implement the same pattern in NAV using a Table as a message queue platform and polling this table. We have named this pattern "Cross Session Events" in order to avoid confusion with the standard NAV Events which use the terms Publisher and Subscriber, and to try and describe more accurately when you would need this pattern.
|
||||
|
||||
The pattern has four components:
|
||||
|
||||
* **Publisher(s)**: These push messages to the Message Broker.
|
||||
* **Subscriber Records**: Identifies the Subscriber and store filters to say what messages the Subscriber and interested in receiving.
|
||||
* **Message Broker**: This distributes all messages sent in to all Subscribers that have expressed an interest (i.e. the message is within their filters).
|
||||
* **Message Queue**: To hold the messages for each Subscriber. Generally once these messages are read, they are deleted.
|
||||
|
||||
### Example
|
||||
|
||||
An example of this would be when we have multiple users looking at the same set of data and we want their screens to update in "real time" whenever one of them makes a change, without doing a full refresh. We will use the [Observer pattern][anchor2] to capture the change (act as the Publisher) and then create a Table to hold Subscribers and Filters (Change Observer), a Table to be the Message Queue (Change Notification), and a Codeunit to be the Message Broker and help with the polling (ObserverMgt).
|
||||
|
||||
Below are the table definitions:
|
||||
|
||||
**Change Observer:
|
||||
**"Table ID" Integer "Observable Table"
|
||||
"Server ID" Integer
|
||||
"Session ID" Integer
|
||||
|
||||
**Change Notification:
|
||||
**"Table ID" Integer "Observable Table"
|
||||
"Server ID" Integer
|
||||
"Session ID" Integer
|
||||
"Entry No." Integer AutoIncrement
|
||||
"Type of Change" Option Insert,Modify,Delete,Rename
|
||||
"Record ID" RecordID
|
||||
... (other fields to indicate what has changed)
|
||||
|
||||
|
||||
The Change Observer table identifies the Subscriber using Server ID and Session ID, and then in this example there is only one filter, which is the Table ID we want to listen to any changes. In this case all three fields are in the Primary Key.
|
||||
|
||||
The Change Notification table then has the same three fields plus an Entry No. as its Primary Key, and in this example borrows heavily from the Change Log code to fill in the rest of the message.
|
||||
|
||||
_**Note:** _Other examples of the pattern could have very different fields to identify the Subscriber, Filters and then whatever fields needed for content of the Message.
|
||||
|
||||
Our Message Broker Codeunit will also serve as a central place to create Subscribers (Listen and StopListening functions) and a place to Poll for Messages. Note that the Poll function deletes the Messages as it reads them.
|
||||
|
||||
**Listen(TableID : Integer)**
|
||||
WITH Observer DO BEGIN
|
||||
"Table ID" := TableID;
|
||||
"Server ID" := SERVICEINSTANCEID;
|
||||
"Session ID" := SESSIONID;
|
||||
INSERT(TRUE);
|
||||
COMMIT;
|
||||
END;
|
||||
**StopListening(TableID : Integer)
|
||||
**WITH Observer DO BEGIN
|
||||
RESET;
|
||||
SETRANGE("Server ID",SERVICEINSTANCEID);
|
||||
SETRANGE("Session ID",SESSIONID);
|
||||
SETRANGE("Table ID",TableID);
|
||||
DELETEALL(TRUE);
|
||||
COMMIT;
|
||||
END;
|
||||
**NotifyAll(ChangeNotification : Record "Change Notification")**
|
||||
WITH Observer DO BEGIN
|
||||
RESET;
|
||||
SETRANGE("Table ID",ChangeNotification."Table ID");
|
||||
IF FINDSET THEN REPEAT
|
||||
Notify(Observer,ChangeNotification);
|
||||
UNTIL NEXT = 0;
|
||||
END;
|
||||
**Notify(Observer : Record "Change Observer";ChangeNotification : Record "Change Notification")**
|
||||
WITH ChangeNotification DO BEGIN
|
||||
"Server ID" := Observer."Server ID";
|
||||
"Session ID" := Observer."Session ID";
|
||||
"Entry No." := 0;
|
||||
INSERT;
|
||||
END;
|
||||
**Poll(TableID : Integer;VAR TempChangeNotification : TEMPORARY Record "Change Notification")**
|
||||
WITH ChangeNotification DO BEGIN
|
||||
TempChangeNotification.RESET;
|
||||
TempChangeNotification.DELETEALL;
|
||||
RESET;
|
||||
SETRANGE("Table ID",TableID);
|
||||
SETRANGE("Server ID",SERVICEINSTANCEID);
|
||||
SETRANGE("Session ID",SESSIONID);
|
||||
IF FINDSET THEN REPEAT
|
||||
TempChangeNotification := ChangeNotification;
|
||||
TempChangeNotification.INSERT;
|
||||
MARK(TRUE);
|
||||
UNTIL NEXT = 0;
|
||||
MARKEDONLY(TRUE);
|
||||
DELETEALL;
|
||||
END;
|
||||
|
||||
**__**The final part of this example is an object that calls the functions above. In this example we will use a Page with a PingPong Timer Control to do the polling in (almost) real time. These are the functions on the page:
|
||||
|
||||
**OnQueryClosePage(CloseAction : Action None) : Boolean**
|
||||
ObserverMgt.StopListening(DATABASE::"NAV Whiteboard Booking");
|
||||
**Timer::AddInReady()**
|
||||
IF ObserverMgt.Listen(DATABASE::"NAV Whiteboard Booking") THEN
|
||||
CurrPage.Timer.Ping(1000);
|
||||
**Timer::Pong()**
|
||||
CallUpdate;
|
||||
CurrPage.Timer.Ping(1000);
|
||||
**LOCAL CallUpdate()**
|
||||
ObserverMgt.Poll(DATABASE::"NAV Whiteboard Booking",TempChangeNotification);
|
||||
WITH TempChangeNotification DO BEGIN
|
||||
IF FINDSET THEN REPEAT
|
||||
IF "Type of Change" = "Type of Change"::Delete THEN BEGIN
|
||||
...
|
||||
END ELSE IF RecRef.GET("Record ID") THEN BEGIN
|
||||
...
|
||||
END;
|
||||
UNTIL NEXT = 0;
|
||||
END;
|
||||
|
||||
### Consequences
|
||||
|
||||
The PingPong control is only available on the Windows Client, so if you want to use another client you will need to use another solution to Poll for Messages. Therefore this pattern is not always going to be "real time".
|
||||
|
||||
### Related Topics
|
||||
|
||||
This pattern was originally described in the following blog:
|
||||
|
||||
[https://geeknikolai.wordpress.com/2015/10/30/pubsub-pattern-in-dynamics-nav-2016/][anchor3]
|
||||
|
||||
Below is the Wikipedia link to the PubSub pattern
|
||||
|
||||
[https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe\_pattern][anchor1]
|
||||
|
||||
|
||||
|
||||
[anchor0]: PubSub.png
|
||||
[anchor1]: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
|
||||
[anchor2]: /nav/w/designpatterns/248.observer
|
||||
[anchor3]: https://geeknikolai.wordpress.com/2015/10/30/pubsub-pattern-in-dynamics-nav-2016/
|
||||
|
||||
|
||||
[image0]: PubSub.png
|
||||
|
After Width: | Height: | Size: 14 KiB |
166
content/NAVPatterns/1-patterns/currently-active-record/index.md
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
+++
|
||||
title = "Currently Active Record"
|
||||
weight = 450
|
||||
+++
|
||||
Authors: Henrik Langbak and Kim Ginnerup, Bording Data
|
||||
|
||||
## Abstract
|
||||
|
||||
Date controlled data is expensive to find in the database. This pattern describes how using a view with a sub-select and a linked table object will minimize the returned dataset.
|
||||
A side effect is reduced and simplified code, increased performance and a more scalable solution that is almost independent of the amount of records in the table.
|
||||
|
||||
## Description
|
||||
|
||||
There is no way in NAV to get a set of records from the database, which all have the newest starting date, that is less than or equal to today's date. Having an ending date on the record will help, but it introduces some other problems. In Dynamics NAV this is normally done by reading too many records, either at the SQL Server level or in the middle tier and throw away the ones you do not need. That is a waste of resources:
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>The SQL Server is reading too many records
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>There would be too much data sent over the network.
|
||||
(If the SQL Server and the NAV Service tier are on different machines.)
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>The NAV Service Tier receives and throws away data.
|
||||
|
||||
### Ending Date Problem
|
||||
|
||||
Ending Date may introduce some problems of its own.
|
||||
|
||||
If your design requires to have one and only one active record per key in a dataset, then Ending Date introduces the possibility for overlapping or holes in the timeline.
|
||||
Ending Date creates a dependency between two records. Changing a Starting Date, requires you to update the previous record. Changing the Ending Date requires you to update the next record.
|
||||
If you add a record in between you will have to update both the before and the after record.
|
||||
|
||||
The pattern we describe here will work whether there is an Ending Date or Not.
|
||||
|
||||
The pattern is also relevant for other types than date. The pattern is usable whenever you have dependencies between rows in a table.
|
||||
|
||||
Use the pattern whenever you read a set of data containing a Starting Date and you need to implement a loop to throw away unwanted records. An example could be Codeunit 7000 "Sales Price Calc. Mgt.". In this codeunit there are many loop constructs to find prices and discounts.
|
||||
|
||||
## Usage
|
||||
|
||||
In the following example, we have a fictive table containing: Code, Starting Date and Price. The Primary Key consist of Code, Starting Date. The Database is the Demo Database, and the Company is Cronus.
|
||||
|
||||
< --\[if supportLineBreakNewLine\]--\>[![ ][image0]][anchor0]
|
||||
< --\[endif\]--\>
|
||||
|
||||
### 1\. Create the view
|
||||
|
||||
You will need to create the view before you define the Table Object.
|
||||
You will need to create a view for every company in the database.
|
||||
|
||||
CREATE VIEW \[dbo\].\[CRONUS$PriceView\]
|
||||
AS
|
||||
SELECT \[Code\], \[Starting Date\], \[Price\]
|
||||
FROM dbo.\[CRONUS$Price\] AS A
|
||||
WHERE \[Starting Date\] =
|
||||
(SELECT MAX(\[Starting Date\])
|
||||
FROM dbo.\[CRONUS$Price\] AS B
|
||||
WHERE B.\[Code\] = A.\[Code\] AND
|
||||
B.\[Starting Date\] <= GETDATE())
|
||||
|
||||
Test the view to ensure that you get the correct result. It is much easier to test now than later.
|
||||
|
||||
### 2\. Create the Table object
|
||||
|
||||
Remember to set the link table property before you save it.
|
||||
|
||||
### 3\. Implement the code
|
||||
|
||||
IF PriceView.FINDSET THEN // You have them
|
||||
|
||||
### 4\. Create a deployment codeunit
|
||||
|
||||
Create a SQL Deployment codeunit to manage your views.
|
||||
The codeunit needs to Create or Alter the views for all companies.
|
||||
To see an example of how to talk to SQL Server using .NET see Waldo's blog here:
|
||||
[http://dynamicsuser.net/blogs/waldo/archive/2011/07/19/net-interop-calling-stored-procedures-on-sql-server-example-1.aspx][anchor1]
|
||||
< --\[if supportLineBreakNewLine\]--\>
|
||||
< --\[endif\]--\>
|
||||
|
||||
### 5\. Deployment
|
||||
|
||||
You need to deploy in three steps:
|
||||
|
||||
< --\[if supportLists\]--\>1\. < --\[endif\]--\>Delete the table objects referencing the views
|
||||
|
||||
< --\[if supportLists\]--\>2\. < --\[endif\]--\>Deploy and run the deployment codeunit
|
||||
|
||||
< --\[if supportLists\]--\>3\. < --\[endif\]--\>Deploy the new table objects that reference the views
|
||||
|
||||
### General precaution
|
||||
|
||||
If you later want to change the view, you need to follow these rules:
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>If you add columns, you need to add them to the view first and then add them to the Table Object.
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>If you want to remove columns from the view, you need to delete the Table Object, then change the view and last recreate the Table Object without the new columns.
|
||||
|
||||
### Code example that accomplish the same but without using the pattern
|
||||
|
||||
This following example will give you the same result but the performance will deteriorate as time goes by and you get more and more old data.
|
||||
|
||||
Price.SETCURRENTKEY(Code,"Starting Date");
|
||||
|
||||
Price.SETFILTER("Starting Date",'..%1', TODAY
|
||||
|
||||
IF Price.FINDSET THEN BEGIN
|
||||
REPEAT
|
||||
|
||||
Price.SETRANGE(Code, Price.Code);
|
||||
|
||||
Price.FINDLAST;
|
||||
|
||||
Price.SETRANGE(Code);
|
||||
|
||||
PriceTemp := Price;
|
||||
|
||||
PriceTemp.INSERT;
|
||||
|
||||
UNTIL Price.NEXT = 0;
|
||||
|
||||
END;
|
||||
// PriceTemp will contain the Prices
|
||||
|
||||
### Comparison
|
||||
|
||||
The above NAV example is for a very simple date controlled solution and is provided to give an idea of what the pattern changes seen from a NAV development point of view. But consider the following:
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>The table has a more complex key.
|
||||
This will require setting and clearing more filters
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>You need to read from more than one table.
|
||||
Say you need to apply discount from a separate table.
|
||||
This may give several lines in PriceTemp.
|
||||
|
||||
< --\[if supportLists\]--\>\* < --\[endif\]--\>If the Code field is controlled by a Type field.
|
||||
The Code field reference keys in different tables
|
||||
|
||||
All three examples above can be implemented directly in the view. By using the pattern, it will still only require a single line of NAV code.
|
||||
|
||||
Using the pattern will only issue one SQL call and thereby one trip to the server.
|
||||
The NAV Example will require an unknown number of SQL calls and thereby an unknown number of trips to the server. The number of SQL calls is dependent on the number of distinct Code values.
|
||||
The NAV example will require SQL Server to read all data older than or equal to TODAY, but only return one row per Code. Over time, as old data piles up in the system, the NAV code will perform slower because the SQL statements will be slower.
|
||||
The Pattern makes a scalable solution with a predictable performance. The performance will not deteriorate at the same rate as the NAV code example.
|
||||
|
||||
## NAV Usages
|
||||
|
||||
The pattern does not exist in NAV (yet J). We have used it several times in our code for an Add-On.
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
|
||||
Query Object should be able to handle sub-selects and Unions. A simple solution could be to allow the NAV developer to specify the actual Select statement inside the query Object in clear text. Opening up for writing your own queries and map the projection to the Query-defined fields will make the query Object very versatile and remove the pressure from Microsoft trying to create all the different permutations that a select statement can have. Microsoft and others have all tried to create wizards that can create SQL select statement. They all end up having a clear text option.
|
||||
|
||||
An alternative would be better support for linked table objects, specifically views. The current implementation is very fragile.
|
||||
|
||||
The pattern only supports fetching data for a given date (normally today). This is because you cannot control the where-clause of the sub-select.
|
||||
|
||||
## Related Topics
|
||||
|
||||
The idea of having a linked table object pointing to a view could be a pattern of its own.
|
||||
|
||||
|
||||
|
||||
[anchor0]: 6545.Table.png
|
||||
[anchor1]: http://dynamicsuser.net/blogs/waldo/archive/2011/07/19/net-interop-calling-stored-procedures-on-sql-server-example-1.aspx
|
||||
|
||||
|
||||
[image0]: 6545.Table.png
|
||||
|
After Width: | Height: | Size: 6 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 53 KiB |
284
content/NAVPatterns/1-patterns/data-migration-facade/index.md
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
+++
|
||||
title = "Data Migration Facade"
|
||||
weight = 480
|
||||
+++
|
||||
# **Data Migration Façade**
|
||||
|
||||
_By David Bastide and Soumya Dutta at Microsoft Development Center Copenhagen_
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## **Context:**
|
||||
|
||||
This pattern is describing how you can migrate data using the Data Migration Façade.
|
||||
|
||||
## **Problem:**
|
||||
|
||||
Writing migration code from an external source, such as a product from a competitor, can be time consuming, as you need to tackle the problems of what to migrate, in which order, exception handling... and can result in code that is fragile due to deep dependencies on the NAV data model (high coupling). Any change to the NAV data model can easily break this code. ****
|
||||
|
||||
## **Solution:**
|
||||
|
||||
The idea of the Data Migration Façade is to provide an API that creates and updates master data and related entities (including transactions) without referencing NAV tables.
|
||||
|
||||
Additionally, the framework around the Data Migration Façade provides tools for error handling, and a way to integrate the migration in the Data Migration Overview page (page 1799).
|
||||
|
||||
The façade framework has the following components:
|
||||
|
||||
* Two management codeunits:
|
||||
* **Data Migration Façade** (codeunit 6100): Integrates the extension to the Data Migration Wizard. Starts a migration, or restarts a migration that failed for some records.
|
||||
* **Data Migration Status Facade** (codeunit 6101): Initializes and updates the status of the migration. The status displays in the **Data Migration Overview** page (page 1799).
|
||||
|
||||
* Several master data migration façade codeunits that create and update entities. Each codeunit also contains events that help ensure that data is created in the correct order:
|
||||
* **GL Acc. Data Migration Façade** (codeunit 6110)
|
||||
* **Vendor Data Migration Façade** (codeunit 6111)
|
||||
* **Customer Data Migration Façade** (codeunit 6112)
|
||||
* **Item Data Migration Façade** (codeunit 6113)
|
||||
* If you want to migrate other entities, it is possible to define your own codeunit that will contain your custom code (see 'Usage' below).
|
||||
|
||||
* A page where you can view the status and progress of the migration. It shows one line for each master data entity (item, customer, vendor, general ledger account) that was chosen for migration. You can also stop a migration by choosing the **Stop Migration** action.
|
||||
|
||||
* * **Data Migration Overview** (page 1799)
|
||||
|
||||
## **Usage:**
|
||||
|
||||
There are the following use cases:
|
||||
|
||||
* Migration with staging tables, where data from another product is exported to a file or set of files, and the exported data is then imported to buffer tables, before running the migration logic. In this case, the migration is implemented in your extension codeunits, and it is called through events, one record at a time.
|
||||
|
||||
* Migration without staging tables, for example, when you migrate data by importing it from an external tool such as external APIs and webservices. In this case, the migration is also implemented in your extension codeunits but it will be called through the OnRun procedure. You will be responsible for looping on the records to migrate, and you must migrate all records in this unique OnRun call for a given entity.
|
||||
|
||||
To initialize and start the data migration, you must call the following procedures:
|
||||
|
||||
* **"Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,0,Codeunit::"My extension Item migration codeunit") **
|
||||
This deletes existing status lines for migrating Items for 'My Migration Type', and initializes a new status line with 0 records migrated out of 42000\.
|
||||
|
||||
**"Data Migration Façade".StartMigration('My Migration Type',false) **
|
||||
This starts the migration. False means this is not a retry. A re-try is when you migrate one or more records from the **Show Errors** page, which is described later in this document. Retry = true is only used by the **Show Errors** page and should not be used from extensions.
|
||||
|
||||
### **Usage without staging tables:**
|
||||
|
||||
The overall workflow is:
|
||||
|
||||
1. Integrate your extension in the **Data Migration Wizard** by subscribing to the events exposed by the **Data Migration Façade**.
|
||||
2. From there, initialize the status of the migration so it can be displayed in the Data Migration Overview. When initializing the status lines, you provide the codeunit ID that will be called for each entity: **"Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,0,Codeunit::"My extension Item migration codeunit")**.
|
||||
3. Launch the migration: **"Data Migration Façade".StartMigration('My Migration Type',false).**
|
||||
4. Your migration codeunits are called one at a time (**OnRun**) in the following order:
|
||||
1. G/L accounts (first, because customer/vendor posting groups refer to G/L accounts)
|
||||
2. Customers
|
||||
3. Vendors
|
||||
4. Items (because discounts may refer to customer groups)
|
||||
5. Others
|
||||
5. Loop on all of the records to migrate. You can update the increment of the amount of records migrated: **"Data Migration Status Facade".IncrementStatusLine('My Migration Type',Database::Item,42).**
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
_Figure 1: sequence diagram of the data migration without staging tables _
|
||||
|
||||
The following example shows how to migrate items without staging tables:
|
||||
|
||||
trigger OnRun();
|
||||
var
|
||||
ItemDataMigrationFacade: Codeunit "Item Data Migration Facade";
|
||||
ItemNumber: Integer;
|
||||
ItemJson: Text;
|
||||
begin
|
||||
// loop on items retrieved through a web service for example
|
||||
for ItemNumber := 1 to ExternalWebService.GetItemCount do begin
|
||||
ExternalWebService.GetItem(ItemNumber,ItemJson);
|
||||
// create item using the facade
|
||||
if not ItemDataMigrationFacade.CreateItemIfNeeded(ItemJson.ItemNumber,ItemJson.ItemName1,
|
||||
ItemJson.ItemName2,ConvertItemType(ItemJson.ItemType)) then
|
||||
exit; // item already exists
|
||||
// set some fields using the facade
|
||||
ItemDataMigrationFacade.SetVendorItemNo(ItemJson.VendItemNumber);
|
||||
ItemDataMigrationFacade.SetUnitVolume(ItemJson.Volume);
|
||||
ItemDataMigrationFacade.SetAlternativeItemNo(ItemJson.AltItemNumber);
|
||||
if ItemJson.PrimaryVendor <\> '' then
|
||||
ItemDataMigrationFacade.SetVendorNo(ItemJson.PrimaryVendor);
|
||||
// migrate dependencies
|
||||
MigrateItemUnitOfMeasure(ItemDataMigrationFacade,ItemJson);
|
||||
// modify the item (+run trigger) to save the changes made by setters
|
||||
ItemDataMigrationFacade.ModifyItem(true);
|
||||
// update the status in the migration dashboard
|
||||
DataMigrationStatusFacade.IncrementMigratedRecordCount('My Migration Type',
|
||||
Database::Item,1);
|
||||
end;
|
||||
end;
|
||||
procedure MigrateItemUnitOfMeasure(ItemDataMigrationFacade : Codeunit "Item Data Migration Facade";
|
||||
ItemJson : Text);
|
||||
var
|
||||
MyUnitCodeStagingTable: Record "My Unit Code Staging Table";
|
||||
DataMigrationStatusFacade: Codeunit "Data Migration Status Facade";
|
||||
DescriptionToSet: Text\[10\];
|
||||
UnitCodeJson: Text;
|
||||
begin
|
||||
if ItemJson.UnitCode = '' then
|
||||
// log an error using the Data migration façade
|
||||
DataMigrationStatusFacade.RegisterErrorNoStagingTablesCase(
|
||||
'My Migration Type',Database::Item,'Unit of measure is empty.');
|
||||
if ExternalWebService.GetUnitCode(ItemJson.UnitCode,UnitCodeJson) then
|
||||
DescriptionToSet := UnitCodeJson.Description;
|
||||
ItemDataMigrationFacade.CreateUnitOfMeasureIfNeeded(ItemJson.UnitCode, DescriptionToSet);
|
||||
// set the unit of measure on the item
|
||||
ItemDataMigrationFacade.SetBaseUnitOfMeasure(ItemJson.UnitCode);
|
||||
end;
|
||||
|
||||
|
||||
_Figure 2: Example of Item and Item Unit of Measure migration without staging tables _
|
||||
|
||||
### **Usage with staging tables:**
|
||||
|
||||
The overall workflow is:
|
||||
|
||||
* Integrate your extension in the Data Migration Wizard by subscribing to the events exposed by the **Data Migration Façade**.
|
||||
|
||||
* From there, initialize the status of the migration so it can be displayed in the **Data Migration Overview: "Data Migration Status Façade".InitStatusLine('My Migration Type',Database::Item,42000,Database::"My extension Staging table for items",0)**.
|
||||
* You can either fill the staging tables from the wizard events, or in a subscriber to the event dedicated to filling staging tables (**'OnFillStagingTables'** in codeunit 6100): in this case, the import of data from the files to the staging tables will be done in the background.
|
||||
* Launch the migration: **"Data Migration Façade".StartMigration('My Migration Type',false)**.
|
||||
* Subscribe to the events to migrate entities and their dependencies.
|
||||
* From the event subscribers, call the façade procedures to create entities and set their field values:
|
||||
|
||||
* * **"Item Data Migration Façade".CreateItemIfNeeded('ITEM042','My Item Description';'My Item Description 2';ItemTypeToSet::Inventory)**
|
||||
*
|
||||
**"Item Data Migration Façade".SetBaseUnitOfMeasure('BOX')**
|
||||
*
|
||||
**"Item Data Migration Façade".ModifyItem(true)**
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
_Figure 3: Simplified sequence diagram of the data migration with staging tables _
|
||||
|
||||
Below is a simplified example showing how to create an item:
|
||||
|
||||
\[EventSubscriber(ObjectType::Codeunit, Codeunit::"Item Data Migration Facade", 'OnMigrateItem', '', true, true)\]
|
||||
procedure OnMigrateItem(VAR Sender : Codeunit "Item Data Migration Facade";RecordIdToMigrate : RecordId);
|
||||
var
|
||||
MyItemStagingTable : Record "My Item Staging Table";
|
||||
begin
|
||||
// handle the event if it targets this extension's staging table
|
||||
if RecordIdToMigrate.TableNo <\> Database::"My Item Staging Table" then
|
||||
exit;
|
||||
MyItemStagingTable.Get(RecordIdToMigrate);
|
||||
// create item using the facade
|
||||
if not Sender.CreateItemIfNeeded(MyItemStagingTable.ItemNumber,MyItemStagingTable.ItemName1,
|
||||
MyItemStagingTable.ItemName2,ConvertItemType(MyItemStagingTable.ItemType)) then
|
||||
exit; // item already exists
|
||||
// set some fields using the facade
|
||||
Sender.SetVendorItemNo(MyItemStagingTable.VendItemNumber);
|
||||
Sender.SetUnitVolume(MyItemStagingTable.Volume);
|
||||
Sender.SetAlternativeItemNo(MyItemStagingTable.AltItemNumber);
|
||||
if MyItemStagingTable.PrimaryVendor <\> '' then
|
||||
Sender.SetVendorNo(MyItemStagingTable.PrimaryVendor);
|
||||
// modify the item (+run trigger) to save the changes made by setters
|
||||
Sender.ModifyItem(true);
|
||||
end;
|
||||
|
||||
|
||||
_Figure 4: Example of event subscriber for Item migration _
|
||||
|
||||
__
|
||||
|
||||
Below is another example showing how to use additional events to set fields that reference other tables, here the unit of measure:
|
||||
|
||||
\[EventSubscriber(ObjectType::Codeunit, Codeunit::"Item Data Migration Facade", 'OnMigrateItemUnitOfMeasure', '', true, true)\]
|
||||
procedure OnMigrateItemUnitOfMeasure(VAR Sender : Codeunit "Item Data Migration Facade";RecordIdToMigrate : RecordId);
|
||||
var
|
||||
MyItemStagingTable : Record "My Item Staging Table";
|
||||
MyUnitCodeStagingTable : Record "My Unit Code Staging Table";
|
||||
DescriptionToSet: Text\[10\];
|
||||
begin
|
||||
// handle the event if it targets this extension's staging table
|
||||
if RecordIdToMigrate.TableNo <\> Database::"My Item Staging Table" then
|
||||
exit;
|
||||
MyItemStagingTable.Get(RecordIdToMigrate);
|
||||
if MyItemStagingTable.UnitCode = '' then
|
||||
error('Unit of measure is empty.');
|
||||
MyUnitCodeStagingTable.SetRange(UnitCode,MyItemStagingTable.UnitCode);
|
||||
if MyUnitCodeStagingTable.FindFirst then
|
||||
DescriptionToSet := MyUnitCodeStagingTable.Description;
|
||||
// create the unit of measure through the facade
|
||||
Sender.CreateUnitOfMeasureIfNeeded(MyItemStagingTable.UnitCode, DescriptionToSet);
|
||||
// set the unit of measure on the item
|
||||
Sender.SetBaseUnitOfMeasure(MyItemStagingTable.UnitCode);
|
||||
// modify the item to save the changes made by setter
|
||||
Sender.ModifyItem(false);
|
||||
end;
|
||||
|
||||
_Figure 5: Example of event subscriber for Item Unit of Measure migration _
|
||||
|
||||
### **Combining both approaches:**
|
||||
|
||||
If you want to migrate additional entities, the **Data Migration **framework lets you initialize the migration with entities other than master data. In this case, the **Data Migration Overview** page will show additional lines. Item, vendor, customer, an general ledger accounts are migrated with an event driven approach, and the additional entities are migrated by calling an extension codeunit **OnRun** method.
|
||||
|
||||
## **Error handling with staging tables:**
|
||||
|
||||
The migration starts by calling **RUN** on the façade codeunit. Errors thrown during the call are captured by **GETLASTERRORTEXT** and displayed when you choose the **Show Errors** action on the **Data Migration Overview** page.
|
||||
|
||||
[![ ][image3]][anchor3]
|
||||
|
||||
_Figure 6: List of errors shown when clicking **Show Errors** on the **Data Migration Overview** page _
|
||||
|
||||
__
|
||||
|
||||
The **Edit Record** action opens a view of the staging table, where you can edit fields to fix errors. Figure 4 shows an example of a page for the vendor staging table in a migration from C5\.
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
|
||||
_Figure 7: Edit a staging table record _
|
||||
|
||||
__
|
||||
|
||||
The **Staging Table ID** determines the page to open, so it is important that the page ID is equal to the **Staging Table ID**, at least for the master data staging tables, for example, for**G/L Accounts, Items, Customers** and **Vendor**. You should ensure that pages to edit related entities are linked on this page by means of new actions. For example, Figure 4 uses the **C5 Purchaser** action.
|
||||
|
||||
After you fix the staging table record, you can choose the **Migrate** action to mark the selected records as records to retry, and then run **StartMigration** with the **Retry** flag set to true. This is the only place where the retry flag should be set to true in the **StartMigration** procedure.
|
||||
|
||||
Error handling without staging tables
|
||||
|
||||
When migrating data without staging tables, errors can be registered manually by the extension using **DataMigrationStatusFacade.RegisterErrorNoStagingTablesCase**. Otherwise they can be registered automatically if the codeunits fail when called on their **OnRun** procedure.
|
||||
|
||||
Errors will be displayed in the error list, but you cannot open and edit records because there is no staging table. The Edit action will not be available.
|
||||
|
||||
## **Limitations:**
|
||||
|
||||
* Data migration will fail if there are customers, vendors, items in the database and if these entities are selected for migration. For example, if you choose to migrate items and your company already contains items, you will get an error. This should not be an issue if you migrate your data from another tool to NAV, in which case you will most likely start on a fresh empty company. However, if you just want to import additional items to a company with existing items, then it is not supported by the framework. however, you can still use the different functions provided by the different codeunits (such as **Item Data Migration Facade**) to create the entities without strong coupling on the NAV data model.
|
||||
* **G/L entries** are deleted automatically.
|
||||
|
||||
* There is no automated rollback in case of failure: data that is successfully migrated will be commited, and data that is not successfully migrated with be shown in the errors list. The retry feature (in case of staging tables) then makes it possible for you to retry individual entities or ignore them.
|
||||
|
||||
## **Usages in NAV:**
|
||||
|
||||
The Data Migration Façade is available starting from version 2018\.
|
||||
|
||||
The following Façade codeunits for data migration management are available:
|
||||
|
||||
* COD6100 (**Data Migration Facade**)
|
||||
|
||||
* COD6101 (**Data Migration Status Facade**)
|
||||
|
||||
The following Entity data migration façade codeunits are available:
|
||||
|
||||
* COD6110 (**GL Acc. Data Migration Facade**)
|
||||
* COD6111 (**Vendor Data Migration Facade**)
|
||||
* COD6112 (**Customer Data Migration Facade**)
|
||||
|
||||
* COD6113 (**Item Data Migration Facade**)
|
||||
* COD6114 (**Ex. Rate Data Migration Facade**)
|
||||
|
||||
## **References:**
|
||||
|
||||
Façade pattern on Wikipedia: https://en.wikipedia.org/wiki/Facade\_pattern
|
||||
|
||||
|
||||
|
||||
[anchor0]: 8308.logo.png
|
||||
[anchor1]: NoStagingTableNew2.png
|
||||
[anchor2]: StagingTableNew2.png
|
||||
[anchor3]: errorhandling1.png
|
||||
[anchor4]: errorhandling2.png
|
||||
|
||||
|
||||
[image0]: 8308.logo.png
|
||||
[image1]: NoStagingTableNew2.png
|
||||
[image2]: StagingTableNew2.png
|
||||
[image3]: errorhandling1.png
|
||||
[image4]: errorhandling2.png
|
||||
BIN
content/NAVPatterns/1-patterns/discovery-event/Pic2.jpg
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
content/NAVPatterns/1-patterns/discovery-event/Pic2b.jpg
Normal file
|
After Width: | Height: | Size: 6.8 KiB |
BIN
content/NAVPatterns/1-patterns/discovery-event/Pic3.jpg
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
BIN
content/NAVPatterns/1-patterns/discovery-event/Pic4.jpg
Normal file
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 18 KiB |
85
content/NAVPatterns/1-patterns/discovery-event/index.md
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
+++
|
||||
title = "Discovery Event"
|
||||
weight = 500
|
||||
+++
|
||||
by waldo
|
||||
|
||||
# Abstract
|
||||
|
||||
The "Discovery Event" pattern is a way for a generic functionality, to call out to other functionalities that want to make use of it, by raising an event, so that they have an event to subscribe to. This is usually done to set itself up within the generic app.
|
||||
|
||||
# The problem
|
||||
|
||||
Let's suppose you have a generic piece of functionality, that hooks into lots of places (modules) in your application. To set this up, you might have to hook into all these parts of the application. Well, this pattern turns this setup around: let all the different modules set itself up in the generic app by raising a "discovery event".
|
||||
|
||||
# Usage
|
||||
|
||||
The pattern is most easily described when you look at an example. This example is an actual usage of the pattern within the application, in page **Service Connections.**
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
The goal of this functionality is to:
|
||||
• List all the different connections to external services,
|
||||
• Have a central place to navigate to the corresponding setup of the service.
|
||||
|
||||
The functionality (**Service Connections**) itself, is not aware of the state nor setup nor any context of all the different services in the list. All it does is:
|
||||
• It raises an event as an opportunity for all services within the NAV application to subscribe to,
|
||||
• It has a public function **InsertServiceConnection** that the subscribers can use to register itself at the Service Connection.
|
||||
|
||||
The event **OnRegisterServiceConnection** is raised when the page (1279 - **Service Connections**) is opened.
|
||||
|
||||
One example of a subscription is the SMTP setup. In Codeunit 400 you'll find the subscriber function **HandleSMTPRegisterServiceConnection** which subscribes to this discovery event, and calls the **InsertServiceConnection** to register itself.
|
||||
|
||||
# Description
|
||||
|
||||
The main idea of this pattern is: "Discover the settings, the context, the records, ... which I need for my functionality" or "Discover the configuration for my functionality". In any case, "discover" is the main idea. It's a pattern where using both publishers and subscribers in one application makes a lot of sense.
|
||||
Let's break down to the steps that are needed to implement the pattern.
|
||||
|
||||
## Step 1: Publish the event
|
||||
|
||||
In the below example, I create a table **Module Status** with a published event **OnDiscoverModuleStatuses**.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
You see that I also include the sender. This way, I will be able to access the methods on my table (which I use as a class). Obviously, other patterns can be applied here as well, like the Argument Table pattern.
|
||||
|
||||
## Step 2: Raise the event on the right place
|
||||
|
||||
When you publish an event, it should obviously be raised somewhere in the code as well. In the below example, I want to raise the event simply by a method which I want to call from a page. So I create a global function where I raise the event:
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
## Step 3: Create one or more global functions, so that your subscriber can call into your functionality to configure, set up, or do whatever it needs to do to make itself discoverable
|
||||
|
||||
The generic functionality that I want to call, should be part of the main class - in this case the**Module Discovery** class, or better, the table (**Module Status**). In this table, I create this global function, because I want to make it available for the subscribers:
|
||||
|
||||
[![ ][image3]][anchor3]
|
||||
The business logic doesn't really matter for this pattern. This is obviously dependent on the functionality where you would like to implement the pattern.
|
||||
|
||||
## Step 4: subscribe from the places in the app to this event, use the global function(s)
|
||||
|
||||
This could be anywhere. Any module within your vertical, of within the main application, can subscribe to the event. In the example below, I create the subscriber in Codeunit80, as I was interested in the status of the Sales-module in default NAV.
|
||||
The exact place of the subscriber is up to you. The main message is that it's part of the module that wants to subscribe, and not part of the **Module Status** module in the application.
|
||||
Here is the subscriber (and one small helper function):
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
You see I can use the "sender" as a normal Record-variable. I access the previously created global function to "register" this sales-module.
|
||||
|
||||
# Microsoft Dynamics NAV Versions
|
||||
|
||||
This pattern only works with Microsoft Dynamics **NAV 2016 and up.**
|
||||
|
||||
|
||||
|
||||
[anchor0]: ServiceConnections.jpg
|
||||
[anchor1]: Pic2.jpg
|
||||
[anchor2]: Pic2b.jpg
|
||||
[anchor3]: Pic3.jpg
|
||||
[anchor4]: Pic4.jpg
|
||||
|
||||
|
||||
[image0]: ServiceConnections.jpg
|
||||
[image1]: Pic2.jpg
|
||||
[image2]: Pic2b.jpg
|
||||
[image3]: Pic3.jpg
|
||||
[image4]: Pic4.jpg
|
||||
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 42 KiB |
112
content/NAVPatterns/1-patterns/document/index.md
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
+++
|
||||
title = "Document"
|
||||
weight = 510
|
||||
+++
|
||||
_By Xavier Garonnat, knk Ingénierie (France), xgaronnat@knk.fr_
|
||||
|
||||
## Abstract
|
||||
|
||||
A document structure contains a header and a set of lines. Each line is linked to the header and could have common data with header.
|
||||
|
||||
## Description
|
||||
|
||||
This pattern should be used as a basis to build any document, showing a header and multiple lines in the same page. Basically, a document is at least composed of two tables and three pages, as shown below:
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## Usage
|
||||
|
||||
You should use it any time you have to capture and store a document.
|
||||
|
||||
## Example
|
||||
|
||||
To build this example from scratch, you will need:
|
||||
|
||||
* Two tables, one for the header (called "Document Header"), and one for the document lines (called "Document Line"). Each document will be composed of "1 to N" line(s).
|
||||
* Three pages, one for the header, one for the subpage (lines), and the last for the document list obviously.Table "Document Header"
|
||||
|
||||
**Table "Document Header" **: Is the "header" table of your document (like Sales Header, Purchase Header, Transfer Header ...)
|
||||
|
||||
* Add a field "No." (Code 20): Should be the first field and primary key of your documents, to be driven by Serial No. (See corresponding design pattern)
|
||||
|
||||
For this sample, I just added a "Sell-to Customer No." to this table. Don't forget to manage deletion of lines with trigger OnDelete().
|
||||
|
||||
**Table "Document Line"**: will store the lines of the document
|
||||
|
||||
* Add a field "Document No." (Code 20): Should be the first field and is related to table "Document Header": set TableRelation to your "Document Header" table
|
||||
* Add a field "Line No." (Integer): this field will be populated automatically by the subpage Page (see AutoSplitKey)
|
||||
|
||||
First (Primary) Key must be "Document No.,Line No.". On table properties, set PasteIsValid to No (to avoid copying/pasting lines, will be implemented by "Copy document", another pattern).
|
||||
|
||||
For my sample, I just add a couple of fields: "Item No." and "Quantity" to this table (just copy/paste standard fields from "Sales Line" table and delete trigger code, this will insure that each field will be well designed)
|
||||
|
||||
**Page "Document Subpage"**: will display the lines in the main form, and will be in charge of assigning line number automatically.
|
||||
|
||||
Create the page for table "Document Line" with the wizard by selecting the ListPart template, add all yours fields except the primary key ("Document No." and "Line No.").
|
||||
|
||||
Then edit the properties:
|
||||
|
||||
* Set AutoSplitKey, DelayedInsert and MultipleNewLines to Yes: this combination will make your subpage work as required.
|
||||
* AutoSplitKey is used to set NAV calculate the last field of the key ("Line No.") with proper numbers (10000, 20000...).
|
||||
|
||||
Set caption to "Lines". Save your page, we will use it on the next step.
|
||||
|
||||
**Page "Document"**: will display the document, and the lines with subpage.
|
||||
|
||||
Create the page for "Document Header" Table with the wizard by selecting the Document template:
|
||||
|
||||
* Add a General FastTab
|
||||
* Add all the revelant fields for the user (or at least "No.")
|
||||
* Click Finish to close the wizard
|
||||
|
||||
Then simply add your subpage as new line in the designer, and adjust the property "SubFormPerLink" with "Document No.=FIELD(No.)" to link header and lines :
|
||||
|
||||
**[![ ][image1]][anchor1]**
|
||||
|
||||
**Page "Document List": **Use the Page wizard to create a List page based on the Document table and add fields, FactBox (RecordLinks, Notes...), etc.
|
||||
|
||||
Once created:
|
||||
|
||||
* Set Editable to No on the List
|
||||
* CardPageID to Page "Document" to enable New/Edit/... Pane actions.
|
||||
|
||||
Save our page and add it to the Role Page "Order Processor Role Center" for example.
|
||||
|
||||
Now, observe how "Line No." is calculated on the first line, and when inserting a new line between the first and second one.
|
||||
|
||||
Code sample (copy link to your browser) : https://knk1fr-my.sharepoint.com/personal/xgaronnat\_knk\_fr/\_layouts/15/guestaccess.aspx?guestaccesstoken=hL0P%2fyQ1ZreY5KlSPc%2b8dHrO4zjUkqQbg8DnGSbgd1Y%3d&docid=02b3cb93e1ff1459380891795fb8441fc
|
||||
|
||||
## NAV Usages
|
||||
|
||||
So many: Sales Order, Purchase Order, Transfer Order, Assembly Order...
|
||||
|
||||
For posted document, it's quite similar, but you don't have to setup subpage properties like AutoSplitKey, used for data entry purpose only (and your pages content should be mainly read-only / non editable).
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
* A new property like "AutoSplitStartNumber", enabled if AutoSplitKey=Yes, default value with <10000\>. Allow to change the numbers of created line.
|
||||
* Be able to copy/paste header AND lines or import header and line from an Excel file.
|
||||
|
||||
## When it should not be used
|
||||
|
||||
This pattern is mainly used for Documents, and may not be used directly for Master data or any other table (Setup, Supplemental, etc...).
|
||||
|
||||
## Related Topics
|
||||
|
||||
Use Series No. Pattern for your documents, and Copy Document to implement document duplication.
|
||||
|
||||
## References
|
||||
|
||||
Walkthrough: Creating a Document Page : [http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx][anchor2]
|
||||
[][anchor2][watch?v=S9cRD2D4c0&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=27][anchor3]
|
||||
|
||||
|
||||
|
||||
[anchor0]: 0005.Document-Pattern-UML-Class-Diagram.jpg
|
||||
[anchor1]: 2086.Design-Pattern-Document-SubPage-Properties.png
|
||||
[anchor2]: http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx "http://msdn.microsoft.com/en-us/library/dd338599(v=nav.71).aspx"
|
||||
[anchor3]: https://www.youtube.com/watch?v=S9cRD2D4c_0&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=27
|
||||
|
||||
|
||||
[image0]: 0005.Document-Pattern-UML-Class-Diagram.jpg
|
||||
[image1]: 2086.Design-Pattern-Document-SubPage-Properties.png
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
|
@ -0,0 +1,95 @@
|
|||
+++
|
||||
title = "Easy Update Of Setup Or Supplementary Information"
|
||||
weight = 520
|
||||
+++
|
||||
_by Anders Larsen at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
Users or the administrator must regularly update setup or supplementary information in the day-to-day business, such as setting up a new type of customer. This setup task often arrives when their focus is on registration and execution instead of setup.
|
||||
|
||||
The navigation experience around these extra steps is often quite troublesome and time-consuming. To enable users to easily perform the needed update, a guide often gives the best support.
|
||||
|
||||
To guide users, we can prompt them with a dialog on which they can update the setup or supplementary information instantly and easily, so that they can proceed with the business task without being side-tracked.
|
||||
|
||||
## Usage
|
||||
|
||||
Define two functions in the setup or supplementary table: One for verifying if the needed information is available, and another for exposing the page that contains the fields that the user must update.
|
||||
|
||||
Call the code. For example:
|
||||
|
||||
Local IsXAvailable : Boolean
|
||||
If field X <\> '' then
|
||||
Exit(True)
|
||||
Exit(false)
|
||||
|
||||
VerifyAndSetX
|
||||
If IsXAvailable then
|
||||
Exit;
|
||||
If Confirm('Field X is missing a value. Do you want to update it now?') then
|
||||
Open the card page in edit mode
|
||||
|
||||
If not IsXAvailable then
|
||||
Error(Field X is missing a value. Please correct it.)
|
||||
|
||||
The calling code
|
||||
|
||||
..
|
||||
|
||||
SetupTable.VerifyAndSetX
|
||||
|
||||
..
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
****
|
||||
|
||||
In the **Sales & Receivables Setup** table (311) for the DK version, the following procedures have been added:
|
||||
|
||||
Local Procedure IsOIOUBLPathAvailable(...)
|
||||
|
||||
Procedure VerifyAndSetOIOUBLPath(...)
|
||||
|
||||
The code in the **Sales & Receivables Setup** table can now be called directly from the related processing codeunit, such as the **Sales-Post + Print** codeunit (82).
|
||||
|
||||
Were the code is called:
|
||||
|
||||
IF ("EAN No." <\> '') THEN
|
||||
|
||||
SalesSetup.VerifyAndSetOIOUBLPathSetup(SalesHeader."Document Type");
|
||||
|
||||
If the setup is not updated properly, the user is prompted to update it as follows.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
Choosing **Yes** opens the related setup page.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
## NAV Usages
|
||||
|
||||
* Report 206, **Sales invoice**
|
||||
* Table 79, **Company Information**
|
||||
* In OIOUBL fields (DK version) during posting/printing of a sales invoice.
|
||||
|
||||
## Ideas for Improvement
|
||||
|
||||
Make a more generic platform implementation that launches the corresponding card page for Rec on Rec.testfield with an asterisk mark for the field that needs a proper value.
|
||||
|
||||
## Related Topics
|
||||
|
||||
The anti-pattern is to do a testfield on a field that is not in the table that you are currently updating.
|
||||
|
||||
The test field message can often be confusing because the pages are often named differently than the tables, which can lead to misunderstanding and context-switching.
|
||||
|
||||
[watch?v=oeASJN zqTo&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=18][anchor2]
|
||||
|
||||
|
||||
|
||||
[anchor0]: 0654.easy-update-1.png
|
||||
[anchor1]: 4024.easy-update-2.png
|
||||
[anchor2]: https://www.youtube.com/watch?v=oeASJN-zqTo&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=18
|
||||
|
||||
|
||||
[image0]: 0654.easy-update-1.png
|
||||
[image1]: 4024.easy-update-2.png
|
||||
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 89 KiB |
103
content/NAVPatterns/1-patterns/error-message-processing/index.md
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
+++
|
||||
title = "Error Message Processing"
|
||||
weight = 550
|
||||
+++
|
||||
_By Jesper Schulz at Microsoft Development Center Copenhagen_
|
||||
|
||||
Note: This pattern describes new functionality which makes it possible to generalize the [Journal Error Processing][anchor0] pattern.
|
||||
|
||||
## Abstract
|
||||
|
||||
Missing, invalid or incomplete data is a common issue during data processing in NAV. This article describes how to collect all error messages during processing using the error message component and present them to the user in a unified way, which enables the user to correct the errors efficiently. By leveraging the integrated error message logging functions, you can log a message with a single line of code and present it to the user with another one-liner.
|
||||
|
||||
## Description
|
||||
|
||||
This article describes how to use the Error Message component in NAV, which in short gives you the possibility to:
|
||||
|
||||
1\. Link an error mesesage to the page which enables you to resolve the problem.
|
||||
2\. Assemble all error messages in one central view instead of having to encounter them one by one.
|
||||
|
||||
Validating data is a common task during data processing in NAV. Unfortunately, validation is often done using NAV's integrated ERROR and TESTFIELD functions, which halt execution of the process. The user will then have to locate the invalid / missing data, correct it and reinitiate the process, possibly running into the next error, making the cycle repeat itself. This can be a very tedious, time-consuming and frustrating process. The error message component aims at improving this experience by providing a lightweight framework for error message logging and this article will explain how to leverage this functionality in your code. By doing so, all error messages are gathered during (pre-)processing and are finally presented to the user. The user then has the possibility to click on the error message, which will open the record where the invalid / missing data is located, thereby enabling the user to correct all mistakes efficiently, from one central place and in one go.
|
||||
|
||||
The example below comes from a Mexican localization, where the user has to export financial balances and transactions into an XML file for government audit purposes. In order to generate valid files, some mandatory data needs to be entered in the system. By leveraging the error message component, the user will be presented with the following page, if missing or invalid data was discovered:
|
||||
|
||||
[![ ][image0]][anchor1]
|
||||
|
||||
By clicking on the error message, the user will be presented with the entity, where the invalid / missing data should be corrected / added. This is done by applying the related pattern [Easy Update of Setup or Supplementary Information][anchor2].
|
||||
|
||||
[![ ][image1]][anchor3]
|
||||
|
||||
## Usage
|
||||
|
||||
In the processing function, define a temporary record of type "Error Message". Use the functions on that record to populate the record with error message, a few of them being:
|
||||
|
||||
* **LogIfEmpty******
|
||||
* **LogIfLengthExceeded******
|
||||
* **LogIfInvalidCharacters******
|
||||
* **LogIfOutsideRange******
|
||||
* **LogIfGreaterThan******
|
||||
* **LogIfEqualTo******
|
||||
* **LogMessage******
|
||||
|
||||
The following parameters must be provided to these functions:
|
||||
|
||||
* **Record:** The record which you want to check
|
||||
* **Field Number:** The field number of the field you want to verify the value of
|
||||
* **Condition:** The condition the field must meet (e.g. length, range, valid characters)
|
||||
* **Message Type:** The type of message, which can be Error, Warning or Message
|
||||
|
||||
When the processing is complete, you can check if any error messages of type "Error" were logged by calling the **HasErrors** function and you can show the list or error messages by calling the **ShowErrorMessages** function. You can also integrate the error messages list as a FactBox, but that is not part of this example.
|
||||
|
||||
## NAV Specific Example
|
||||
|
||||
The code below is an example of how the error message component was used in one part of the before mentioned Mexican feature. This code iterates over all G/L Accounts and pipes information out into an XML file. While doing so, it is validated that all mandatory fields have values and meet certain conditions. And only if that is the case, is the XML document actually exported. Also notice, that an error message is logged, in case no G/L Accounts are found given the provided filters. That way, the user can be guided to setup the system correctly.
|
||||
|
||||
PROCEDURE ExportChartOfAccounts@1(Year@1000 : Integer;Month@1001 : Integer);
|
||||
VAR
|
||||
**TempErrorMessage@1003 : TEMPORARY Record 700;
|
||||
**BEGIN
|
||||
**TempErrorMessage.ClearLog;** // only necessary if variable is global
|
||||
...
|
||||
CreateXMLHeader(Document,RootNode,CatalogoNodeTxt,Namespace,Year,Month,'1.1');
|
||||
IF GLAccount.FINDSET THEN BEGIN
|
||||
REPEAT
|
||||
**TempErrorMessage.LogIfEmpty (GLAccount,GLAccount.FIELDNO(Name),TempErrorMessage."Message Type"::Error);
|
||||
**
|
||||
XMLDOMManagement.AddElement(RootNode,'Ctas','',Namespace,Node);
|
||||
XMLDOMManagement.AddAttribute(Node,'CodAgrup',GLAccount."SAT Account Code");
|
||||
...
|
||||
CASE GLAccount."Debit/Credit" OF
|
||||
GLAccount."Debit/Credit"::Debit:
|
||||
XMLDOMManagement.AddAttribute(Node,'Natur','D');
|
||||
GLAccount."Debit/Credit"::Credit:
|
||||
XMLDOMManagement.AddAttribute(Node,'Natur','A');
|
||||
ELSE
|
||||
**TempErrorMessage.LogMessage(
|
||||
GLAccount,GLAccount.FIELDNO("Debit/Credit"),TempErrorMessage."Message Type"::Error,
|
||||
STRSUBSTNO(GLAccountTypeErr,GLAccount."Debit/Credit",GLAccount.RECORDID));
|
||||
** END;
|
||||
UNTIL GLAccount.NEXT = 0;
|
||||
END ELSE
|
||||
**TempErrorMessage.LogSimpleMessage(TempErrorMessage."Message Type"::Error,NoSATAccountDefinedErr);
|
||||
**
|
||||
**IF NOT TempErrorMessage.HasErrors(TRUE) THEN
|
||||
** SaveXMLToClient(Document,Year,Month,'CT');
|
||||
**TempErrorMessage.ShowErrorMessages(FALSE);
|
||||
**END;
|
||||
|
||||
One could also do pre-processing in a function of its own, and only if the pre-processing results in no error messages of type "Error" would the processing continue.
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
By using this easy to use component, we have the possibility to extend this functionality going forward. A nice addition to the error message component would be the possibility to log the error messages persistently in a grouped manner, thereby allowing 3rd parties to see the issues the users bump into the most, or allowing 3rd parties to get an detailed insight into what happened, thereby enabling them to provide better support.
|
||||
|
||||
|
||||
|
||||
[anchor0]: /nav/w/designpatterns/124.journal-error-processing.aspx
|
||||
[anchor1]: image001.png
|
||||
[anchor2]: /nav/w/designpatterns/104.easy-update-of-setup-or-supplementary-information.aspx
|
||||
[anchor3]: image003.png
|
||||
|
||||
|
||||
[image0]: image001.png
|
||||
[image1]: image003.png
|
||||
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
|
@ -0,0 +1,170 @@
|
|||
+++
|
||||
title = "Extending the Role Center Headlines"
|
||||
weight = 560
|
||||
+++
|
||||
_By David Bastide at Microsoft Development Center Copenhagen_
|
||||
|
||||
_[![ ][image0]][anchor0]_
|
||||
|
||||
__
|
||||
|
||||
## Context
|
||||
|
||||
|
||||
Headlines are designed as a page of type HeadlinePart containing at least one text field. The part is added to the top of Role Center pages.
|
||||
This document provides an elegant and extensible pattern about how to extend the Role Center headlines to add your own business headlines based on your data, and display them only if relevant.
|
||||
|
||||
## Description
|
||||
|
||||
|
||||
The Dynamics 365 Business Central release (April 2018) introduces a new HeadlinePart page type. This page type defines a page that rotates a display of several headlines after another, in the web client. A user can also click to switch to another headline. Headlines can also include a drilldown action that will be invoked when the user clicks the headline Text of the payload can be emphasized.
|
||||
Headlines are divided in 2 parts: the qualifier, and the payload as you can see in the figure below.
|
||||
_
|
||||
_
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 10\]\>
|
||||
< \[endif\]--\>
|
||||
|
||||
_Figure 1: Qualifier, Payload and emphasized text.
|
||||
_
|
||||
|
||||
## Usage
|
||||
|
||||
A page part has been added to each major Role Center:
|
||||
|
||||
* Page 9006 Order Processor Role Center, contains Page 1441 Headline RC Order Processor
|
||||
* Page 9015 Job Project Manager RC, contains Page 1443 Headline RC Project Manager
|
||||
* Page 9022 Business Manager Role Center, contains Page 1440 Headline RC Business Manager
|
||||
* Page 9024 Security Admin Role Center, contains Page 1445 Headline RC Administrator
|
||||
* Page 9026 Sales & Relationship Mgr. RC, contains Page 1444 Headline RC Relationship Mgt.
|
||||
* Page 9027 Accountant Role Center, contains Page 1442 Headline RC Accountant
|
||||
* Page 9028 Team Member Role Center, contains Page 1446 Headline RC Team Member
|
||||
* Page 9010 Production Planner Role Center, contains Page 1447 Headline RC Prod. Planner
|
||||
* Page 9016 Service Dispatcher Role Center, contains Page 1448 Headline RC Serv. Dispatcher
|
||||
|
||||
You can create extensions that extend these pages to add your own headlines.
|
||||
If no headline is added on these pages, fallback headlines will be displayed.
|
||||
|
||||
The process to extend the headlines of a Role Center is simple:
|
||||
|
||||
1. In a V2 extension, extend the pages (PAG1440 to 1446) with one or more fields you want to add as headlines. The field and its visibility should be variables that are populated in OnAfterGetRecord.
|
||||
2. Subscribe to the OnComputeHeadlines event from the codeunits associated with the page (same ID and name as the page). Here you can compute your headlines. You should store the result in a table in your extension, so you can quickly get the results in step 3\. The computation is done in a background task, not to decrease the performance of the role center pages.
|
||||
3. Subscribe to the OnIsAnyExtensionHeadlineVisible event from the page. This event is used to determine if any extension has visible headlines, and if so, hide the fallback headlines. You should set the ExtensionHeadlinesVisible variable to true if your extension has headlines to display at the time of the event. Otherwise, do nothing.
|
||||
4. In the page, in the OnAfterGetRecord trigger, get the headline text and visibility values and copy them to your added fields.
|
||||
|
||||
To format headlines, you should use Codeunit 1439 Headline Management functions:
|
||||
|
||||
* Truncate: to truncate a text gracefully when possible with "...". For example, HeadlineManagement.Truncate('the text',6) returns "the...".
|
||||
* Emphasize: to emphasize part of the headline payload. Emphasized text is shown with a different style.
|
||||
* GetHeadlineText: to build the headline text. You provide the headline qualifier and payload, and you get the headline in a format that will be interpreted and formatted correctly by the client. It returns false if the qualifier exceeds its maximum length (50 characters) or payload exceeds its maximum length (75 characters). In that case it will not return the headline. If the qualifier you specify is empty, the default text "HEADLINE" will be displayed in the qualifier area. The payload must not be empty.
|
||||
|
||||
### Examples:
|
||||
|
||||
#### 1\. Extending the page with a new headline:
|
||||
|
||||
group(LargestSale)
|
||||
{
|
||||
Visible = LargestSaleVisible;
|
||||
ShowCaption=false;
|
||||
Editable=false;
|
||||
|
||||
field(LargestSaleText;LargestSaleText)
|
||||
{
|
||||
ApplicationArea = Basic, Suite;
|
||||
DrillDown=true;
|
||||
|
||||
trigger OnDrillDown()
|
||||
var
|
||||
EssentialBusHeadlineMgt: Codeunit "Essential Bus. Headline Mgt.";
|
||||
begin
|
||||
EssentialBusHeadlineMgt.OnDrillDownLargestSale();
|
||||
end;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
####
|
||||
|
||||
#### 2\. Subscribing to the OnComputeHeadlines event, and computing headlines
|
||||
|
||||
\[EventSubscriber(ObjectType::Codeunit, Codeunit::"Headline RC Business Manager", 'OnComputeHeadlines', '', true, true)\]
|
||||
procedure OnComputeHeadlinesBusinessManager()
|
||||
begin
|
||||
// \[...\] compute headline, and init the EssentialBusinessHeadline record
|
||||
if not ShowHeadline then
|
||||
exit; // not enough data to compute headline
|
||||
if not HeadlineManagement.GetHeadlineText(
|
||||
'Insight from last week',
|
||||
StrSubstNo('The largest posted sales invoice was for %1',
|
||||
HeadlineManagement.Emphasize(Format(CustomerLedgerEntry.Amount, 0, TypeHelper.GetAmountFormatWithUserLocale('$'))))
|
||||
EssentialBusinessHeadline."Headline Text")
|
||||
then
|
||||
exit;
|
||||
EssentialBusinessHeadline.Validate("Headline Visible", true);
|
||||
EssentialBusinessHeadline.Modify();
|
||||
end;
|
||||
|
||||
|
||||
####
|
||||
|
||||
#### 3\. Subscribing to the OnIsAnyExtensionHeadlineVisible event
|
||||
|
||||
\[EventSubscriber(ObjectType::Page, Page::"Headline RC Business Manager", 'OnIsAnyExtensionHeadlineVisible', '', true, true)\]
|
||||
procedure OnIsAnyExtensionHeadlineVisible(var ExtensionHeadlinesVisible: Boolean)
|
||||
var
|
||||
EssentialBusinessHeadline: Record "Essential Business Headline";
|
||||
AtLeastOneHeadlineVisible: Boolean;
|
||||
begin
|
||||
EssentialBusinessHeadline.SetRange("Headline Visible", true);
|
||||
EssentialBusinessHeadline.SetFilter("Headline Name",'%1|%2|%3|%4|%5',
|
||||
EssentialBusinessHeadline."Headline Name"::LargestOrder,
|
||||
EssentialBusinessHeadline."Headline Name"::LargestSale,
|
||||
EssentialBusinessHeadline."Headline Name"::BusiestResource,
|
||||
EssentialBusinessHeadline."Headline Name"::MostPopularItem,
|
||||
EssentialBusinessHeadline."Headline Name"::SalesIncrease,
|
||||
EssentialBusinessHeadline."Headline Name"::TopCustomer);
|
||||
AtLeastOneHeadlineVisible := not EssentialBusinessHeadline.IsEmpty();
|
||||
// only modify the var if this extension is making some headlines visible, setting to false could overrride some other extensions setting the value to true
|
||||
if AtLeastOneHeadlineVisible then
|
||||
ExtensionHeadlinesVisible := true;
|
||||
end;
|
||||
|
||||
####
|
||||
|
||||
#### 4\. Setting the headline text on the page
|
||||
|
||||
trigger OnAfterGetRecord()
|
||||
begin
|
||||
EssentialBusinessHeadline.GetHeadline(EssentialBusinessHeadline."Headline Name"::LargestSale);
|
||||
LargestSaleVisible := EssentialBusinessHeadline."Headline Visible";
|
||||
LargestSaleText := EssentialBusinessHeadline."Headline Text";
|
||||
end;
|
||||
|
||||
|
||||
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
_Figure 2: Sequence diagram of headline usage_
|
||||
|
||||
##
|
||||
Usages in NAV:
|
||||
|
||||
* Essential Business Headlines extension_
|
||||
_
|
||||
|
||||
< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if gte mso 9\]\>< \[endif\]--\>< --\[if supportAnnotations\]--\>< --\[endif\]--\>< --\[if gte mso 10\]\>
|
||||
< \[endif\]--\>
|
||||
|
||||
|
||||
|
||||
[anchor0]: 3733.logo.png
|
||||
[anchor1]: Headline.png
|
||||
[anchor2]: 0724.Headline-sequence-diagram-v2.png
|
||||
|
||||
|
||||
[image0]: 3733.logo.png
|
||||
[image1]: Headline.png
|
||||
[image2]: 0724.Headline-sequence-diagram-v2.png
|
||||
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
|
@ -0,0 +1,258 @@
|
|||
+++
|
||||
title = "Feature Localization For Data Structures"
|
||||
weight = 570
|
||||
+++
|
||||
_by Bogdan Sturzoiu at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
This pattern shows a solution for integrating W1 features to pre-existing country features that use different tables to achieve similar functionality.
|
||||
|
||||
## Description
|
||||
|
||||
It sometimes happens that certain features are requested in a NAV-supported country, but they are not initially considered generic enough to be included in the W1 build. This is how local features, such as Subcontracting in Italy and India, were created or specific banking and payments functionality in Italy, France, Spain, and others.
|
||||
|
||||
Then, at some point in time, a decision is made to create a W1 feature that is closely related to the local functionality but uses a completely different set of tables, pages, etc. The developers now face the following problem: How to enable the newly-developed W1 feature into a country, such that the customers who are accustomed to their local structures can seamlessly continue working without completely (or immediately) switching to the W1 objects.
|
||||
|
||||
This was the issue that was tackled in the NAV 2013 R2, in relation to the SEPA Credit Transfers functionality.
|
||||
|
||||
### Using a Proxy
|
||||
|
||||
The generic Proxy pattern is "a class functioning as an interface to something else" ([Wikipedia][anchor0]).
|
||||
|
||||
[![ ][image0]][anchor1]
|
||||
|
||||
Figure 1\. Proxy in UML
|
||||
|
||||
### Pattern Elements
|
||||
|
||||
The NAV data model translation of the proxy pattern can be used as explained below.
|
||||
|
||||
The RealSubject is the NAV data model. Variations in table structures, relationships, and numbers are particular to each country. The W1 model is the base for the country-localized data models. However, some countries have heavy localizations which cannot be directly processed by the W1 core objects.
|
||||
|
||||
The proxy is a codeunit that gathers data from wherever it is stored and transforms it to fit into a standard table, which is later used across all localizations.
|
||||
|
||||
The interface is the fixed form in which the data is presented to be consumed by the client.
|
||||
|
||||
The client can be an XML port that is fed from the common data interface. It can also be any other data processor (a codeunit fed to another table, etc.) or data display object (page or report).
|
||||
|
||||
### Pattern Steps
|
||||
|
||||
1. The user creates records in the local tables.
|
||||
2. The user invokes an action that must be processed using the W1 feature code.
|
||||
|
||||
1. The proxy codeunit moves the data from the local tables to the W1 tables, either into a temporary or persistent set of records, as needed.
|
||||
|
||||
1. The W1 code now performs the action on the W1 table data.
|
||||
|
||||
## Usage
|
||||
|
||||
In NAV 2013 R2, we released the SEPA Credit Transfer functionality. It involves exporting vendor payments to an XML file that is subsequently processed by the customer's bank. The payments are exported from the Payment Journal page through a configurable XMLport. Therefore, the data source for these payment lines is the Gen. Journal Line table (81).
|
||||
|
||||
In various countries, we already had payment export functionality, usually into flat bank files. However, the files are generated from different tables than in W1\. For example, in Italy, vendor payments are handled through the Vendor Bill Header table (12181) and the Vendor Bill Line table (12182). They are the RealSubject.
|
||||
|
||||
The W1 feature flow is as follows:
|
||||
|
||||
[![ ][image1]][anchor2]
|
||||
|
||||
Figure 2\. W1 object call sequence
|
||||
|
||||
**Note:** CT = Credit Transfers, pain = payments initiation (the XML format used for SEPA Credit Transfers and SEPA Direct Debit).
|
||||
|
||||
The key question is: Where to tap into this flow when using a local data structure. For this purpose, a proxy codeunit has been added in W1, called 1222 -- SEPA CT-Prepare Source. This codeunit feeds the client (XML1000) data in a standard format (the interface is the Gen. Journal Line table (81)).
|
||||
|
||||
In W1, the codeunit simply outputs the same set of general journal lines that it receives as an input:
|
||||
|
||||
OnRun(VAR Rec : Record "Gen. Journal Line")
|
||||
|
||||
GenJnlLine.COPYFILTERS(Rec);
|
||||
|
||||
CopyJnlLines(GenJnlLine,Rec);
|
||||
|
||||
LOCAL CopyJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line")
|
||||
|
||||
IF FromGenJnlLine.FINDSET THEN BEGIN
|
||||
|
||||
GenJnlBatch.GET(FromGenJnlLine."Journal Template Name",FromGenJnlLine."Journal Batch Name");
|
||||
|
||||
REPEAT
|
||||
|
||||
TempGenJnlLine := FromGenJnlLine;
|
||||
|
||||
TempGenJnlLine.INSERT;
|
||||
|
||||
UNTIL FromGenJnlLine.NEXT = 0
|
||||
|
||||
END ELSE
|
||||
|
||||
CreateTempJnlLines(FromGenJnlLine,TempGenJnlLine);
|
||||
|
||||
LOCAL CreateTempJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line")
|
||||
|
||||
// To fill TempGenJnlLine from the source identified by filters set on FromGenJnlLine
|
||||
|
||||
TempGenJnlLine := FromGenJnlLine;
|
||||
|
||||
In a country, such as Italy, the codeunit will have the following functions:
|
||||
|
||||
1. Gets an empty set of general journal lines that carry the local payment document key as a filter on the Document No. field (as opposed to W1 that gets the real set of records to be exported). This is done so that the local data can be extracted at runtime.
|
||||
|
||||
1. Selects the local payment data, for example in Italy, in the Vendor Bill Header and Vendor Bill Lines tables.
|
||||
|
||||
1. Transforms the local payment data into temporary records of the Gen. Journal Line table.
|
||||
|
||||
1. Outputs the temporary general journal lines that will be further processed and exported, exactly as in W1\.
|
||||
|
||||
OnRun(VAR Rec : Record "Gen. Journal Line")
|
||||
|
||||
GenJnlLine.COPYFILTERS(Rec);
|
||||
|
||||
CopyJnlLines(GenJnlLine,Rec);
|
||||
|
||||
LOCAL CopyJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line")
|
||||
|
||||
IF FromGenJnlLine.FINDSET THEN BEGIN
|
||||
|
||||
GenJnlBatch.GET(FromGenJnlLine."Journal Template Name",FromGenJnlLine."Journal Batch Name");
|
||||
|
||||
REPEAT
|
||||
|
||||
TempGenJnlLine := FromGenJnlLine;
|
||||
|
||||
TempGenJnlLine.INSERT;
|
||||
|
||||
UNTIL FromGenJnlLine.NEXT = 0
|
||||
|
||||
END ELSE
|
||||
|
||||
CreateTempJnlLines(FromGenJnlLine,TempGenJnlLine);
|
||||
|
||||
LOCAL CreateTempJnlLines(VAR FromGenJnlLine : Record "Gen. Journal Line";VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line")
|
||||
|
||||
PaymentDocNo := FromGenJnlLine.GETFILTER("Document No.");
|
||||
|
||||
VendorBillHeader.GET(PaymentDocNo);
|
||||
|
||||
VendorBillLine.RESET;
|
||||
|
||||
VendorBillLine.SETCURRENTKEY("Vendor Bill List No.","Vendor No.","Due Date","Vendor Bank Acc. No.","Cumulative Transfers");
|
||||
|
||||
VendorBillLine.SETRANGE("Vendor Bill List No.",VendorBillHeader."No.");
|
||||
|
||||
VendorBillLine.SETRANGE("Cumulative Transfers",TRUE);
|
||||
|
||||
IF VendorBillLine.FINDSET THEN BEGIN
|
||||
|
||||
CumulativeAmount := 0;
|
||||
|
||||
PrevVendorBillLine := VendorBillLine;
|
||||
|
||||
REPEAT
|
||||
|
||||
VendorBillLine.TESTFIELD("Document Type",VendorBillLine."Document Type"::Invoice);
|
||||
|
||||
IF ((VendorBillLine."Vendor No." <\> PrevVendorBillLine."Vendor No.") OR (VendorBillLine."Vendor Bank Acc. No." <\> PrevVendorBillLine."Vendor Bank Acc. No.")) THEN BEGIN InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount);
|
||||
|
||||
CumulativeAmount := VendorBillLine."Amount to Pay";
|
||||
|
||||
END ELSE
|
||||
|
||||
CumulativeAmount += VendorBillLine."Amount to Pay";
|
||||
|
||||
PrevVendorBillLine := VendorBillLine;
|
||||
|
||||
UNTIL VendorBillLine.NEXT = 0; InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,PrevVendorBillLine,CumulativeAmount);
|
||||
|
||||
END;
|
||||
|
||||
VendorBillLine.SETRANGE("Cumulative Transfers",FALSE);
|
||||
|
||||
IF VendorBillLine.FINDSET THEN
|
||||
|
||||
REPEAT
|
||||
|
||||
VendorBillLine.TESTFIELD("Document Type",VendorBillLine."Document Type"::Invoice); InsertTempGenJnlLine(TempGenJnlLine,VendorBillHeader,VendorBillLine,VendorBillLine."Amount to Pay");
|
||||
|
||||
UNTIL VendorBillLine.NEXT = 0;
|
||||
|
||||
LOCAL InsertTempGenJnlLine(VAR TempGenJnlLine : TEMPORARY Record "Gen. Journal Line";VendorBillHeader : Record "Vendor Bill Header";VendorBillLine : Record "Vendor Bill Line";AmountToPay : Decimal)
|
||||
|
||||
WITH TempGenJnlLine DO BEGIN
|
||||
|
||||
INIT;
|
||||
|
||||
"Journal Template Name" := '';
|
||||
|
||||
"Journal Batch Name" := '';
|
||||
|
||||
"Document Type" := "Document Type"::Payment;
|
||||
|
||||
"Document No." := VendorBillLine."Vendor Bill List No.";
|
||||
|
||||
"Line No." := VendorBillLine."Line No.";
|
||||
|
||||
"Account No." := VendorBillLine."Vendor No.";
|
||||
|
||||
"Account Type" := TempGenJnlLine."Account Type"::Vendor;
|
||||
|
||||
"Bal. Account Type" := TempGenJnlLine."Bal. Account Type"::"Bank Account";
|
||||
|
||||
"Bal. Account No." := VendorBillHeader."Bank Account No.";
|
||||
|
||||
"Applies-to Ext. Doc. No." := VendorBillLine."External Document No.";
|
||||
|
||||
Amount := AmountToPay;
|
||||
|
||||
"Applies-to Doc. Type" := VendorBillLine."Document Type";
|
||||
|
||||
"Applies-to Doc. No." := VendorBillLine."Document No.";
|
||||
|
||||
"Currency Code" := VendorBillHeader."Currency Code";
|
||||
|
||||
"Due Date" := VendorBillLine."Due Date";
|
||||
|
||||
"Posting Date" := VendorBillHeader."Posting Date";
|
||||
|
||||
"Recipient Bank Account" := VendorBillLine."Vendor Bank Acc. No.";
|
||||
|
||||
Description := VendorBillLine.Description;
|
||||
|
||||
"Message to Recipient" := VendorBillLine."Description 2";
|
||||
|
||||
INSERT;
|
||||
|
||||
END;
|
||||
|
||||
The derived local feature flow is as follows:
|
||||
|
||||
[![ ][image2]][anchor3]
|
||||
|
||||
Figure 3\. The local country object flow
|
||||
|
||||
As we can see from the diagram, this solution allows integration of the local and W1 features with a minimum amount of changes in W1 code. The only two differences are:
|
||||
|
||||
1. The entry point of the flow is the local table/page.
|
||||
|
||||
1. Codeunit 1222 is overloaded to prepare general journal lines from the local records.
|
||||
|
||||
## NAV Usages
|
||||
|
||||
The data mapping technique has been used for the SEPA Credit Transfer feature, and will be used in subsequent local integration projects.
|
||||
|
||||
## Ideas for improvement
|
||||
|
||||
A weak point for this pattern is the need to set a filter on the empty journal line in order to retrieve the local data when exporting from a local page. This can cause problems if the size of the local table document number is larger than the Document No. field (ID 20) in the Gen. Journal line table (81).
|
||||
|
||||
Also, there is a strong need for thorough testing when using this pattern, because there might be differences in the behavior of the local table and table 81\. Whatever is acceptable for the local table may not be acceptable for the W1 table. A deep functional analysis is needed to see if the local export feature uses the same constraints as the W1 feature.
|
||||
|
||||
|
||||
|
||||
[anchor0]: http://en.wikipedia.org/wiki/Proxy_pattern
|
||||
[anchor1]: 5123.Feature-localization-for-data-structures-1.png
|
||||
[anchor2]: 6052.Feature-localization-for-data-structures-2.png
|
||||
[anchor3]: 3058.Feature-localization-for-data-structures-3.png
|
||||
|
||||
|
||||
[image0]: 5123.Feature-localization-for-data-structures-1.png
|
||||
[image1]: 6052.Feature-localization-for-data-structures-2.png
|
||||
[image2]: 3058.Feature-localization-for-data-structures-3.png
|
||||
BIN
content/NAVPatterns/1-patterns/hooks/5383.HookPattern1.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
content/NAVPatterns/1-patterns/hooks/6378.HookPattern2.png
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
content/NAVPatterns/1-patterns/hooks/8156.HookPattern3.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
BIN
content/NAVPatterns/1-patterns/hooks/8875.HookPattern4.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
102
content/NAVPatterns/1-patterns/hooks/index.md
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
+++
|
||||
title = "Hooks"
|
||||
weight = 620
|
||||
+++
|
||||
_By Eric Wauters ([waldo][anchor0]), Partner-Ready-Software_
|
||||
|
||||
## Abstract
|
||||
|
||||
As a partner, adding new code to NAV means interfering with code shipped by Microsoft. Minimize your footprint of changes in Microsoft code, so that, when a new NAV version is shipped, you avoid conflicts and upgrade impact. The core NAV code is the "danger zone" - the less you touch it, the happier your upgrade will be.
|
||||
|
||||
Description
|
||||
|
||||
When doing development over years, by different developers with different mindsets, the standard codebase gets changed a lot, adding multiple lines of code, adding local and global variants, adding or changing keys, changing existing business logic, ... . In other terms, the standard text objects are being changed all over the place.. .
|
||||
|
||||
After years, it's not clear why a change was done, and what was the place where the change was intended to be done. And the latter is quite important in an upgrade process, when code in the base product is being refactored: if the exact place of the posting of the Customer Entry is being redesigned to a separate number, the first thing I need to know, is that I did a certain change at the place: "where the posting of the Customer Entry starts". The definition of that place, we call a "Hook".
|
||||
|
||||
By minimizing the code in already existing application objects, you will make the upgrade process much easier, and all customization business logic will be grouped in new objects. When using atomic coding, it will be very readable what is being customized on a certain place in an existing part of the application.
|
||||
|
||||
To minimize the impact of customizations, the idea of hooks is:
|
||||
|
||||
* First of all, name the places in the already existing code where customization is needed;
|
||||
* Second, place your business logic completely outside the already existing application code.
|
||||
|
||||
I recommend to use this concept on:
|
||||
|
||||
* All objects of the default applications that need to be changed
|
||||
* On objects that should not hold any business logic (like tables, pages, XMLPorts)
|
||||
|
||||
## Usage
|
||||
|
||||
Step 1 - if it doesn't exist yet - you create your Hook Codeunit. As the name assumes .. this is always a codeunit. We apply the following rules to it:
|
||||
|
||||
* One Hook always hooks into one object. Which basically means that I will only declare this new codeunit in one other object (which is its parent object)
|
||||
* The naming convention is: "The\_Original\_Object\_Name Hook". Naming conventions are important, just to find your mapped object, and also to be able to group the Hooks.
|
||||
|
||||
Step 2, you create the hook, which is basically a method (function) in your codeunit. The naming is important:
|
||||
|
||||
* The naming of the hook should NOT describe what it is going to do (So, examples like "CheckMandatoryFields", "FillCustomFields" should not be used as a hook)
|
||||
* The naming of the hook should describe WHERE the hook is placed, not what the hook will be doing (as nobody is able to look into the future .. :-))
|
||||
* To help with the naming, it is a good convention to use the "On"-prefix for these triggers. This way, it's very clear what are hooks, and what aren't..
|
||||
|
||||
Step 3, it's time to hook it to its corresponding object and right place in the business logic of that object. You do this by declaring your codeunit as a global in your object, and using the created hook function on its place in the business logic. This way, these one-liners apply:
|
||||
|
||||
* A Hook Codeunit is only used once in one object only (its corresponding object)
|
||||
* A Hook (function) is used only once in that object. As a consequence, changing the parameters has no consequence: you only need to change one function-call
|
||||
* The codeunit is declared as a global. That exact global is the only custom declaration in the existing object .. Everything else is pushed to the hook-codeunit.
|
||||
|
||||
Step 4, implement your business logic in the hook. Do this in the most atomic way, as there is a good chance that this same hook is going to be used for other business logic as well. Best is to use a one-line-function-call to business logic, so that the Hook Function itself stays readable.
|
||||
|
||||
## Example
|
||||
|
||||
Suppose, we want to add business logic just before posting a sales document. In that case, we have to look for the most relevant place, which is somewhere in the "Sales-Post" codeunit. So:
|
||||
|
||||
Step 1: create codeunit "Sales-Post Hook"
|
||||
|
||||
[![ ][image0]][anchor1]
|
||||
|
||||
Step 2: create the hook function "OnBeforePostDocument"
|
||||
|
||||
[![ ][image1]][anchor2]
|
||||
|
||||
Step 3: declare a global in the "Sales-Post"-codeunit, called "SalesPostHook". Then, call the Hook Function that you created in Step 2 in the right place.
|
||||
|
||||
[![ ][image2]][anchor3]
|
||||
|
||||
Step 4: implement the business logic, by calling out to a new function. And implement the test-codeunit.
|
||||
|
||||
[![ ][image3]][anchor4]
|
||||
|
||||
## Consequences
|
||||
|
||||
This pattern can be used in all cases to put busines logic. But I see three possible approaches
|
||||
|
||||
1. You only declare the most important and most used hooks
|
||||
* This way, you limit the amount of objects and hooks to only a few in the default product
|
||||
* For example, only the OnBeforePostSalesHeader, OnBeforeReleaseSalesDocument, .. And no field validation or such...
|
||||
2. Only at objects of the default application which you are customizing.
|
||||
* This way, you don't want to create hooks for your own objects, only default existing objects.
|
||||
3. (recommended) You create hooks on all places you don't want to write business logic, and on all existing objects which you would like to customize.
|
||||
* This is a very consistent way of working, as in any case, your business logic ends up in either a hook, or in its corresponding objects from a specific design pattern. But you know that the entry point is always a hook.
|
||||
* You know what to expect in any case, both changed business logic in existing code and business logic in newly created code is entered from a hook.
|
||||
|
||||
## Related Topics
|
||||
|
||||
Atomic coding: It's important that the hook function is readable in the most extreme way. For this, we recommend to use the "Atomic Coding" concept.
|
||||
|
||||
See here a comparison / extension of hooks : [http://www.waldo.be/2016/02/29/nav-2016-hooks-or-events/][anchor5]
|
||||
|
||||
|
||||
|
||||
[anchor0]: http://www.waldo.be "waldo's blog"
|
||||
[anchor1]: 5383.HookPattern1.png
|
||||
[anchor2]: 6378.HookPattern2.png
|
||||
[anchor3]: 8156.HookPattern3.png
|
||||
[anchor4]: 8875.HookPattern4.png
|
||||
[anchor5]: http://www.waldo.be/2016/02/29/nav-2016-hooks-or-events/
|
||||
|
||||
|
||||
[image0]: 5383.HookPattern1.png
|
||||
[image1]: 6378.HookPattern2.png
|
||||
[image2]: 8156.HookPattern3.png
|
||||
[image3]: 8875.HookPattern4.png
|
||||
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
|
@ -0,0 +1,180 @@
|
|||
+++
|
||||
title = "Surrogate keys using Autoincrement Pattern"
|
||||
weight = 630
|
||||
+++
|
||||
_By [Soren Klemmensen][anchor0], [_Partner-Ready-Software_ ][anchor1]& [360 Visibility][anchor2]_
|
||||
|
||||
## **Abstract**
|
||||
|
||||
This Pattern is meant to create generic & reusable links between tables. The goal is to have an easy generic way to link a generically designed sub table to a record on a main table which can be used for other links too.
|
||||
|
||||
To minimize the impact of customizations and to keep modules as generic and reusable as possible the idea of the Implementation of surrogate keys using AutoIncrement pattern is:
|
||||
|
||||
* To create a generic and reusable auto generated link (A Surrogate Key), Immune to natural key data & requirement changes, on a main table with minimum impact on the table.
|
||||
* To create generic and reusable sub tables that effortless can be reused anywhere in the application.
|
||||
|
||||
## **Description**
|
||||
|
||||
Over years of development many things are repeated across different implementation and even inside the same application. A typical example could be adding comments to an area just as it is done in Microsoft Dynamics NAV multiple times. There can be reasons for doing this again and again, but not only does this need to be maintained and upgraded over the years, but all the implementations of comments also needs to be tested separately. If a standard and generic comment could be developed and a generic way of connecting it to a main table this could be resolved. This is exactly what this pattern is trying accomplish.
|
||||
|
||||
[![ ][image0]][anchor3]
|
||||
|
||||
_Figure 1: Table structure for linking a Document Header and Line Table with a Document Comment Table._
|
||||
|
||||
__
|
||||
|
||||
_[![ ][image1]][anchor4]_
|
||||
|
||||
_Figure 2: Table Structure for linking a Master Data Table with a Master Data Comment Table_
|
||||
|
||||
__
|
||||
|
||||
A typical way of linking a table to master data or to a document has been to use the primary key of the table being linked to. This causes some issues as the linked table now is designed specifically for the main table and it functionality cannot be reused. In case of renames the linked table needs to be renamed too which is costly in processing. Code also needs to be added on the delete trigger of the table to ensure that the attached records get removed if needed which increases the over all footprint of any change.
|
||||
|
||||
_[![ ][image2]][anchor5]_
|
||||
|
||||
_Figure 3: A Generic Way of creating a Comment table and linking it in a generic way to the main table no matter what this table might be. The Unique Record Identifier on the main tables is an Integer with AutoIncrement set to yes._
|
||||
|
||||
__
|
||||
|
||||
It is recommended using this pattern in all tables which need sub tables unless specific reasons exists for not doing this.
|
||||
|
||||
## **Usage**
|
||||
|
||||
**Step 1**: Create a generic Unique Record Identifier in the main table
|
||||
|
||||
The Pattern is implemented by adding a Field (I have called it Unique Record Identifier for this article) in a table (the main Table) where links are needed to be established to. Set the Property Data Type to Integer, Editable to No & AutoIncrement to Yes.
|
||||
|
||||
**Step 2**: Create a generic link-able sub table.
|
||||
|
||||
Create a new table (Sub Table) which you would like to be reusable with a primary key containing
|
||||
|
||||
* Table No. of Data Type Integer
|
||||
* Unique Record Identifier of Data Type Integer
|
||||
* A 3 field for allowing multiple entries to exist per record in the main table if so needed. This could be a Line No. of Data Type Integer or a Code field of Data Type Code(10) and so on.
|
||||
|
||||
The important part here is that the 2 or 3 first fields in the tables primary key is the Table No. and the Unique Record Identifier. If a 3rd field was added to allow for multiple entries to exist per record in the main table this should also be included in the primary key.
|
||||
|
||||
Make sure to also add any other fields containing the information you wish to store as needed to the table.
|
||||
|
||||
The sub table will be immune to renames from the main table as the main tables primary key is not used in the primary key of the sub table. The Insert, Modify and Rename triggers are not causing any issues and only the delete trigger will need to be considered. This can be dealt with generically from the OnDatabaseDelete trigger in Codeunit 1\. I would recommend to use a Hook Pattern for this.
|
||||
|
||||
**Step 3**: Create a page showing the sub table information.
|
||||
|
||||
Now create a page showing the data in the sub table.
|
||||
|
||||
**Step 4**: Add an Action or factbox.
|
||||
|
||||
Create an action or factbox on the pages showing the main table data linking to the subpage with Table ID filtered to a constant of the Table No. of the main table and the Unique Record Identifier of the sub table filtering to the Unique Record Identifier of the main table.
|
||||
|
||||
**Step 5**: Create a Hook for Function OnDatabaseDelete in Codeunit 1 ApplicationManagement if one doesn't already exist. See the Hook pattern.
|
||||
|
||||
**Step 6**: Create a code to delete records in the Sub table if a main table record is deleted if this is required. This function needs to be called from the Hook created in Step 5\.
|
||||
|
||||
## **NAV Specific Example**
|
||||
|
||||
Let's assume we would like to create comment for a larger number of very different tables in the system.
|
||||
|
||||
**Update the Customer table (Step 1)**: Go to table 18 Customer and add Field 50000 Unique Record Identifier. Set the Property Data Type to Integer, Editable to No & AutoIncrement to Yes. Save the changes.
|
||||
|
||||
_[![ ][image3]][anchor6]_
|
||||
|
||||
__
|
||||
|
||||
_[![ ][image4]][anchor7]_
|
||||
|
||||
__
|
||||
|
||||
**Create Comment table (Step 2)**: Create a new table called Comment. Add 3 fields Table No., Unique Record Identifier & Line No. all of Data Type Integer. Make these 3 fields into the primary key for the table. Add a 4 field called Comment with Data Type Text(80). Save the changes.
|
||||
|
||||
[![ ][image5]][anchor8]
|
||||
|
||||
**Create the Comments page (Step 3)**: Start the page wizard and create a Page based on table comment created above as a List only showing the Comment field. Set AutoSplitKey property to Yes on the page.
|
||||
|
||||
__
|
||||
|
||||
_[![ ][image6]][anchor9]_
|
||||
|
||||
__
|
||||
|
||||
**Update the Customer Card (Step 4)**: Add an action to the Customer Card to open the Comments. Go to Actions and create an action called Smart Comment. Populate the properties RunObject, RunPageView and RunPageLink as see in the picture below.
|
||||
|
||||
[![ ][image7]][anchor10]
|
||||
|
||||
__
|
||||
|
||||
**Create a hook OnDatabaseDelete (Step 5)**:
|
||||
|
||||
Create a codeunit 50000 called "ApplicationManagement Hook" with one function called OnAfterOnDatabaseDelete taking the parameter RecRef of Data Type RecordRef. Add it as a global variable to Codeunit 1 ApplicationManagement and call the function as the last line in OnDatabaseDelete. Please read about the hook pattern before implementing it.
|
||||
|
||||
[![ ][image8]][anchor11]
|
||||
|
||||
__
|
||||
|
||||
**Create the code needed to delete comments linked to a deleted record (Step6)**:
|
||||
|
||||
Create a DeleteComments function taking the RecRef of Data Type RecordRef and add the code as shown blow.
|
||||
|
||||
[![ ][image9]][anchor12]
|
||||
|
||||
__
|
||||
|
||||
It is assumed in this example for simplicity that the Field 50000 is reserved across the entire application for the Unique Record Identifier as defined in Step 1\.
|
||||
|
||||
The comments are now fully working if we look away from the fact that we did not deal with a few things specific to Sales orders like RecreateSalesLines function, Archiving and Copy Document. All of which can easily be dealt with.
|
||||
|
||||
These comments are now completely reusable everywhere else in the system. Sales Document is a perfect example as the primary keys of the Sales Header and the Sales line are both different from the customer and normally we would not be able to use the comments header or the line. All that needs to be done is adding the Field 50000 Unique Record Identifier to the Sales Header & Sales Line (Disregarding the posted documents in this example) and creating the actions on the Page Actions with the needed filters. Deletion is already handled of comments no matter what the main table might be.
|
||||
|
||||
Looking at the main table the Unique Record Identifier is also completely reusable for any other linking needed.
|
||||
|
||||
Other ideas for use of this pattern could be. An Error table, Tags, Dynamically defined fields and Generic fact boxes. Only the imagination sets limits for its use.
|
||||
|
||||
Upgrade wise there can be an impact if data is moved out of tables to be reinserted again because of a change to a database structure. This will cause the Unique Record Identifier to change, unless steps are taken to avoid this, and the links will need to be reestablished.
|
||||
|
||||
Other risks could be if Transfer Fields are used and data is being copied unintentionally.
|
||||
|
||||
## **NAV Usages**
|
||||
|
||||
This is a new pattern not currently used in Microsoft Dynamics NAV.
|
||||
|
||||
## **Ideas for improvement ******
|
||||
|
||||
The reason for doing it this way is that you now can reuse your code again and again with only creating the same link on other tables instead of building it from scratch each time reducing testing needed and improving the quality of the overall product.
|
||||
|
||||
## **Consequences (When it should not be used)**
|
||||
|
||||
This can be used on any table when linking anything to it that can be considered a generic module which can be reused. That said it should not be used in cases where there is a risk of tables growing so much that performance could be impacted. There are ways to reduce performance impact when using high volume tables, but that is outside the scope of this pattern.
|
||||
|
||||
## **Related Topics**
|
||||
|
||||
This is related to the hook pattern as far as they both try to reduce the footprint changes have on the standard application, by creating reusable ways to interact with the standard code. That said the hook pattern is more about hooking the functionality to existing while this pattern is more about creating reusable ways of creating functionality.
|
||||
|
||||
__
|
||||
|
||||
|
||||
|
||||
[anchor0]: http://mvp.microsoft.com/en-us/mvp/Soren%20Klemmensen-5001002 "Soren Klemmensen"
|
||||
[anchor1]: http://partner-ready-software.com/ "Partner-Ready-Software"
|
||||
[anchor2]: http://www.360visibility.com/ "360 Visibility"
|
||||
[anchor3]: 0458.Figure-1.PNG
|
||||
[anchor4]: 0638.Figure-2.PNG
|
||||
[anchor5]: 0333.Figure-3.PNG
|
||||
[anchor6]: 1488.Example-Figure-1.png
|
||||
[anchor7]: 4682.Example-Figure-2.png
|
||||
[anchor8]: 4532.Example-Figure-3.png
|
||||
[anchor9]: 2068.Example-Figure-4.png
|
||||
[anchor10]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/0552.Example-Figure-5.png
|
||||
[anchor11]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/4477.Example-Figure-6.png
|
||||
[anchor12]: /cfs-file.ashx/__key/communityserver-wikis-components-files/00-00-00-00-42/1884.Example-Figure-7.png
|
||||
|
||||
|
||||
[image0]: 0458.Figure-1.PNG
|
||||
[image1]: 0638.Figure-2.PNG
|
||||
[image2]: 0333.Figure-3.PNG
|
||||
[image3]: 1488.Example-Figure-1.png
|
||||
[image4]: 4682.Example-Figure-2.png
|
||||
[image5]: 4532.Example-Figure-3.png
|
||||
[image6]: 2068.Example-Figure-4.png
|
||||
[image7]: 0552.Example-Figure-5.png
|
||||
[image8]: 4477.Example-Figure-6.png
|
||||
[image9]: 1884.Example-Figure-7.png
|
||||
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 80 KiB |
157
content/NAVPatterns/1-patterns/instructions-in-the-ui/index.md
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
+++
|
||||
title = "Instructions in the UI"
|
||||
weight = 670
|
||||
+++
|
||||
_by Nikola Kukrika at Microsoft Development Center Copenhagen_
|
||||
|
||||
## Abstract
|
||||
|
||||
To mitigate usability problems with learnability or discoverability of NAV functionality, it is possible to embed instructions in the UI in connection with the task that the user is performing. The goal is to explain how to use the product or feature without impairing the user's productivity after user has learned how to use a feature.
|
||||
|
||||
## Description
|
||||
|
||||
Users must often go through a few days of training to learn how to use NAV, and even then, many users rely on super users to help them mitigate difficulties using NAV. In addition, because of low discoverability and learnability, many useful features are not being used at all.
|
||||
|
||||
Users' expectations are changing. They expect the software to be usable out-of-the-box because this is the trend in software generally.
|
||||
|
||||
One of the cheapest and most effective methods to solve usability issues is to embed instructional messages in the product. From a user-experience point of view, **this should be used as a last resort**. UI should be self-explanatory, efficient, and simple to use. Accordingly, you should only implement this pattern if simplifying and improving a scenario is not possible or is too expensive.
|
||||
|
||||
In this connection, the most important requirement is not to impair productivity of the users. One of the biggest and most common UX mistakes that developers make is to "optimize for new users". After the user has learned how to use the product, all the instruction texts and dialogs that we added to the UI will clutter the page and make information less visible. Instructional dialogs on routine tasks will become annoying. Therefore, we must make all instructions dismissible.
|
||||
|
||||
In the Mini App solution we have used following elements:
|
||||
|
||||
1. Dismissible dialogs
|
||||
2. FastTabs with instructional text
|
||||
3. Help tiles on a Role Center
|
||||
4. Tooltips on actions and fields
|
||||
5. Task-oriented page Help
|
||||
|
||||
## Usage
|
||||
|
||||
The following pattern applies to dismissible parts in the UI.
|
||||
|
||||
We have a table that stores the instructional code ID and the UserID, so that we can track which user has turned off which instruction. All the logic handling is done from a codeunit. It is the responsibility of the codeunit to show/hide dialogs if needed.
|
||||
|
||||
[![ ][image0]][anchor0]
|
||||
|
||||
## Dismissible Dialogs
|
||||
|
||||
Dismissible dialogs show the instructional message about the functionality, with the user option to select "Don't show this again". This is a good solution to problems where users enter text in the wrong place, or to explain behavior of a somewhat hidden feature.
|
||||
|
||||
[![ ][image1]][anchor1]
|
||||
|
||||
On a recent usability study of the **Description** field on sales or purchase lines, most users ignored the **No.** field and started entering text in the description field before proceeded to enter a quantity. In the solution in question, text only is treated as a line comment if the **No.** field is blank. The fix was to update the field name to **Description/Comment** and to provide a message that typing in the field creates a comment only. Users that often use comments can then choose "Do not show again" to get rid of the instructional text.
|
||||
|
||||
**When to use: **Recommendation is to use only when many users are entering data in the wrong way and modifying the code is costly. This is an interrupting dialog, but the benefits are that it is very hard to overlook this dialog.
|
||||
|
||||
## FastTabs with Instructional Text
|
||||
|
||||
Instructional text on FastTabs is ideal for showing larger amounts of text in the UI.
|
||||
|
||||
[![ ][image2]][anchor2]
|
||||
|
||||
When a user changes a filter in the **Navigate** page, we blank the grid. This may confuse the users as to how to proceed. The **Notification** FastTab provides information on what has happened and gives instructions on how to proceed.
|
||||
|
||||
Similar implementation is to have the FastTab always visible with the **Do not show again** check box present, so that users can dismiss it after they have read the message. This is less intrusive than using a dialog, and it has the benefit of being always visible compared to the dialog. The drawback is that users may not read it or may not dismiss it.
|
||||
|
||||
## Information Tiles on Role Centers
|
||||
|
||||
On the **Small Business Role Center** page (9022), we have implemented a **Getting Started** group containing action tiles. Clicking on the first two tiles will play instructional videos. Clicking on the third tile launches a dedicated help topic. Since these tiles will get in the way of the experienced users, an option to hide the entire group is provided.
|
||||
|
||||
[![ ][image3]][anchor3]
|
||||
|
||||
**Note**: in NAV 2013 R2, actions appear as tiles in the web client only. In the win client, they appear as links. In the web client, the actions only appear if they are in a group for themselves (without Stack Queues -- empty group with only actins defined).
|
||||
|
||||
### To implement tiles for instructional videos
|
||||
|
||||
1. Upload a video to a video hosting service (check if licensing is allowing you to use if for this usage. Examples of video hosting services are: YouTube, Vimeo, Yahoo Video.)
|
||||
2. Get the code to embed the video (select option embed).
|
||||
3. You can reuse the code on the **Mini Video Player Page** page (1395) or implement a custom one.
|
||||
|
||||
Important parts:
|
||||
**VideoPlayerAddIn.SetFrameAttribute** function is used to set an attribute to the iframe that will be playing the video.
|
||||
|
||||
|
||||
Example of the embed code:
|
||||
|
||||
<iframe width="560" height="315" src="//www.youtube.com/embed/7SGp9pA9cAY" frameborder="0" allowfullscreen\></iframe\>
|
||||
|
||||
You must assign**src attribute **to src of the embed code, for example:
|
||||
|
||||
VideoPlayer.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:
|
||||
|
||||
VideoPlayer.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.
|
||||
|
||||
VideoPlayerAddIn.SetHeight(Height) and VideoPlayerAddIn.SetWidth(Width);
|
||||
|
||||
If you would like to reuse the **Mini Video Player Page** page (1395), then use:
|
||||
|
||||
SetParameters(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
|
||||
|
||||
**Note:**
|
||||
|
||||
Videos 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.
|
||||
|
||||
For 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.
|
||||
|
||||
### To 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.
|
||||
|
||||
## Tooltips 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.
|
||||
|
||||
[![ ][image4]][anchor4]
|
||||
|
||||
**Note**: 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.
|
||||
|
||||
## Task-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.
|
||||
|
||||
[![ ][image5]][anchor5]
|
||||
|
||||
## NAV Usages
|
||||
|
||||
Dismissible dialogs - Used in the **Description** field in pages 1305, 1325, 1355, 1373, ....
|
||||
|
||||
FastTabs with instructional text -- **Navigate** page (344).
|
||||
|
||||
Help Tiles on Role Center -- **Small Business Role Center** page (9022) and **Mini Activities** page (1310).
|
||||
|
||||
Tooltips -- All pages in the 1300 number range.
|
||||
|
||||
Task-oriented page help -- all task pages in 1300 number range
|
||||
|
||||
## Ideas 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.
|
||||
|
||||
Implement tooltips across the application and in all country versions. (Requires a run-time infrastructure system.)
|
||||
|
||||
[watch?v=loobQ1TVO3o&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=14][anchor6]
|
||||
|
||||
|
||||
|
||||
[anchor0]: 6215.picture-1.png
|
||||
[anchor1]: 2804.Picture-2.png
|
||||
[anchor2]: 6685.picture-3.png
|
||||
[anchor3]: 5707.Picture-4.png
|
||||
[anchor4]: 7217.picture-1.png
|
||||
[anchor5]: 7245.Picture-2.png
|
||||
[anchor6]: https://www.youtube.com/watch?v=loobQ1TVO3o&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=14
|
||||
|
||||
|
||||
[image0]: 6215.picture-1.png
|
||||
[image1]: 2804.Picture-2.png
|
||||
[image2]: 6685.picture-3.png
|
||||
[image3]: 5707.Picture-4.png
|
||||
[image4]: 7217.picture-1.png
|
||||
[image5]: 7245.Picture-2.png
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
+++
|
||||
title = "Integration of Addresses"
|
||||
weight = 680
|
||||
+++
|
||||
[watch?v=60Wrx9N gfY&list=PLhZ3P LY7CqmVszuvtJLujFyHpsVN0Uw&index=19][anchor0]
|
||||
|
||||
|
||||
|
||||
[anchor0]: https://www.youtube.com/watch?v=60Wrx9N-gfY&list=PLhZ3P-LY7CqmVszuvtJLujFyHpsVN0U_w&index=19
|
||||
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 28 KiB |