Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Curso de Desarrollo Microsoft Dynamcis Ax 2012 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 582

COURSE 80313

DEVELOPMENT IV
IN MICROSOFT DYNAMICS® AX 2012

Microsoft Official Training Materials for Microsoft Dynamics®


Your use of this content is subject to your current services agreement
Last Revision: March 2012

This courseware is provided “as-is”. Information and views expressed in this courseware, including URL and other
Internet Web site references, may change without notice.

Unless otherwise noted, the examples depicted herein are provided for illustration only and are fictitious. No real
association or connection is intended or should be inferred.

This courseware does not provide you with any legal rights to any intellectual property in any Microsoft product.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under
copyright, no part of this courseware may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means or for any purpose, without the express written permission of Microsoft
Corporation.

Copyright © 2012 Microsoft Corporation. All rights reserved.

Microsoft®, Microsoft Dynamics®, Microsoft® PowerPoint®, Microsoft® SQL Server® data management software
and Microsoft Dynamics® AX are trademarks of the Microsoft group of companies. All other trademarks are
property of their respective owners.

This course content is designed for Microsoft Dynamics® AX 2012.

Microsoft Official Training Materials for Microsoft Dynamics®


Your use of this content is subject to your current services agreement
Table of Contents

Introduction 0-1 
Welcome ............................................................................................................ 0-1 
Microsoft Dynamics Courseware Contents ........................................................ 0-2 
Documentation Conventions .............................................................................. 0-3 
Student Objectives ............................................................................................. 0-4 
Chapter 1: Number Sequences 1-1 
Objectives ........................................................................................................... 1-1 
Introduction ......................................................................................................... 1-1 
Overview ............................................................................................................ 1-2 
Set Up and Administration .................................................................................. 1-4 
Extensibility Scenarios ..................................................................................... 1-10 
Using Number Sequences in Forms ................................................................ 1-19 
Lab 1.1 - Implement a New Number Sequence ............................................... 1-22 
Summary .......................................................................................................... 1-31 
Test Your Knowledge ....................................................................................... 1-32 
Quick Interaction: Lessons Learned ................................................................. 1-33 
Solutions ........................................................................................................... 1-34 
Chapter 2: Framework Features 2-1 
Objectives ........................................................................................................... 2-1 
Introduction ......................................................................................................... 2-1 
Event Handlers for Customization ...................................................................... 2-5 
Integration with Microsoft Dynamics AX ........................................................... 2-16 
Interop to X++ ................................................................................................... 2-23 
Interop from X++ .............................................................................................. 2-30 
Deploy .NET Assemblies for Interop ................................................................ 2-40 
Summary .......................................................................................................... 2-45 
Test Your Knowledge ....................................................................................... 2-46 
Quick Interaction: Lessons Learned ................................................................. 2-48 
Solutions ........................................................................................................... 2-49 
Chapter 3: Application Foundation Features 3-1 
Objectives ........................................................................................................... 3-1 
Introduction ......................................................................................................... 3-1 
Global Address Book .......................................................................................... 3-2 
Extensible Data Security Policy Framework ..................................................... 3-12 
Lab 3.1 - Extensible Data Security Policies ...................................................... 3-22 
Financial Dimension Framework ...................................................................... 3-25 
Organization Model Framework ....................................................................... 3-26 
Case Management Framework ........................................................................ 3-34 
Lab 3.2 - Extend Case Management ................................................................ 3-44 
Policy Framework ............................................................................................. 3-49 
Summary .......................................................................................................... 3-59 
Test Your Knowledge ....................................................................................... 3-60 
Quick Interaction: Lessons Learned ................................................................. 3-62 
Solutions ........................................................................................................... 3-63 

i
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Chapter 4: Use and Design of the Ledger Module 4-1 


Objectives ........................................................................................................... 4-1 
Introduction ......................................................................................................... 4-1 
General Ledger Overview .................................................................................. 4-2 
Chart of Accounts ............................................................................................... 4-8 
Lab 4.1 - Create a System-Defined Dimension ................................................ 4-22 
Journals and Transactions ............................................................................... 4-24 
Lab 4.2 - Import Ledger Transactions .............................................................. 4-33 
Budgeting Overview ......................................................................................... 4-39 
Fixed Asset Overview ....................................................................................... 4-45 
Summary .......................................................................................................... 4-49 
Test Your Knowledge ....................................................................................... 4-50 
Quick Interaction: Lessons Learned ................................................................. 4-52 
Solutions ........................................................................................................... 4-53 
Chapter 5: Use and Design of the Product Information Management
Module 5-1 
Objectives ........................................................................................................... 5-1 
Introduction ......................................................................................................... 5-1 
Products ............................................................................................................. 5-2 
Inventory Dimensions ....................................................................................... 5-13 
Managing Inventory Policies ............................................................................ 5-19 
Lab 5.1 - Product Information Management Workshop .................................... 5-22 
Summary .......................................................................................................... 5-29 
Test Your Knowledge ....................................................................................... 5-30 
Quick Interaction: Lessons Learned ................................................................. 5-31 
Solutions ........................................................................................................... 5-32 
Chapter 6: Use and Design of the Inventory and Warehouse
Management Module 6-1 
Objectives ........................................................................................................... 6-1 
Introduction ......................................................................................................... 6-1 
Reservations and Marking .................................................................................. 6-2 
Inquiries and Transactions ................................................................................. 6-3 
Inventory Journals ............................................................................................ 6-13 
Lab 6.1 - Import Beginning Balances ............................................................... 6-17 
Quarantine and Quality Management............................................................... 6-29 
Other Functionality ........................................................................................... 6-31 
Lab 6.2 - Inventory Blocking ............................................................................. 6-33 
Summary .......................................................................................................... 6-42 
Test Your Knowledge ....................................................................................... 6-43 
Quick Interaction: Lessons Learned ................................................................. 6-45 
Solutions ........................................................................................................... 6-46 

ii
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Table of Contents

Chapter 7: Use and Design of the Accounts Receivable and Accounts


Payable Modules 7-1 
Objectives ........................................................................................................... 7-1 
Introduction ......................................................................................................... 7-1 
Customers .......................................................................................................... 7-2 
Vendors .............................................................................................................. 7-6 
Free Text Invoices .............................................................................................. 7-9 
Vendor Invoices ................................................................................................ 7-12 
Payments ......................................................................................................... 7-15 
Lab 7.1 - Export Vendor Payments .................................................................. 7-25 
Collections and Interest .................................................................................... 7-31 
Bills of Exchange .............................................................................................. 7-33 
Promissory Notes ............................................................................................. 7-35 
Lab 7.2 - Transfer Balances ............................................................................. 7-37 
Summary .......................................................................................................... 7-39 
Test Your Knowledge ....................................................................................... 7-40 
Quick Interaction: Lessons Learned ................................................................. 7-42 
Solutions ........................................................................................................... 7-43 
Chapter 8: Use and Design of the Sales and Purchase Modules 8-1 
Objectives ........................................................................................................... 8-1 
Introduction ......................................................................................................... 8-2 
Sales and Purchase Orders ............................................................................... 8-2 
Agreements ...................................................................................................... 8-11 
Charges ............................................................................................................ 8-19 
FormLetter Framework ..................................................................................... 8-23 
Lab 8.1 - Add a Field to the Sales Invoice ........................................................ 8-37 
Other Features ................................................................................................. 8-45 
Summary .......................................................................................................... 8-50 
Test Your Knowledge ....................................................................................... 8-51 
Quick Interaction: Lessons Learned ................................................................. 8-52 
Solutions ........................................................................................................... 8-53 
Chapter 9: Use and Design of the Project Management and
Accounting Module 9-1 
Objectives ........................................................................................................... 9-1 
Introduction ......................................................................................................... 9-1 
Projects .............................................................................................................. 9-3 
Work Breakdown Structure ................................................................................ 9-9 
Journals and Transactions ............................................................................... 9-11 
Lab 9.1 - Warranty Item .................................................................................... 9-17 
Budgets and Forecasting ................................................................................. 9-21 
Project Contracts .............................................................................................. 9-27 
Invoicing ........................................................................................................... 9-29 
Lab 9.2 - Put an Invoice Proposal on Hold ....................................................... 9-32 
Estimates and Revenue Recognition ............................................................... 9-36 
Project Management and Accounting Add-In ................................................... 9-38 
Summary .......................................................................................................... 9-39 
Test Your Knowledge ....................................................................................... 9-40 

iii
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned ................................................................. 9-42 


Solutions ........................................................................................................... 9-43 
Chapter 10: Use and Design of the Production Control Module 10-1 
Objectives ......................................................................................................... 10-1 
Introduction ....................................................................................................... 10-1 
Bill of Materials ................................................................................................. 10-3 
Routes .............................................................................................................. 10-8 
Production Orders .......................................................................................... 10-11 
Scheduling ...................................................................................................... 10-26 
Planned Production Orders ............................................................................ 10-31 
LEAN Manufacturing ...................................................................................... 10-33 
Process Industries .......................................................................................... 10-37 
Lab 10.1 - Bill of Material ................................................................................ 10-39 
Summary ........................................................................................................ 10-42 
Test Your Knowledge ..................................................................................... 10-43 
Quick Interaction: Lessons Learned ............................................................... 10-44 
Solutions ......................................................................................................... 10-45 
Chapter 11: Workflow 11-1 
Objectives ......................................................................................................... 11-1 
Introduction ....................................................................................................... 11-1 
Line-Item Workflows ......................................................................................... 11-2 
Workflow Providers .......................................................................................... 11-4 
Work Item Queues ......................................................................................... 11-10 
Currency in the Condition Editor..................................................................... 11-16 
Hierarchy Type Fields in the Condition Editor ................................................ 11-22 
Lab 11.1 - Workflow Workshop ...................................................................... 11-25 
Summary ........................................................................................................ 11-37 
Test Your Knowledge ..................................................................................... 11-38 
Quick Interaction: Lessons Learned ............................................................... 11-40 
Solutions ......................................................................................................... 11-41 
Chapter 12: Reporting 12-1 
Objectives ......................................................................................................... 12-1 
Introduction ....................................................................................................... 12-1 
Reporting Features Overview ........................................................................... 12-2 
Report Data Overview ...................................................................................... 12-4 
Creating Basic Reports from a Query............................................................... 12-8 
Lab 12.1 - Report Workshop .......................................................................... 12-21 
Create a Precision Design Report from a Report Data Provider .................... 12-27 
Manage Report Execution by Using X++ ....................................................... 12-36 
Business Logic in Report Data Methods ........................................................ 12-43 
Print Management .......................................................................................... 12-46 
Summary ........................................................................................................ 12-55 
Test Your Knowledge ..................................................................................... 12-56 
Quick Interaction: Lessons Learned ............................................................... 12-58 
Solutions ......................................................................................................... 12-59 

iv
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Introduction

INTRODUCTION
Welcome
We know training is a vital component of retaining the value of your Microsoft
Dynamics® AX 2012. investment. Our quality training from industry experts
keeps you up-to-date on your solution and helps you develop the skills necessary
for fully maximizing the value of your solution. Whether you choose Online
Training, Classroom Training, or Training Materials; there is a type of training to
meet everyone's needs. Choose the training type that best suits you so you can
stay ahead of the competition.

Online Training
Online Training delivers convenient, in-depth training to you in the comfort of
your own home or office. Online training provides immediate access to training
24 hours-a-day. It is perfect for the customer who does not have the time or
budget to travel. Our newest online training option, eCourses, combine the
efficiency of online training with the in-depth product coverage of classroom
training, with at least two weeks to complete each course.

Classroom Training
Classroom Training provides serious, in-depth learning through hands-on
interaction. From demonstrations to presentations to classroom activities, you
receive hands-on experience with instruction from our certified staff of experts.
Regularly scheduled throughout North America, you can be sure you will find a
class convenient for you.

Training Materials
Training Materials enable you to learn at your own pace, on your own time with
information-packed training manuals. Our wide variety of training manuals
feature an abundance of tips, tricks, and insights you can refer to again and again:

Microsoft Dynamics Courseware


The Microsoft Dynamics Courseware consists of detailed training manuals,
designed from a training perspective. These manuals include advanced topics as
well as training objectives, exercises, interactions and quizzes.

Look for a complete list of manuals available for purchase on the Microsoft
Dynamics website: www.microsoft.com/Dynamics.

0-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Microsoft Dynamics Courseware Contents


Test Your Skills
Within the Microsoft Dynamics Training Materials you find a variety of different
exercises. These exercises are offered in three levels to accommodate the variety
of knowledge and expertise of each student. We suggest you try the level three
exercises first, if you need help completing the task look to the information in the
level two exercises. If you need further assistance each step of the task is outlined
in the level one exercise.

Challenge Yourself!
Level 3 exercises are the most challenging. These exercises are designed for the
experienced student who requires little instruction to complete the required task.

Need a Little Help?


Level 2 exercises are designed to challenge students, while providing some
assistance. These exercises do not provide step by step instructions, however, do
provide you with helpful hints and more information to complete the exercise.

Step by Step
Level 1 exercises are geared towards new users who require detailed instructions
and explanations to complete the exercise. Level 1 exercises guide you through
the task, step by step, including navigation.

Quick Interaction: Lessons Learned


At the end of each chapter within the Microsoft Dynamics Training Material, you
find a Quick Interaction: Lessons Learned page. This interaction is designed to
provide the student with a moment to reflect on the material they have learned.
By outlining three key points from the chapter, the student is maximizing
knowledge retention, and providing themselves with an excellent resource for
reviewing key points after class.

0-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Introduction

Documentation Conventions
The following conventions and icons are used throughout this documentation to
help you quickly and effectively navigate through the information.

CAUTION: Cautions are found throughout the training manual and are preceded by
the word CAUTION in bold. Cautions are used to remind you of a specific result of a
specific action which may be undesirable.

HINT: Hints are found throughout the training manual and are preceded by the word
HINT in bold. Hints are used to suggest time-saving features or alternative methods for
accomplishing a specific task.

NOTE: Notes are found throughout the training manual and are preceded by the word
NOTE in bold. Notes are used to provide information which, while not critical, may be
valuable to an end user.

BEYOND THE BASICS: Advanced information found throughout the training manual
is preceded by the words BEYOND THE BASICS in bold. Beyond the Basics provides
additional detail, outside of standard functionality, that may help you to more optimally
use the application.

EXAMPLE: Examples are found throughout the training manual and are preceded by
the word EXAMPLE in bold. Examples bring to light business scenarios that may better
explain how an application can be used to address a business problem.

0-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Student Objectives
What do you hope to learn by participating in this course?

List three main objectives below.

1.

2.

3.

0-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

CHAPTER 1: NUMBER SEQUENCES


Objectives
The objectives are:

• Describe the features of number sequences in Microsoft Dynamics®


AX 2012.
• Describe the steps for setting up and administering a number
sequence.
• Develop new number sequences by extending the
NumberSeqApplicationModule class.
• Use the Form Handler to create number sequences in a form.

Introduction
Number sequencing is a necessary feature in an Enterprise Resource Planning
(ERP) system. Microsoft Dynamics AX uses a number sequence framework to
generate alphanumeric number sequences. These sequences can be used for
transaction documents such as sales orders, purchase orders, invoices, and
journals; or for master data entities such as customers, vendors, and employees.
The primary purpose of the number sequence framework is to provide unique,
user-friendly identifiers while maintaining a continuous or non-continuous
alphanumeric sequence.

This course is designed to explain how developers can perform customizations


using the number sequence framework. However, administrators may be
interested in the "Setup and Administration of Number Sequences" topic, which
describes how to configure and set up number sequences using the new number
sequence administration forms.

1-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Overview
Microsoft Dynamics AX 2012 introduces two concepts to the number sequence
framework: segment and scope. A segment, which is synonymous with
parameter, is a data entity such as a legal entity, operating unit, or fiscal calendar
period that can be used to define a number sequence. In the enhanced number
sequence framework, a number sequence can have more than one segment. A
scope is a valid combination of segments used for a specific transaction or master
data entity. By using segment and scope, Microsoft Dynamics AX 2012 extends
the capabilities of the number sequence framework.

All segments in a scope must be related to the underlying transaction or master


data entity. For example, a journal transaction will have a relationship with the
segments of a legal entity and fiscal calendar period (through the transaction or
posting date) that make up its scope. The scope can be used to partition the entity
instances or transactions based on the segment values. In this example, a journal
transaction might be partitioned into categories based on the two segments in its
scope.

A unique number sequence code must be created for every possible combination
of legal entity and fiscal calendar period instances. For example, if there are two
legal entities with IDs 10 and 20, and there are fiscal calendar periods for every
calendar month in 2011, the user must define separate number sequences for each
combination. An example of a scope instance is 20-Jan11. An example of a
number sequence code for a journal might be JN-J-20-Jan11, in which JN
represents a journal. The number sequence format, J-20-Jan11, is a string that is
defined by the end-user to represent the identifier for the transactions for legal
entity 20 and fiscal calendar period January 2011. The actual instance of a
journal might have a generated number sequence such as J-20-Jan11-000340.
(The last number in the sequence, "000340," is a system-generated number.)

The concept of a number sequence reference, which is synonymous with an


extended data type, is carried forward from Microsoft Dynamics® AX 2009.
When you create a number sequence, you must first create an extended data type
(EDT) with a label-such as SalesOrderID-for the new number sequence. The
label of this EDT is used as a reference. This reference is used to define a field on
a document or master data entity that requires a number sequence.

Supported Scopes
Microsoft Dynamics AX 2012 will convert a subset of existing transactions and
master data entities so they can use scopes such as a legal entity or global scope.
This enables Microsoft Dynamics AX 2012 to ship with predefined scopes for
this subset of entities. The rest of the data entities still have a default scope of
DataArea (or company).

1-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Microsoft Dynamics AX 2012 does not currently support an arbitrary


combination of segments as a valid scope. The following are the only scopes that
are currently valid in the number sequence framework:

• DataArea (or company)


• DataArea and fiscal calendar period
• Legal entity
• Operating unit
• Legal entity and fiscal calendar period
• Legal entity and operating unit

TIP: Use the Legal entity scope when the underlying table does not include the
DataAreaID field and has a foreign key to the legal entity table, CompanyInfo.
For example, use this scope for the number sequence for the expense report
number that is in the expense report table, TrvExpTable.

Although the scope is predefined for a data entity, the segments within that scope
are configurable. This means if a scope consists of a legal entity and fiscal
calendar period, a user can decide to configure the scope to be only a legal entity
during implementation. However, there are some mandatory restrictions on scope
composition. If, for example, a fiscal calendar period is selected as part of a
scope, the inclusion of DataArea or legal entity is mandatory in that scope.

One limitation of the new number sequence framework is that the scope must
always be configured for a specific reference. You cannot define a scope based
on variations in the data. For example, suppose that the regulatory requirements
in France and China require you to generate a number sequence by using the
legal entity and fiscal calendar period segments. However, other countries or
regions might not have the same requirements. The administrator in a
multinational corporation might decide that it is not necessary to include both
segments for all countries or regions. However, you cannot define two different
scopes—one to be used in France and China that includes legal entity and fiscal
calendar period segments, and another to be used in all other countries or regions
that includes only the legal entity segment. You could use the framework in such
a way that all countries or regions have the scope of legal entity and fiscal
calendar period, but display the number sequence format based on both segments
only in France and China. However, the numbers generated would still be
partitioned based on both segments in all companies.

A second limitation is that no references are provided out-of-the box that has a
fiscal calendar period segment. Extending the framework to include a fiscal
calendar period currently requires customization of existing parameters forms in
specific modules. The new Number sequences setup form does support a fiscal
calendar segment.

1-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Set Up and Administration


When an end-user creates a document such as a sales order, purchase order, or
invoice, the extended data type on the document field—such as SalesOrderID or
InvoiceID—is passed to the number sequence framework. Additionally,
information is passed for the segments such as DataArea, or a legal entity plus
fiscal calendar period, depending on the scope for the reference.

The framework then generates a number sequence code based on these


parameters (segments), and this number sequence code is used to generate a
number based on the format for the corresponding number sequence.
Specifying a number sequence is now done in two steps: segment configuration
and setup.

With the Microsoft Dynamics AX 2012 number sequences framework, you can
use multiple segments, but legacy number sequence references do not support
this new capacity. Customers and partners who plan to perform customizations to
enable new segments, based on the new capabilities of the framework, will have
to use the Segment configuration form. This form can be used to view or
modify the default configuration of segments included out of the box.

Segment Configuration
An administrator can configure the segments that are allowed for his or her
requirements. For example, out of the box, the application could allow for two
segments such as legal entity and fiscal calendar period. However, only the legal
entity segment might be included by default. The administrator can enable both
segments for their scenario by using the Segment configuration form.

In Microsoft Dynamics AX 2012, most references use either DataArea (or


company) or legal entity segments out of the box. There are several references
for master data entities that are shared across the application and do not use
segments. However, the framework allows an administrator to add segments such
as the fiscal calendar period.

1-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

To define the segment configuration, open Organization Administration >


Common > Number sequences > Segment configuration.

FIGURE 1.1 SEGMENT CONFIGURATION FORM

Most references use either Company or Legal entity scope segments. By


default, references for master data entities that are shared across the application
do not use scope segments.

NOTE: You cannot modify scope segments for a number sequence that is
currently being used. It is not sufficient to stop the use of number sequences with
a scope segment that you need to modify. You must delete any number sequences
that are based on the current configuration before you can modify the scope
segments for a reference.

1-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Set Up Number Sequences


The existing number sequences can be viewed by using the Number sequences
list page. The navigation path to this page is Organization administration >
Common > Number sequences > Number sequences. The following figure
shows the Number sequences list page.

FIGURE 1.2 NUMBER SEQUENCES LIST PAGE

You can use the Area, Reference, and Company drop-down lists to filter the
data that is displayed in the form.

TIP: The Company filter field only appears after you have selected an Area and
a Reference.

You can set up all required number sequences at the same time by using the Set
up number sequences wizard by clicking Generate in the New group of the
Action Pane, or you can create or modify individual number sequences by using
the Number sequences form.

1-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Procedure: Set Up Number Sequences by Using the


Wizard
You can use the Set up number sequences wizard to automatically create
number sequences. The wizard generates number sequences for all references in
all organizations for which number sequences are not yet defined. You cannot
use the wizard to generate number sequences for a subset of the areas or
references that require number sequences. You cannot use the wizard to modify
existing number sequences. To use the wizard to set up number sequences,
follow these steps.

• Open Organization administration > Common > Number


sequences > Number sequences. Then click Generate in the New
group of the Action Pane.
• On the Welcome page, click Next >.
• The Setup page is displayed. On this page, you can modify the
Identification code, the Lowest value, and the Highest value.
Additionally, you can indicate whether the number sequence must be
Continuous.

IMPORTANT: Do not select the Continuous option if you must preallocate


numbers for the number sequence.

• To add a scope segment to the format of a number sequence, select


the format in the list, and then click Include scope in format. To
remove a scope segment from the format of a number sequence,
select the format in the list, and then click Remove scope from
format.
• To exclude a number sequence from automatic generation, select the
number sequence in the list, and then click Delete.
• Click Next >.
• On the Completed page, verify the information, and then click
Finish.

NOTE: In the Hyper-V training environment, all number sequences are set up.
Therefore, you cannot run the wizard unless you first delete some number
sequences.

Procedure: Set Up Number Sequences Manually


You can use the Number sequences page to create or modify selected number
sequences. To manually create number sequences, follow these steps.

• Click Organization administration > Common > Number


sequences > Number sequences.
• Click Number sequence in the New group of the Action Pane

1-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• On the Identification FastTab, enter an identification code and a


name for the number sequence.
• On the Scope parameters FastTab, select a scope for the number
sequence and select scope values. The scope defines which
organizations use the number sequence. Additionally, number
sequences that have a scope other than Shared can have segments
that correspond to their scope. For example, a number sequence with
a scope of Legal entity can have a legal entity segment. By default,
the following scopes are available:

a. Shared: A single number sequence is used for all organizations.


b. Company: A separate number sequence is used for each
company.

TIP: Use the Company scope when the underlying table includes the DataAreaId
field. For example, use this scope for the number sequence for the customer
account number in the customer table, CustTable.

c. Legal entity: A separate number sequence is used for each legal


entity.

TIP: Use the Legal entity scope when the underlying table does not include the
DataAreaId field and has a foreign key to the legal entity table, CompanyInfo.
For example, use this scope for the number sequence for the expense report
number that is in the expense report table, TrvExpTable.

d. Operating unit - A separate number sequence is used for each


operating unit.
e. Company and Fiscal calendar period - A separate number
sequence is used for each company and fiscal calendar period
combination.
f. Legal entity and Fiscal calendar period - A separate number
sequence is used for each legal entity and fiscal calendar period
combination.

• On the Segments FastTab, define the format for the number


sequence by adding, removing, and rearranging segments. Number
sequences of all scopes can contain Constant segments and
Alphanumeric segments.

Constant segments contain a set of alphanumeric characters that do not


change. Use this segment type to add a hyphen or other separator
between number sequence segments.

1-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Alphanumeric segments contain a combination of number signs (#) and


ampersands (&). These characters represent letters and numbers that
increment every time that a number from the sequence is used. Use a
number sign (#) to indicate incrementing numbers and an ampersand (&)
to indicate incrementing letters. For example, the format #####_2014
creates the sequence 00001_2014, 00002_2014, and so on. At least one
alphanumeric segment must be present. Scope segments, such as
company or legal entity, are optional. However, even if you do not
include scope segments in the format, numbers for the selected reference
are still generated for each scope.

• On the References FastTab, select the document type or record to


assign this number sequence to. This step is optional for sequences
that are defined for special application usage patterns. In these
scenarios, a new number is generated by using the value of a number
sequence code or ID, without using a reference. An example of a
special application usage pattern is a voucher series that is used for
specific journal names. However, the recommendation is not to use
such patterns.
• On the General FastTab, specify whether the number sequence is
manual, and continuous or non-continuous. Additionally, enter the
lowest and highest numbers that can be used in the number sequence.
• Save the number sequence and close the form.

Administration
The administration of number sequences is performed by using actions provided
in the Administration group on the Action Pane on the Number sequences list
page.

• Status list: Provides a list of numbers that are generated for


continuous number sequences, but which are not committed to the
database. The numbers are either currently being used in a user
session, are reserved for future use in a user session, or are free for
use if a new client user session requests a new number for a
particular number sequence in the list. If a new number does not
exist for a specific continuous number sequence, it is generated by
the sequence number framework from the next value for that number
sequence in the Number sequence table (NumberSequenceTable).
• Manual cleanup: Allows the administrator to manually clean up
numbers in the status list. Use of this option is only recommended
after an unexpected system failure; in such rare circumstances,
numbers might not be automatically cleaned up.
• History: Provides the history of the changes to the number
sequences.

1-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Several administrator tasks can be performed from the Details page. An


administrator can, for example, schedule an automated periodic cleanup for every
number sequence by entering intervals on the Automatic cleanup FastTab.

An administrator can also assign number sequences by using a page in the


parameter forms in individual application modules. For example, you can view or
assign the number sequences to specific references in the General ledger module.
You can open the form by using the path General ledger > Setup > General
ledger parameters.

Extensibility Scenarios
This section is primarily intended for developers who want to call an API that
extends the NumSeqApplicationModule class to handle changes that are required
by the enhanced number sequence framework. This API is called to create new
fields on documents or master data entities that will use a number sequence.

In a common extensibility scenario, a developer creates new fields and makes use
of the new number sequence framework to generate values for those fields. There
are two main extensibility scenarios:

• Company scenario: Based on the default segment of DataArea (or


company).
• Organization model and regulatory scenario: Based on the use of
new segments such as legal entity, operating unit, and fiscal calendar
period.

The Microsoft Dynamics AX 2012 number sequence framework does not


currently support an extensibility scenario to add arbitrary segments such as a
warehouse or a site as a segment in the definition of a number sequence for a
reference. That kind of extensibility would require significant customization to
the number sequence framework.

In all extensibility scenarios, the assumption is that the developer is trying to set
up a new module, has already defined a field in a table, and is using the new
number sequence framework to generate values for that field.

A developer would typically follow these steps:

• Make changes to support the new extended data type that


corresponds to the new field in the table.
• Call the API to generate the values by using the number sequence for
that field.

1-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Scenario: Create a Number Sequence with a Company


Scope
Isaac, the Business Application Developer, is developing a new module in
Microsoft Dynamics AX for Fleet management. The module will require two
new number sequences: one for the vehicle numbers, and one for the trip
numbers.

He has already created a new extended data type, and the tables that will store the
vehicles and trip information. Now he must modify the NumberSeqModule base
enumeration, and create a new class that extends the
NumberSeqApplicationModule class that will store the information about the two
number sequences.

When it is finished, he must modify the Fleet management parameters form to


have a Number Sequences tab, and add the references so that the administrator
can set up the number sequences.

Procedure: Modify the NumberSeqModule Base


Enumeration
To add Fleet management as a module in the number sequences base
enumeration, follow these steps.

• Open the Development Workspace.


• In the Application Object Tree (AOT) window, expand Data
Dictionary > Base Enums.
• Select the NumSeqModule base enumeration.
• Right-click the element and select New Element.
• Right-click the new element (this is named Element 1 by default) and
select Properties.
• In the Name field, enter a name such as FleetManagement.
• In the Label field, create or select a label such as "Fleet
management".
• Optionally, you can add a configuration key if it might be required to
disable the Fleet management functionality in certain installation.
• Click the Save all icon to save the changes.

TIP: Make sure that you add the base enumeration and any other objects that
you create or modify to a project. This makes the promotion of changes to a
testing or production environment easier.

NOTE: An element for FleetManagement exists in the training environment by


default.

1-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Extend the NumberSeqApplicationModule


Class
To create a new class for Fleet management, that extends the
NumberSeqApplicationModule class and stores the two number sequences for
the Fleet management module, follow these steps.

• Open the Development Workspace.


• In the AOT window, expand Classes.
• Right-click the Classes node and then select New Class.
• Right-click the newly created class and select Properties.
• Enter a name for the class following the naming standard
NumberSeqModuleXXX where XXX represents the name of the
module such as, NumberSeqModuleFleetManagement.
• Make sure that the new class extends the
NumberSeqApplicationModule, and then use the following code
sample for the class.

Class declaration
public class NumberSeqModuleFleetManagement extends
NumberSeqApplicationModule
{

protected void loadModule()


{
NumberSeqDatatype datatype =
NumberSeqDatatype::construct();

/* Vehicle Number */
datatype.parmDatatypeId(extendedtypenum(FMVehicleId));
datatype.parmReferenceHelp("Unique key for Fleet
Management vehicles");
datatype.parmWizardIsContinuous(false);
datatype.parmWizardIsManual(NoYes::No);
datatype.parmWizardIsChangeDownAllowed(NoYes::No);
datatype.parmWizardIsChangeUpAllowed(NoYes::No);
datatype.parmWizardHighest(999999);
//Use the DataArea segment

datatype.addParameterType(NumberSeqParameterType::DataArea,
true, false);

this.create(datatype);

/* Rental Number */
datatype.parmDatatypeId(extendedtypenum(FMRentalId));
datatype.parmReferenceHelp("Unique key for rentals");
datatype.parmWizardIsContinuous(false);

1-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

datatype.parmWizardIsManual(NoYes::No);
datatype.parmWizardIsChangeDownAllowed(NoYes::No);
datatype.parmWizardIsChangeUpAllowed(NoYes::No);
datatype.parmWizardHighest(999999);
//Use the DataArea segment

datatype.addParameterType(NumberSeqParameterType::DataArea,
true, false);

this.create(datatype);
}

public NumberSeqModule numberSeqModule()


{
return NumberSeqModule::FleetManagement;

• Right-click the Data Dictionary node in the AOT, and then select
Synchronize.

TIP: Notice that the DataArea segment describes the default segment for the
extended data types that are used for both vehicle number and trip number.

IMPORTANT: You will have to synchronize the database after you create a new
class that extends the NumberSeqApplicationModule class. This may take several
minutes to complete.

Procedure: Create a Number Sequences Page in the


Parameters Form of the New Module
Next, you must create or modify a Number sequences page on the FMSetup
form for the new Fleet management module. This requires you to override the
numberSeqPreInit method.

You can refer to existing forms such as CustParameters or LedgerParameters for


examples of the implementation. The following is sample code for the
numberSeqPreInit method on the form for Fleet management.

void numberSeqPreInit()
{
numberSequenceModules =
[NumberSeqModule::FleetManagement];
numberSeqApplicationModule = new
NumberSeqModuleFleetManagement();
scope = NumberSeqScopeFactory::createDataAreaScope();

NumberSeqApplicationModule::createReferencesMulti(numberSeq
uenceModules, scope);
tmpIdRef.setTmpData

1-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

(NumberSequenceReference::configurationKeyTableMulti(number
SequenceModules));
}

NOTE: This form can only be used for references that have a scope of DataArea.
The administration forms described in the “Set Up and Administration” topic
can be used for references that have any scope. These forms can be found in
Organization Administration > Common > Number Sequences.

TIP: You must add several variable declarations to the class declaration of the
form that you are modifying for the code sample provided to compile. Use the
following code sample to guide you.

NumberSeqReference numberSeqReference;
NumberSeqScope scope;
NumberSeqApplicationModule numberSeqApplicationModule;
container numberSequenceModules;
TmpIdRef tmpIdRef;

Procedure: Add a Method on the Parameters Table for


Vehicle Numbers
Next you must use the Number Sequence API in business logic on the parameters
form (FMSetup) so that the number sequence references will appear. Use the
following code sample in the new method.

Public server static NumberSequenceReference


numRefVehicleID()

// Optional step for DataArea scope, mandatory for


other scopes

NumberSeqScopeFactory::CreateDataAreaScope();

return
NumberSeqReference::findReference(extendedtypenum
(FMVehicleID));

NOTE: A FleetManagementParameters table does not exist in the training


environment by default. You can create one, or alternatively use one of the tables
in the FMSetup form.

1-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

You must repeat this process and create a second method for the trip
identification number on the FMSetup form.

Procedure: Add a Table Method for Creating New Vehicle


Numbers
Next, you must add a method to the FMVehicle table for creating a new number.
Use the following code as an example for creating a new vehicle ID.

Void setVehicleID()
{
NumberSeq num;
NumberSequenceReference numberSequenceReference;
numberSequenceReference =
FleetManagementParameters::numRefVehicleID();
if (numberSequenceReference)
{
num = NumberSeq::newGetNum(numberSequenceReference);
this.VehicleID = num.num();
}
}

NOTE: You must repeat this process for each number sequence.

Scenario: Create a Number Sequence with the


Organizational Model
Isaac, the Business Application Developer, is developing a new module in
Microsoft Dynamics AX for Fleet management. The module will require two
new number sequences: one for the vehicle numbers, and one for the rental
numbers.

He has created the classes for storing the number sequences and the code that is
required for the vehicle numbers already. He wants to make the trip ID number
sequence include the data area ID and the fiscal calendar period segments.

Now he must update the code to allow for the additional segments on the rental
ID number sequence.

1-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Modify the loadModule() Method


For each extended data type that needs to be generated by the number sequences
API, additional lines of code must be added to the loadModule() method inside of
the NumberSeqModuleFleetManagment class already created in the "Extend the
NumberSeqApplicationModule Class" procedure. The code is used to add the
second segment. Use the following code sample to guide you.

...
/* Rental Number */
datatype.parmDatatypeId(extendedtypenum(FMRentalID));
datatype.parmReferenceHelp("Unique key for trips");
datatype.parmWizardIsContinuous(false);
datatype.parmWizardIsManual(NoYes::No);
datatype.parmWizardIsChangeDownAllowed(NoYes::No);
datatype.parmWizardIsChangeUpAllowed(NoYes::No);
datatype.parmWizardHighest(999999);
datatype.addParameterType(NumberSeqParameterType::DataArea,
true, false);

//Additional line of code for second segment added here:


datatype.addParameterType(NumberSeqParameterType::FiscalCal
endarPeriod, true, false);
this.create(datatype);

NOTE: The code sample only includes a section of the loadModule() method.

If you want to additional segments, you must add another call to the
addParameterType() method before the call to the create() method.

Procedure: Add a Method on the Parameters Table for


Rental IDs
You have to create an instance of the scope for the two segments of DataArea (or
company), and fiscal calendar period, and call the API with these two segments
passed as parameters to the number sequence framework. The sample code for
the Rental ID is as follows:

Public server static NumberSequenceReference


numRefRentalID(TransDate _date = systemdateget())
{
NumberSeqScope scope =
NumberSeqScopeFactory::CreateDataAreaFiscalCalendarPeriodSc
ope(
curext(),FiscalCalendars::findPeriodByPeriodCodeDate
(CompanyInfo::fiscalCalendarRecId(),_date).RecId);
return
NumberSeqReference::findReference(extendedtypenum(FMRentalI
D), scope);
}

1-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

NOTE: A FleetManagementParameters table does not exist in the training


environment by default. You can create one, or alternatively use any of the tables
in the FMSetup form.

Procedure: Add a Table Method for Creating Rental IDs


Next, you must add a method to the table to create a new number. Use the
following code as an example to create a new trip ID.

Void RentalID()
{
NumberSeq num;
NumberSequenceReference numberSequenceReference;
numberSequenceReference =
FleetManagementParameters::numRefRentalID();
If(numberSequenceReference)
{
num =
NumberSeq::newGetNum(numberSequenceReference);
this.RentalId = num.num();
}
}

NOTE: A FleetManagementParameters table does not exist in the training


environment by default. You can create one, or alternatively use any of the tables
in the FMSetup form.

Scenario: Change the Scope for an Existing Reference


In this scenario, a developer is changing the scope of an existing reference.

Isaac, the Business Application Developer wants to change the vehicle number to
be global (or shared). The existing reference, FMVehicleID, has the scope of the
DataArea segment. But the developer wants to change this to the global scope.
The changes that are required to achieve this resemble those that are described in
the previous section.

First, Isaac must remove the call to the addParameterType() method in the
NumSeqModuleFleetManagment.loadModule() method for the vehicle ID. Then,
he must update the NumberSequenceReference method on the Fleet management
parameters table to create a global scope.

1-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Modify the loadModule() Method


When you use the global scope for a number sequence, you do not have to
include a call to the addParameterType() method. Use the following code sample
when you create the global number sequence.

protected void loadModule()


{
NumberSeqDatatype datatype =
NumberSeqDatatype::construct();

/* Vehicle Number */
datatype.parmDatatypeId(extendedtypenum(FMVehicleID));
datatype.parmReferenceHelp("Unique key for Fleet
Management vehicles");
datatype.parmWizardIsContinuous(false);
datatype.parmWizardIsManual(NoYes::No);
datatype.parmWizardIsChangeDownAllowed(NoYes::No);
datatype.parmWizardIsChangeUpAllowed(NoYes::No);
datatype.parmWizardHighest(999999);
//No longer need the Data Area Scope

//datatype.addParameterType(NumberSeqParameterType::DataAre
a, true, false);

this.create(datatype);

...

NOTE: In the code sample provided, the call to the addParameterType() method
is commented out. Also notice that the sample provided is only a part of the
method.

Procedure: Modify the numRefVehicleID() Method


The numRefVehicleID method on the FleetManagementParameters table must be
updated to create a number sequence reference with a global scope. Replace the
previous code with the following sample.

Public server static NumberSequenceReference


numRefVehicleNumber()
{
NumberSeqScopeFactory::CreateGlobalScope();
return
NumberSeqReference::findReference(extendedtypenum
(FMVehicleID));
}

1-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Using Number Sequences in Forms


To use the number sequence for a form in Microsoft Dynamics AX, or in the
Enterprise Portal, you will typically add code to the data source for the form or
dataset. You can also retrieve a number sequence value directly in code.

Scenario: Use Number Sequences in a Form


Isaac, the Business Application Developer, is developing a new module in
Microsoft Dynamics AX for Fleet management. He has created the new number
sequences and set up the number sequence on the parameters form. Now, he
wants to have the system automatically retrieve the next vehicle number when a
user inserts a new record into the Vehicle form.

Procedure: Implement the Number Sequence Form


Handler
To set up a form to correctly handle the creation and update of a number
sequence in a form, you must insert and update the number sequence when the
form is closed or the record is deleted. Use the following code samples when you
implement the number sequence form handler. For this example, it is assumed
that you have a table and form data source named FMVehicle which has a field
named VehicleId.

Start by declaring the NumberSeqFormHandler in the class declaration of the


form.

public class FormRun extends ObjectRun


{
NumberSeqFormHandler numberSeqFormHandler;
}

Next, create a new method called numberSeqFormHandler. This method should


call the static method newForm() on the numberSeqFormHandler class. Make
sure that you pass in the number sequence reference from your parameters table,
the data source which stores the number, and the table and field that will hold the
number that is generated. Use the following code sample to guide you.

1-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

NumberSeqFormHandler numberSeqFormHandler()
{
if (!numberSeqFormHandler)
{
numberSeqFormHandler =
NumberSeqFormHandler::newForm(FleetManagementParameters::nu
mRefVehicleNumber().NumberSequenceId,

element,

FMVehicle_DS,

fieldNum(FMVehicle, VehicleID));
}
return numberSeqFormHandler;
}

Next you must override the create() method on the data source where the number
will be populated. Use the following code sample to guide you.

void create(boolean append = false,


boolean extern = false) // If created
externally
{

element.numberSeqFormHandler().formMethodDataSourceCreatePr
e();

super(append);

if (!extern)
{

element.numberSeqFormHandler().formMethodDataSourceCreate(t
rue);
}
}

The formMethodDataSourceCreatePre() method is used to validate that there is a


last number on the number sequence. The call to this method must be positioned
before the call to super().

The formMethodDataSourceCreate() method is used to create a record with a


number sequence value. The call to this method must be positioned after the call
to super().

1-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

The next step is to override the validateWrite() and write() methods on the data
source where the number sequence is being inserted into. Use the following code
samples to guide you.

public boolean validateWrite()


{
boolean ret;
ret = super();
ret =
element.numberSeqFormHandler().formMethodDataSourceValidate
Write(ret) && ret;
return ret;
}

void write()
{
ttsbegin;
super();

element.numberSeqFormHandler().formMethodDataSourceWrite();
ttscommit;
}

Next, you must override the delete() method on the data source where the number
sequence is being inserted. This is an important step that will make sure the
number sequence is canceled and deleted when a record is deleted from your
form that has a number sequence.

void delete()
{
ttsbegin;

element.numberSeqFormHandler().formMethodDataSourceDelete()
;
super();
ttscommit;
}

The last step is to override the close() method on the form to make sure that the
number sequence is canceled when the form is closed. Use the following code
sample to guide you.

void close()
{
if (numberSeqFormHandler)
{
numberSeqFormHandler.formMethodClose();
}
super();
}

1-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 1.1 - Implement a New Number Sequence


This lab demonstrates how to implement a new number sequence reference.

Estimated time to complete: 20 minutes

Scenario

Isaac, the Business Application Developer, is developing a new feature in the


Accounts receivable module for tracking customer contracts. The new customer
contracts feature will be used to track the details and terms for multiple contracts
on customers account.

Challenge Yourself!
Isaac must implement a new number sequence for the customer contract ID. He
has already created a new extended data type(CustContractID), contract table
(CustContract), and form (CustContract) to store all the contract information.
Now you must create a new number sequence reference and add it into the
Accounts receivable parameters form. Make sure that you set up the number
sequence format and select it in the Accounts receivable parameters form.

When you are finished, implement the Form Handler on the CustContract form
and make sure that the system will populate the customer contract ID
automatically with the new number sequence when you are finished.

IMPORTANT: You must import the AX2012_ENUS_DEVIV_LAB.xpo file which


is located on the local drive of the training image before starting this lab.

Need a Little Help?

1. Import the NumberSequencesLab1_CustContract.xpo file which is


located on the local drive of the training image.
2. Modify the loadModule() method on the
NumberSeqModuleCustomer class to include a new number
sequence reference for the customer contract ID.
3. Create a new static method on the CustParameters table to find the
number sequence reference.
4. Set up the new Customer contract ID number sequence reference in
the Organization administration module, and then select it on the
Accounts receivable parameters form.
5. Create a new table method on the CustContract table to generate a
new contract ID.
6. Declare the NumberSeqFormHandler class in the CustContract form.
7. Create a new numberSeqFormHandler() method in the CustContract
form to create an instance of the numberSeqFormHandler class for
the custContractID number sequence reference.

1-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

8. Override the create() method on the CustContract data source inside


the CustContract form.
9. Override the write() and validateWrite() methods on the
CustContract data source in the CustContract form.
10. Override the delete() method on the CustContract data source in the
CustContract form to make sure the number sequence is cancelled
when the record is deleted.
11. Override the close() method of the CustContract form to make sure
the number sequence is cancelled when the form is closed.
12. Open the CustContract form and insert a new record to verify that
the Contract ID number is automatically populated.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_01_01_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

Step by Step: Import the Customer Contract Project


Follow these steps to import the Customer Contract project file.

1. Open the Development workspace.


2. Click Command > Import.
3. On the Import dialog box, click Browse....
4. Browse to
E:\\80313_DevelopmentIV_XPOFiles.zip\80313_DevelopmentIV_X
POFiles\AX2012_ENUS_DEVIV_01_01_LAB.xpo
5. Click Open.
6. Click OK.
7. Close the Compiler output window when the file is finished
importing.

NOTE: You may need to extract the files in the


80313_DevelopmentIV_XPOFiles.zip folder first. You can do this by right-
clicking on the folder and selecting Extract All....

Step by Step: Modify the loadModule() Method


To modify the code in the loadModule() method, follow these steps.

1. Open the Projects window.


2. Locate the NumberSequenceLab1_CustContract project that was
created by the import, and then double-click it to open it.
3. Close the Projects window.
4. In the AOT window, expand Classes.
5. Expand the Classes node and then expand
NumberSeqModuleCustomer class.

1-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. Drag the class into the Project


NumberSequenceLab1_CustContract window.
7. Save the project.
8. Expand the NumberSeqModuleCustomer in the project and then
right-click on the loadModule() method and select View code.
9. Add the following code to the end of the method:

/* Customer Contract ID*/

datatype.parmDatatypeId(extendedtypenum(CustContractID));
datatype.parmReferenceHelp("Unique key for Customer
Contracts");
datatype.parmWizardIsContinuous(false);
datatype.parmWizardIsManual(NoYes::No);
datatype.parmWizardIsChangeDownAllowed(NoYes::No);
datatype.parmWizardIsChangeUpAllowed(NoYes::No);
datatype.parmWizardHighest(999999);

datatype.addParameterType(NumberSeqParameterType::DataArea,
true, false);

this.create(datatype);

10. Click Save, and then close the Code Editor window.
11. Right-click the Data Dictionary node in the AOT window, and then
click Synchronize.

NOTE: The Synchronize process can take several minutes to finish.

Step by Step: Modify the Parameters Table


To create a new method on the CustParameters table to find the number sequence
reference for customer contract IDs, follow these steps.

1. In the AOT window, expand Tables.


2. Expand the Tables node and then expand the CustParameters table.
3. Drag the table into the NumberSequenceLab1_CustContract project.
4. Save the project.
5. Expand the CustParameters in the project and then right-click on the
Methods node and select New Method.
6. Add the following code to the method.

1-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Public server static NumberSequenceReference


numRefContractID()
{
return
NumberSeqReference::findReference(extendedtypenum
(CustContractID));
}

7. Save the method, and then close the Code Editor window.

Step by Step: Configure the Customer Contract Number


Sequence
To configure the customer contract ID number sequence, follow these steps.

1. In the Microsoft Dynamics AX 2012 client, open Organization


administration > Common > Number sequences > Number
sequences.
2. Click Number sequence in the New group of the Action Pane
3. On the Identification FastTab, enter Contract in the Number
Sequence and Customer Contract ID in the Name field.
4. Click the Scope parameters FastTab.
5. Select Company in the Scope field.
6. Select CEU in the Company field.
7. Click the Segments FastTab.
8. Click Add.
9. Select the Company segment in the grid, and then click Remove.
10. Select the Constant segment in the grid, and then change the Value
field to C. The Format field should now be C######.
11. Click the Reference FastTab.
12. Click Add.
13. Select Accounts receivable in the Area field.
14. Select Contract in the Reference field.
15. Click OK.
16. Close the Number sequences form.

1-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Step by Step: Add a Method to the Customer Contract


Table
To create a new method on the CustContract table to create a new number
sequence, follow these steps.

1. Open the Development Workspace.


2. In the AOT window, expand Tables.
3. Expand the Tables node and then select the CustContract table.
4. Drag the CustContract table into the
NumberSequenceLab1_CustContract project.
5. Save the project.
6. Expand the CustContract in the project and then right-click the
Methods node and select New Method.
7. Add the following code to the method.

Void setCustContractID()
{
NumberSeq num;
NumberSequenceReference numberSequenceReference;
numberSequenceReference =
CustParameters::numRefContractID();
if (numberSequenceReference)
{
num =
NumberSeq::newGetNum(numberSequenceReference);
this.custContractID = num.num();
}
}

8. Save the method, and then close the Code editor window.

Step by Step: Implement the Number Sequence Form


Handler
To implement the number sequence form handler on the CustContract form,
follow these steps.

1. In the AOT window, expand Forms.


2. Expand the Forms node and then expand the CustContract form.
3. Expand the CustContract form, expand the Methods node, and then
right-click the Class Declaration and click View Code.
4. Add the following code to the method.

1-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

public class FormRun extends ObjectRun


{
SysFormSplitter_X verticalSplitter;

NumberSeqFormHandler numberSeqFormHandler;
}

5. Save the method and then close the Code Editor window.

To instantiate the number sequence form handler class in the customer contract
form, follow these steps.

6. Right-click the Methods node of the CustContract form in the


AOT window, and then click New Method.
7. Add the following code into the new method.

NumberSeqFormHandler numberSeqFormHandler()
{
if (!numberSeqFormHandler)
{
numberSeqFormHandler =
NumberSeqFormHandler::newForm(CustParameters::numRefContrac
tID().NumberSequenceId,
element,

custContract_DS,

fieldNum(CustContract, CustContractID));
}
return numberSeqFormHandler;
}

8. Save the method and then close the Code Editor window.

To override the create() method, follow these steps.

9. Expand the Data Sources node of the CustContract form in the


AOT.
10. Expand the CustContract data source and then right-click the
Methods node of the data source, and select Override Method.
11. Select Create from the list.
12. Add the following code into the create method.

void create(boolean append = false,


boolean extern = false) // If created
externally
{

element.numberSeqFormHandler().formMethodDataSourceCreatePr
e();

1-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

super(append);

if (!extern)
{

element.numberSeqFormHandler().formMethodDataSourceCreate(t
rue);
}
}

13. Save the method and then close the Code Editor window.

To override the write() method, follow these steps.

1. Expand the Data Sources node of the CustContract form in the


AOT.
2. Expand the CustContract data source and then right-click the
Methods node of the data source, and select Override Method.
3. Select Write from the list.
4. Add the following code into the write method.

void write()
{
ttsbegin;
super();

element.numberSeqFormHandler().formMethodDataSourceWrite();
ttscommit;
}

5. Save the method and then close the Code Editor window.

To override the validateWrite() method, follow these steps.

1. Expand the Data Sources node of the CustContract form in the


AOT.
2. Expand the CustContracts data source and then right-click the
Methods node of the data source, and select Override Method.
3. Select validateWrite from the list.
4. Add the following code into the validate write method.

1-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

public boolean validateWrite()


{
boolean ret;
ret = super();
ret =
element.numberSeqFormHandler().formMethodDataSourceValidate
Write(ret) && ret;
return ret;
}

5. Save the method and then close the Code Editor window.

To override the delete() method, follow these steps.

1. Expand the Data Sources node of the CustContract form in the


AOT.
2. Expand the CustContract data source and then right-click the
Methods node of the data source, and select Override Method.
3. Select Delete from the list.
4. Add the following code into the delete method.

void delete()
{
ttsbegin;

element.numberSeqFormHandler().formMethodDataSourceDelete()
;
super();
ttscommit;
}

To override the close() method, follow these steps.

1. Right-click the Methods node of the CustContract form in the


AOT, and select Override Method.
2. Select Close from the list.
3. Add the following code into the close method.

void close()
{
if (numberSeqFormHandler)
{
numberSeqFormHandler.formMethodClose();
}
super();
}

4. Save the project.

1-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

TIP: You can import the AX2012_ENUS_DEVIV_01_01_LAB_SOL.xpo file to


verify and compare your solution.

To test that the number sequence for the customer contracts is populating
correctly, follow these steps.

1. From the Project window, right-click the CustContract form and


select Open.
2. On the Customer contracts form, click New.
3. Verify that the Customer contract ID field has populated with a
new number following the format C#####.

1-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Summary
This chapter provided an overview of how number sequences are set up in the
application. The chapter showed how the number sequence API works and how
to implement a number sequence API in a code. Additionally, the chapter
provided the steps that are required to implement a number sequence in a form.

The primary purpose of the number sequence framework is to provide unique,


user-friendly identifiers while maintaining a continuous or non-continuous
alphanumeric sequence.

An administrator can assign number sequences by using a page in the parameter


forms within individual application modules, or by using a wizard in the
Organization administration module.

The number sequence framework provides APIs that developers can implement
to create new number sequences with global scopes, company scopes, or other
organizational scopes. In addition the APIs can be used to implement number
sequence in a form so that when records are created the number record is updated
automatically with the next number available in the sequence.

1-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. TRUE or FALSE? Scope segments cannot be modified for a number


sequence that is currently being used.
( ) TRUE
( ) FALSE

2. Describe the difference between a constant segment and an alphanumeric


segment on a number sequence format.

3. Which of the following are supported scopes for number sequences in


Microsoft Dynamics AX 2012? (Select all that apply)
( ) DataArea
( ) Department
( ) Legal Entity
( ) Fiscal calendar

1-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 1: Number Sequences

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

1-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Solutions
Test Your Knowledge
1. TRUE or FALSE? Scope segments cannot be modified for a number
sequence that is currently being used.
(•) TRUE
( ) FALSE

2. Describe the difference between a constant segment and an alphanumeric


segment on a number sequence format.

MODEL ANSWER:

Constant segments contain a set of alphanumeric characters that do not


change.
Alphanumeric segments contain a combination of number signs (#) and
ampersands (&). These characters represent letters and numbers that
increment every time that a number from the sequence is used. Use a number
sign (#) to indicate incrementing numbers and an ampersand (&) to indicate
incrementing letters.

3. Which of the following are supported scopes for number sequences in


Microsoft Dynamics AX 2012? (Select all that apply)
(√) DataArea
( ) Department
(√) Legal Entity
(√) Fiscal calendar

1-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

CHAPTER 2: FRAMEWORK FEATURES


Objectives
The objectives are:

• Describe the concept of events and how they can be used in


Microsoft Dynamics® AX.
• Describe the various methods for integrating with Microsoft
Dynamics AX.
• Describe the various types of services available in Microsoft
Dynamics AX.
• Use a proxy class for .NET interop to X++.
• Access managed assemblies from X++.
• Explain how .NET Framework assemblies are deployed.

Introduction
There are many frameworks available in Microsoft Dynamics AX 2012. This
chapter provides descriptions of some frameworks, subsystems and features in
Microsoft Dynamics AX 2012. Frameworks are collections of design patterns,
interfaces, and code that provide support to you as a developer.

Eventing

Eventing is a design pattern for customization that is designed to enable non-


intrusive, maintainable customizations. This technology enables you to customize
the system without extensively altering source code in the base application.

Eventing enables customization behaviors to be implemented in event handlers.


The event handler code is called in response to an event that is raised in the
course of the business logic execution on the system.

For more information about Eventing, refer to the "Event Handlers for
Customization" topic in this chapter.

Address System

Addresses are handled by the Address subsystem. The global address book, or
address subsystem, can help you understand the relationships among people and
organizations that are associated with your organization. For example, a customer
can also be a vendor in a marketing campaign, or a worker in your organization
can also be a vendor.

2-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

NOTE: For more information about the address system refer to the "Global
Address Book" topic in the Application Foundation Features chapter in this
course.

Batch Journal Framework

The Batch Journal framework can be used to run a group of tasks that is created
by using the RunBase framework.

TIP: There are individual tts transaction controls for each task.

The RunBase framework provides a standardized approach to creating processes


and batch jobs in Microsoft Dynamics AX. The framework must be used for
every job-style function in the application.

The framework is implemented by the RunBase application class and supplies


many features that includes the following.

• Query
• Dialog, with persistence of the last values entered by the user
• Validate
• Batch execution for users to schedule jobs. This functionality uses
the RunBaseBatch class and the pack() and unpack() methods with
versioning.
• Progress bar
• Run
• Client/server-optimized

NOTE: For more information about the RunBaseframweowrk, refer to the


RunBase Framework (http://go.microsoft.com/fwlink/?LinkId=238164) page on
MSDN.

Business Operation Framework

The Business Operation Framework (BOF) follows the Windows


Communication Foundation (WCF) protocols and standards. With the BOF you
can do the following.

• Enables menu-driven execution or batch execution of services.


• Calls services in synchronous or asynchronous mode.
• Automatically creates a customizable user interface (UI) based on
the data contract.
• Encapsulates code to operate on the appropriate tier (prompting on
the client tier, and business logic on the server tier).

2-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

For more information about the BOF, refer to the "Business Operation
Framework" topic in this chapter.

Consistency Check Framework

The Consistency Check Framework helps validate the consistency of the data in
the production database and helps fix the inconsistencies that it finds.

The framework consists of classes that have names ending in


"ConsistencyCheck" (for example, InventConsistencyCheck). Each of the
framework classes extends the SysConsistencyCheck class.

Dimension

You can use the Dimension subsystem to work with financial dimensions. Use
the InventDim subsystem to work with inventory dimensions.

For more information about the financial dimensions subsystem, refer to the
"Dimensions" topic in the Application Foundation Features chapter.

Document Management System

The document management system is automatically available everywhere in


Microsoft Dynamics AX. Text notes and documents of any type and size can be
attached to any record in Microsoft Dynamics AX.

Note fields should not be put on your own tables, instead use the document
management system's text notes.

NOTE: If documents attached to a record are stored on a file share instead of in


the database in Microsoft Dynamics AX, you must make sure that the correct
access levels are set.

Infolog

Information and messages to the user are located in the Infolog. It also contains
contextual information and supporting Help and actions. For more information
see the "Using the Infolog (http://go.microsoft.com/fwlink/?LinkId=238165)"
page on MSDN.

Number Sequence

Microsoft Dynamics AX has a number sequence framework to generate


alphanumeric number sequences that are used to identify transaction documents
such as sales orders.

NOTE: For more information, refer to the Number Sequences chapter in this
course.

2-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Operation Progress

You can inform the user that a process will take some time by using the
Operation Progress framework.

BEST PRACTICE: Use a progress indicator during operations that take more
than two seconds.

Use an hourglass mouse pointer if the process takes two to seven seconds.

Use a progress bar if the process takes eight seconds or more.

NOTE: For more information, see the "How to: Create Progress Indicators
(http://go.microsoft.com/fwlink/?LinkId=238166)" page on MSDN.

Reporting

SQL Server Reporting Services (SSRS) is the primary reporting platform for
Microsoft Dynamics AX. The default, out of the box reports provided with
Microsoft Dynamics AX run on the Reporting Services platform. The new report
development environment takes advantage of extended SQL Server tools and
components. The report development environment is fully integrated into
Microsoft Visual Studio®.

NOTE: For more information, refer to the Reporting chapter in this course.

Application Integration

The capability to integrate Microsoft Dynamics AX with other systems inside


and outside the enterprise is a common requirement. Application Integration
Framework (AIF) provides this capability by enabling the exchange of data
through formatted XML. This formatted XML is referred to as a document, and
each document contains data and business logic. Documents are based on a
document class and defined by using Microsoft Dynamics AX.

Microsoft Dynamics AX is shipped together with many standard document


services that support common business processes. By using the capabilities that
AIF provides, you can also customize existing document services or create your
own document services.

NOTE: For more information about services, AIF, and the BOF, refer to the
Application Integration Framework and Services in Microsoft Dynamics® AX
course.

2-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Event Handlers for Customization


This topic describes the concept of events and how they can be used in Microsoft
Dynamics AX.

Microsoft Dynamics AX is rarely used without modification, because customers


have their own set of requirements to implement the product. Because of this,
partners have customized the product and this translates into costs for the
customer. Partners also invest significant time in browsing and understanding the
source code that is provided by Microsoft. When customization is needed, the
partner modifies the code in the customer’s layer, and the runtime engine
guarantees that the customization occurs. However, a problem exists because the
customizations can be broken when Microsoft restructures code in a lower layer
of the product when a newer version is released, and fixing customizations for
the next version upgrade can be expensive for partners. Additionally, when a
customer uses several Independent Software Vendors (ISVs) or partners there
can be modifications to the same objects. When there are overlapping objects,
this causes the same problem.

You can reduce the cost of creating and upgrading customizations by using
events. Developers creating code customized by other users should create events
in places where customizations typically occur. Then, those developers
customizing the original functionality in another layer can subscribe to an event.
When the customized functionality is tied to an event, the underlying application
code can be rewritten and it will have little effect on the customization, because
the same events are raised in the same sequence from one version to the next.

The Nature of Events


Object oriented programming paradigms map easily to the problem domains they
try to model. For example, classes are entities that represent something in real
life, and the names selected are typically accounts, people, and customers.
Methods are used to change objects, and the names selected specify what
operation is performed on the objects, such as deposit, hire, and invoice.

An event represents something that happens inside an object. Applicable event


names are typically in the past, such as deposited, hired, and invoiced. Events
will always occur, some are outside the scope of interest and some require taking
action.

You can use events to support the following programming paradigms.

• Observation: Events can be used to look for exceptional behavior


and generate alerts when such behavior occurs. An example of this
type of event is regulation compliance systems. For example, if more
than a designated amount of money is transferred from one account
to another, the system triggers a workflow that asks for acceptance of
the transaction.

2-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Information dissemination: Events can deliver the correct


information to the appropriate consumers at the most suitable time.
Information dissemination is supported by publishing an event to
anyone that wants to react to it.
• Decoupling: Events produced by one part of the application can be
consumed by a completely different part of the application. There is
no need for the producer to be aware of the consumers, nor do the
consumers have to know details about the producer. One producer's
event can be acted upon by any number of consumers. On the other
hand, consumers can act upon any number of events from many
producers.

TIP: There are some differences in how X++ and C# implement the event design
pattern. For more information, refer to the "X++ and C# Comparison: Event
(http://go.microsoft.com/fwlink/?LinkId=238167)" page on MSDN.

Terminology
X ++ events in Microsoft Dynamics AX 2012 are modeled after .NET eventing
concepts. The following table lists the terms in Microsoft Dynamics AX 2012
related to events.

Term Definition
Producer The producer is the logic that contains the code that
causes a change. It is an entity that emits events.
Consumer The consumer is the application code that represents an
interest in being notified when a specific event occurs.
It is an entity that receives events.
Event An event is a representation of a change that happened
in the producer.
Event payload The event payload is the information the event carries
with it. When a person is hired, for example, the
payload might include the employee's name and date of
birth.
Delegate A delegate is the definition of the information passed
from the producer to the consumer when an event
occurs.

2-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Coded Events
In X++, you can add delegates as members of a class. The syntax for defining a
delegate is the same as the syntax used for defining a method, except for the
following.

• The "delegate" keyword is used.


• No "public" or any other accessibility specifier is allowed.
• The return type must be "void."
• The body must be empty; meaning, it cannot contain declarations or
statements.

For example, a delegate for an event that is raised when a person is hired could
be expressed as follows.

delegate void hired(str name, UtcDateTime


startingDate)
{

TIP: You can right-click a class and select New > Delegate to create a new
delegate or you can click the New icon from the Code Editor and type the code.

The following figure shows a class named HireWorkerEventSample that includes


a delegate called hired that accepts a string and a date.

FIGURE 2.1 CLASS WITH DELEGATE SAMPLE

TIP: The lightning bolt icon indicates that this is a delegate and not an X++
method.

2-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When the application code has to signal that a new person is hired, it uses the
delegate as a method call, supplying the event payload as parameters, as shown
in the following code sample.

{
while select * from Employees where
Employees.hiredDate == today
{
this.hired(employees.Name,
employees.FirstWorkingDay);
}
}

NOTE: The code sample provided is only an example. This code will not compile
in Microsoft Dynamics AX because there is no Employee table.

The parameters that are defined in the parameter profile can be any type allowed
in X++. It is useful to pass an object instance, and to have the handlers modify
the state of that object, so that the publisher can ask for values from the
subscribers. Event handlers are run within the caller's transaction context.
Subscribers can be added to the event in one of two ways—through modeling for
example, in the Application Object Tree (AOT) or through X++ code execution.

Automatic Events
Automatic events are triggered by the environment as the result of something
occurring. Currently, a developer can indicate an event is triggered when a
method is called. This is described in the following sections.

Pre and Post are predefined events that occur when methods are called. The pre-
event handlers are called before the execution of the designated method, and the
post-event handlers are called after the method call has ended. It might be useful
to understand this to augment the existing method with methods called before
and after the normal body, as shown in the following figure.

Calls to the pre- and post-event handlers are inserted into the code generated for
the delegate when that delegate is compiled. Therefore, there is no overhead
penalty incurred by accessing metadata at runtime. In other words, the additional
code in the pre and post handlers has the same overhead as adding the same code
into the original method.

2-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

The example in the following figure also demonstrates that if an exception is


thrown in any of the pre-event handlers, neither the remaining handlers nor the
method itself is invoked. If a method that has pre-event and, or post-event
handlers throws an exception, the remaining post-event handlers are not invoked.
If an exception is thrown in a post-event handler, the remaining handlers are not
called. In any case, the exception propagates back to the caller as normal.

FIGURE 2.2 METHODS WITH AND WITHOUT HANDLERS

Each of the pre-event handlers can access the original values of the parameters
and modify them as required. The post-event handlers can modify the return
value of the called method.

Event Handlers
Event handlers are the methods that are called when the delegate is called, either
directly through code (for the coded events) or from the environment (in the
modeled events). The relationship between the delegate and the handlers can be
maintained in the code or in the AOT.

Adding Handlers in the AOT

A developer must identify a static method to handle the event on the delegate.
Only static methods can be used in this context. Event handlers can be added to
the delegate by dragging the event handler to the delegate node that represents
the event to be handled. The handler can be removed by using the Delete menu
item available for any node in the AOT.

Adding Handlers in Code

Event handlers can be added to or removed from events by using special X++
syntax. The delegate name appears on the left side of the += (for adding) or the -
= (for removing) operator. On the right side the keyword eventhandler is given,
together with the qualified name of the handler to add or remove. The compiler
will check that the parameter profiles of the delegate and the handler match.

You can subscribe to methods as event handlers in two locations in the AOT—
under a delegate node or under a method node.

2-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Under a Delegate Node

A class node, such as AOT > Classes > MyClass, can have delegate nodes
directly underneath it. The following rules apply to delegates in the AOT.

Under a Method Node

In the AOT, you can assign a method as an event handler for the pre-method
event or the post-method event of another method. The event handler subscribes
to an event of the host method.

The nodes that represent the subscription of an event handler to a host method are
underneath the node for the host method. AOT elements such as classes, tables,
and forms can have methods.

NOTE: Event handlers cannot subscribe to the classDeclaration of a class


because they are not methods.

All event handlers that subscribe to a method must return void. Event handlers
for host methods can use one of two parameter signatures.

• One parameter of the type XppPrePostArgs.


• The same parameters that are on the host method that the event
handler subscribes to.

Procedure: Add an Event Handler in the AOT


To add an event handler in the AOT, follow these steps.

1. Create a new class that contains a delegate.


2. Create a new class that contains a static method with the logic to be
run.
3. Right-click the delegate and select New Event Handler Subscription.
4. Set the following properties on the event handler that is created:
a. Name = MyEventHandler
b. Class = the class that you created in step 2.

2-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

c. EventHandlerType = X++
d. Method = the static method that you created in step 2.

FIGURE 2.3 X++ EVENT HANDLER ADDED TO MYDELEGATE

Procedure: Add an Event Handler in Code


To add a static method event handler in code, follow these steps.

1. Create a new class that contains a delegate.


2. Create a new "subscriber" class that contains a static method with the
logic to be run.
3. Create a new static method in the class that contains the delegate.
4. Add code to the method to call the subscriber class. Use the
following code sample to guide you.

To add an instance method event handler in code, follow these steps.

1. Create a new class that contains a delegate.


2. Create a new "subscriber" class that contains an instance method
with the logic to be run.
3. Create a new instance method in the class that contains the delegate.
4. Add code to the method to call the subscriber class. Use the
following code sample to guide you.

private void AddStaticHandler()


{
this.MyDelegate += eventhandler
(Subscriber::MyHandler);
}

2-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

private void AddInstanceHandler()


{
Subscriber s = new Subscriber();
this.MyDelegate += eventhandler (s.InstanceHandler);
}

Pre and Post Event Handlers


An event handler that is underneath a method node can run before or after the
method runs. You control the timing by setting the CalledWhen property on the
event handler node. The CalledWhen property has two values.

• Pre: The event handler runs before the method starts.


• Post: The event handler runs after the method ends.

NOTE: In Microsoft Dynamics AX 2012, there is no option to assign pre and


post event handlers to methods programmatically.

The XppPrePostArgs Class Parameter

A pre-method event handler that has only an XppPrePostArgs parameter can


inspect and change the values of the parameters. The changes take effect before
the parameters are passed to the host method that is being called. View the
getArg and setArg methods.

When an XppPrePostArgs object is used, the values of the parameters and the
return value can be changed by the event handler. The values can be changed
even if the parameters and return type are value types, such as an integer or
string. If a parameter or a return type is a reference to an object, the event handler
can call methods on the object and could change the state of the object.

Matched Parameters without XppPrePostArgs

A pre-method or post-method event handler can have the same parameter


signature as the host method that it subscribes to. This is the alternative to the
event handlers having just one parameter of type XppPrePostArgs.

There are two types of parameters that are treated differently by event handlers:

• Value types, such as an integer or string


• Reference types, such as an instance of a class

A pre-method event handler receives the same parameter values that the host
method receives. However, this event handler cannot modify the value of any
value type parameters that refer to the host method.

A post-method event handler receives the same parameter values that the host
method received. However, this event handler does not receive the return value
from the host method.

2-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Demonstration: Modify Parameter Values in a Pre-Method


Event Handler
In Microsoft Dynamics AX, you can assign a static method to be an event
handler that starts and ends immediately before a specific method on a class ends.
This is known as a before-method event handler, or a pre-method event handler.
In the AOT you assign the event handler as a node under the method node. The
CalledWhen property on the event handler node must be set to Pre.

The before-method event handler can modify the parameter values that are
passed by the caller method, before the called method receives them. To modify
the pre-method event handler, follow these steps.

1. Create a new Class named TestClass.


2. Create a new method on the TestClass and use the following code
sample.

// Called by the job later in this example.


public str formatWholeName
(str _firstName, str _lastName)
{
return _lastName + ", " + _firstName;
}

3. Create a new static method for the event handler and use the
following code sample.

// CalledWhen = Pre.
static public void formatWholeNameEhBefore(XppPrePostArgs
ppArgs)
{
str firstName;
firstName = ppArgs.getArg("_firstName");

if ("Dave" == firstName)
{
ppArgs.setArg("_firstName", "David");
}
else if ("Bill" == firstName)
{
ppArgs.setArg("_firstName", "William");
}
}

4. Save the class.


5. Right-click the formatWholeName method and select New Event
Handler Subscription.
6. In the Properties window, set the following properties:
a. Name = PreHandler
b. CalledWhen = Pre
c. Class = TestClass

2-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

d. EventHandlerType = X++
e. Method = formatWholeNameEhBefore

7. Create a new job to run the new class and call the method. Use the
following code sample.

static void NameBefore(Args _args)


{
TestClass testClass;
str formattedWholeName;
testClass = new TestClass();

// Run a method that has a pre-method event handler,


// one that starts and ends before the method starts.
formattedWholeName = testClass.formatWholeName
("Dave", "Ahs");

// The Infolog displays the effect of the before-


method event handler.
info(strFmt
("%1 == the formatted formal name.",
formattedWholeName));
}

/*** Output displayed in the Infolog:


Ahs, David == the formatted formal name.
***/

8. Save the job, and then click Run.

Demonstration: Modify the Return Value in a Post-Method


Event Handler
You can assign a static method to be an event handler that starts when a specific
method on a class ends. This is known as an after-method event handler, or a
post-method event handler. In the AOT, you assign the event handler as a node
under the method node. The CalledWhen property on the event handler node
must be set to Post.

The post-method event handler can modify the return value of the completed
method, before the return value is given to the method caller.

1. In the TestClass created as a part of the "Modify Parameter Values


in a Pre-Method Event Handler" demonstration, create a new method
and use the following code sample.

public int numberOfExpectedAttendees


(int _numOfInvites, int _numOfDeclines)
{
return _numOfInvites - _numOfDeclines;
}

2-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

2. Create a new static method for the event handler and use the
following code sample.

// CalledWhen = Post.
static public void numberOfExpectedAttendeesEhAfter
(XppPrePostArgs ppArgs)
{
int intAttendees;

intAttendees = any2Int(ppArgs.getReturnvalue());
info(strFmt("%1 = intAttendees raw, in event
handler.", intAttendees));
if (0 > intAttendees)
{
intAttendees = 0;
ppArgs.setReturnValue(intAttendees);
}
}

3. Save the class.


4. Right-click the numberOfExpectedAttendees method and select
New Event Handler Subscription.5.
5. In the Properties window, set the following properties:
a. Name = PostHandler
b. CalledWhen = Post
c. . Class = TestClass
d. . EventHandlerType = X++
e. . Method = numberOfExpectedAttendeesEhAfter
6. Create a new job to run the class and call the method. Use the
following code sample.

static void Job2ReturnTestEhAfter(Args _args)


{
TestClass testClass9;
int attendeeCountReturned;

testClass9 = new TestClass();

// Run a method that has an event handler that starts


after the method finishes.
attendeeCountReturned =
testClass9.numberOfExpectedAttendees(8, 13);

// The Infolog output displays the effect of the


after-method event handler.
info(strFmt
("%1 == the number of expected attendees.",
attendeeCountReturned));
}

2-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

/*** Output displayed in the Infolog:


0 == the number of expected attendees.
***/

7. Save the job, and then click Run.

Tips for Events


When you consider working with events

• Define events the programmers customizing the behavior of the


system should react to. You should identify natural customization
points and use events to publish the relevant information to
subscribers.
• Maintain the semantics implied by the event from one version to the
next. Part of the usefulness of events comes from the preservation of
the semantics of the events. As soon as an interface is defined, third
parties will be able to leave their existing code unmodified if the
semantics are left unchanged (even though the implementation
behind might be modified).
• Document the events that you create well because this will help
anyone who is performing the customization later.
• Favor defining events over creating pre and post events on methods.
Events are strong interfaces, whereas methods are an implementation
artifact—a method's responsibilities and parameters can change over
time, and they can disappear completely if the developer so decides.

When you consider working with events do not

• Try to raise an event from outside the class in which the event is
defined. The X++ compiler disallows raising events from outside the
class by design.
• Make customizations that rely on the order in which event handlers
are executed. No guarantees are made by the runtime environment
about the order in which the event handlers are called.

Integration with Microsoft Dynamics AX


Integration is the development pattern that involves enabling existing
applications (not written exclusively for Microsoft Dynamics AX) to interact and
work with Microsoft Dynamics AX across process boundaries.
An example of integration is when a value added reseller (VAR) integrates with
an existing legacy Customer Relationship Management (CRM) system to
synchronize the customer list between Microsoft Dynamics AX and the legacy
CRM system.

2-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Much of Microsoft Dynamics AX functionality is contained in X++ classes. The


programming models are how you access that functionality. The following
programming models are supported in Microsoft Dynamics AX 2012:

• X++ development
• .NET languages development with weakly typed .NET interop to
X++ (Also referred to as .NET Business Connector)
• .NET languages development with strongly typed .NET interop to
X++ (Also referred to as .NET Proxies)
• Services

The integration components in all these methods interact with the Application
Object Server (AOS), shown in the following figure.

FIGURE 2.4 MICROSOFT DYNAMICS AX INTEGRATION TECHNOLOGIES

IMPORTANT: Integrations to external systems are best implemented by using


the services programming model. Although the weakly typed and strongly typed
.NET interop to X++ can be used for the integration development pattern, we do
not recommend the use of these technologies for integration. Their firewall
unfriendliness together with their dependencies on Business Connector
assemblies make these technologies unfit for most integration scenarios.

If the functionality that you need is not available in a service that ships with
Microsoft Dynamics AX 2012, you can use the declarative attributes to expose
existing X++ classes and methods as a service interface.

2-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following topics provide further descriptions of each programming model.

X++ Development
X++ development is the programming model in which the developer directly
adds or alters Microsoft Dynamics AX metadata and/or X++ source code. This
model provides complete access to all the base functionality implemented in the
lower layers in the system. This is the most commonly used programming model
in Microsoft Dynamics AX development.

Advantages:

• The most powerful programming model because it provides


complete access to all functionality in the system.
• Precise and fine-grained control over the scope of customizations.

Disadvantages:

• Steeper learning curve for .NET developers.

Weakly Typed .NET Interop to X++


The Business Connector presents a comprehensive but weakly typed
programming model to access all the Microsoft Dynamics AX metadata and X++
business logic from .NET. This is the only mechanism available for .NET to X++
interop in Microsoft Dynamics AX 2009 and earlier versions. This model
continues to be available and supported in Microsoft Dynamics AX 2012.

Advantages:

• Opens up Microsoft Dynamics AX development to the .NET


community.

Disadvantages:

• Weakly typed programming model abstraction results in most


problems being found at run time rather than at design time, which
can lead to increased total cost of ownership (TCO).

Strongly Typed .NET Interop to X++


In Microsoft Dynamics AX 2012, the Visual Studio Tools provides access to a
strongly typed programming model for Microsoft Dynamics AX metadata and
X++ business logic. This is achieved through the generation of strongly typed
.NET proxies on top of the newest version of the Business Connector.

2-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Advantages:

• Adapts Microsoft Dynamics AX development seamlessly into the


.NET paradigm.
• Strongly typed programming model.
• Results in more maintainable code.
• Precise and targeted access to the Microsoft Dynamics AX system
functionality needed.

Disadvantages:

• Requires redistribution of Business Connector assemblies with the


consuming .NET application.
• Not firewall friendly due to underlying dependency on Remote
procedure call (RPC) protocols.

Services
Exposes Microsoft Dynamics AX functionality through WS-* standards-
compliant service interfaces. In addition to exposing functionality through
services that ship with Microsoft Dynamics AX 2012, Microsoft Dynamics AX
2012 also provides declarative language constructs (X++ attributes) and
development tools so that you can quickly expose existing X++ business logic as
services without additional coding.

Advantages:

• Standards-based service interfaces enable widening reach to many


platforms, such as mobile platforms.
• Strongly typed programming model.
• Firewall friendly.
• We recommend that you use "chunky" interfaces that have fewer
methods that enable you to send the required data in fewer, larger,
chunks, when possible.
• Runs in Common Intermediate Language (CIL) which provides the
advantages of being able to run on any platform that supports CIL
and improved security and reliability because the code is verified for
safety at runtime.

Disadvantages:

• Typically, coarse-grained chunky service interfaces limit precision of


functionality exposure--you may need to use a less specific method
to meet your needs.

2-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Application Integration Framework


AIF provides an extensible framework within Microsoft Dynamics AX that
enables the exchange of data. AIF consists of three primary components.

• Services: With AIF you can expose any business logic as a service to
be consumed by other applications. Within Microsoft Dynamics AX
you can create, customize, and publish services.
• Document services: A specific implementation of services in which
the Microsoft Dynamics AX business logic is exposed through
document services. Document services are typically used to
exchange data with other systems.

NOTE: For more information about standard document services and how to
create your own document services, refer to the Services and AIF development
(http://go.microsoft.com/fwlink/?LinkId=238168) page on MSDN.

Document services exchange data in the form of XML documents. Document


services provide the tools to build business-to-business (B2B) and application-to-
application (A2A) integration between your system and trading partners or other
external software systems. AIF includes many services that encapsulate common
business functionality that you can use out of the box. Additionally, there is a
wizard that you can use to create your own custom document services.

AIF document services have the following types of exchanges.

• Adapter-based exchange: An asynchronous document exchange


that uses an adapter in Microsoft Dynamics AX. In this type of
exchange, documents are moved through the system in queues and
processed by the batch jobs. Adapter transports supported by AIF are
Microsoft Message Queuing (also known as MSMQ) and file
systems. If you use the Message Queuing adapter, you must have
Message Queuing or installed on the AIF gateway computer.
• Web services-based exchange: A synchronous document exchange
that uses web services. Because this type of exchange is
synchronous, queues are not used. The web services can be
generated automatically from the Microsoft Dynamics AX business
logic. Developers with limited web experience can easily expose
services through web services. AIF supports WCF services.

TIP: Internet Information Services (IIS) only needs to be installed if you are
configuring an “Enhanced Inbound Port”. IIS is not required for basic ports,
because they are hosted by the AOS itself.

2-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Microsoft Dynamics AX supports integration with the Application Integration


Framework (AIF) components by using the Microsoft Dynamics AX services
programming model. You can customize the document services that are included
with Microsoft Dynamics AX, create new custom services, and consume external
web services. To support a range of option for customization and
programmability, Microsoft Dynamics AX provides the following types of
services.

• Custom Services are services that you create to expose X++ logic
through a service interface. You can use the business logic with
inbound or outbound transfers. The types of services are developed
by using the Business Operation Framework (BOF). This is done by
creating X++ classes that expose their logic through the use of
attributes available within the BOF.
• Document Services represent data and business logic within
Microsoft Dynamics AX. You can use or customize the over 70
standard Axd document services that are included with Microsoft
Dynamics AX. If standard document services do not meet your
needs, you can create a new document service by using the AIF
Document Service Wizard. Each document is represented by a class.
The name of a document class is preceded by Axd. For example,
AxdSalesOrder is the name of the document and also the name of the
document class. The terms "document" and "Axd document" and
"document class" are used interchangeably.
• System Services cannot be customized. The Query Service,
Metadata Service, and User Session Service are Windows
Communication Foundation (WCF)-based services included with
Microsoft Dynamics AX. They provide access to data returned in
queries, metadata for AOT objects such as tables and extended data
types (EDTs), and data about the calling user such as default
language and default company.

With Microsoft Dynamics AX, you can consume external web services from
X++ code, and consume web services hosted by Microsoft Dynamics AX from
.NET Framework languages such as Microsoft Visual C#.

Microsoft Dynamics AX supports application integration and data exchange in


both intranet and Internet-facing scenarios. Services that are based on WCF
classes are hosted on the AOS for applications to integrate within the intranet of a
company. To consume or expose services over the Internet, you must install and
use IIS. For more information about Microsoft Dynamics AX web services on
IIS refer to the Install web services on IIS
(http://go.microsoft.com/fwlink/?LinkId=238169) page.

2-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Business Operation Framework


The Business Operation Framework (BOF) is the model-view-controller
framework that synchronously or asynchronously controls the execution of
immediate or batched business operation implementations. It lets you run
services on Microsoft Dynamics AX by using the Windows Communication
Foundation (WCF) framework.

BOF uses services to call from the client to the server so application “chattiness”
is reduced. The BOF classes separate the user interface, business logic, and data
contract logic. You can use BOF to write applications that have reduced client to
server communication. Because BOF uses services, there is no calling from the
client back to the server, and an open connection from the server to the client
cannot be maintained. The user interface for input parameters can be auto-
generated.

Features of the BOF include the following.

• Allows menu-driven execution or batch execution of services.


• Calls services in synchronous or asynchronous mode.
• Automatically creates a customizable UI based on the data contract.
• Encapsulates code to operate on the appropriate tier (prompting on
the client tier, and business logic on the server tier).

To create a Business Operation Framework service, you must follow these steps.

• Create a data contract class.


• Identify the parameters that are passed to the service.
• Register the class as a Business Operation Framework service.
• Optionally customize the automatically generated UI for the class.

NOTE: For more information about services, AIF, and the BOF, refer to the
Application Integration Framework and Services in Microsoft Dynamics® AX
course.

NOTE: Additional examples of how to use the BOF can be found in the
Workflow and Reporting chapters later in this course.

2-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Interop to X++
A proxy class is a .NET Framework class that provides access to one X++ item
type of Microsoft Dynamics AX. You can build proxies for the following X++
item types:

• Classes: Both application and system classes.


• Tables: Both application and system tables.
• Enums: Both base and system enums.

CAUTION: You cannot build a proxy for an X++ interface. If you try, a proxy is
generated for a .NET Framework class which at best approximates the interface.
This incorrect translation into a class causes some common scenarios to fail, and
it might create problems in future releases.

You can generate the proxy C# or Visual Basic source code by using the
Application Explorer in Microsoft Visual Studio. Proxies are usually a better
alternative to .NET Business Connector. .NET Business Connector requires your
C# code to use a late-bound programming model. Proxies provide an early-bound
programming model. With the early-bound model the Code Editor can provide
IntelliSense, and it can also catch misspellings and other errors at compile time,
that is, before the code is run.

There are different scenarios for constructing a proxy object from a proxy class
that is written in C# or in another .NET Framework language. The following
topics describe three possible scenarios.

Scenario: Implicit Construction by Parameter Passing


This scenario starts when an X++ job passes an X++ DictClass object to a C#
method. The C# method takes a parameter type of a proxy for the X++ class
DictClass. The system performs the marshaling by automatically constructing a
proxy object from the DictClass object.

The X++ Job

static void StartInteropFromXppJob2a(Args _args) // X++


{
DictClass dictClass2;
int classId;
str className;

classId = classnum(DateTimeUtil);
dictClass2 = new DictClass(classId);

// Initiate interop from X++.


className =
CSharpDll.CSharpClass::CalledFromXppDc(dictClass2);

2-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

info(strFmt("%1 , %2", classId, className));


}
/*** Output copied from the Infolog:
64900 , DateTimeUtil
***/

The C# Method

using System; // C#
namespace CSharpDll
{
public class CSharpClass
{
static public string CalledFromXppDc
(DictClass pxyDictClass)
{
return pxyDictClass.name();
}
}
}

Scenario: Use a Proxy Object as Input to Construct a


Copy in a Different Namespace
A C# application can have two proxy classes to the same X++ class, because the
two proxies could have different namespaces. This section describes a scenario
where you construct an instance of one proxy from an instance of the other,
despite the namespace difference.

In the following example, at run time your C# code has an instance of the proxy
class Finance.TownBank. But your code must pass an Economics.TownBank
object to a method. The namespaces do not match.

The solution is to construct an instance of the Economics.TownBank proxy class


from the Finance.TownBank object. Your C# code can use the following proxy
constructor for this.

public Bank(Microsoft.Dynamics.AX.ManagedInterop.Object axObject)

After the constructor is called, both proxies reference the same TownBank object
in Microsoft Dynamics AX. If one proxy changes the state of the underlying
TownBank X++ object, the other proxy sees the changes.

// C# method to create a proxy object from an equivalent


proxy object.
using System;
public class TestTheProxy3
{
public void CloneAProxy(Finance.TownBank finBank)
{
Economics.TownBank ecoBank;
Economics.AuditManager auditMgr;

2-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

// Constructor call.
ecoBank = new Economics.TownBank(finBank);

auditMgr = new Economics.AuditManager();


// Use the copy of the proxy, ecoBank.
auditMgr.AuditABank(ecoBank);
}
}

NOTE: This code sample is theoretical and will compile if pasted directly into a
C# Class Library. Additional code would be required for this example to work.

Scenario: Construct a Session Object in C#


A C# .exe program that is started from the console can construct an instance of
the Microsoft.Dynamics.AX.ManagedInterop.Session class. Then the C# code
can call the constructor on a proxy class.

The first step is to create the class library in Visual Studio. After you have
created the class library project, you can then add a Microsoft Dynamics AX
table to the project. Then you can create class methods that access that table.

In Visual Studio, you use Application Explorer to add an X++ element to a


managed code project. This walkthrough illustrates the following tasks:

• Creating the class library, adding a Microsoft Dynamics AX table to


the project, and accessing that table from code.
• Creating a console application project and testing the generated
assembly.

To create the class library

1. To create a new class library project, click File > New> Project.
2. Under the Installed Templates tree, click Visual C# > Windows,
select the Class Library project type and then click OK.
3. Save the new project.
4. Add the project to the AOT by clicking File > Add ClassLibrary1
to AOT. Notice that the project icon changes in Solution Explorer.
Alternatively, you can right-click the ClassLibrary1 project and
click Add ClassLibrary1 to AOT.

To add a Microsoft Dynamics AX table to the project

1. Open the Application Explorer by clicking View > Application


Explorer. Click the Data Dictionary > Tables node and locate the
CustTable table.

2-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

2. Click the CustTable table and drag it onto the project in Solution
Explorer. Alternatively, you can right-click the table and then click
Add to Project. In Solution Explorer, you can view the table and the
proxy to the CustTable table that is created internally by the system.
In the References node, you can view a reference to the assembly
Microsoft.Dynamics.Ax.ManagedInterop.

TIP: You can add a system table or system class to your Visual Studio project
even if the interface does not support the dragging of system objects. For
example, to add the FormRun system class, first add any application class, such
as the Bank class. Then rename the new proxy node from Class.Bank.axproxy to
Class.FormRun.axproxy.

To create methods that use the table

Open the Class1.cs file and add the following code. This code contains two
methods that each take two parameters and return data for the specified customer.

///C# code:

using System;
namespace ClassLibrary1
{
public class Class1
{
public string GetCustomerPaymentMode(string
accountNum,

string dataAreaId)
{
string paymentMode = String.Empty;
CustTable custTable = new CustTable();
// Search for the customer.
custTable =
CustTable.findByCompany(dataAreaId, accountNum);
if (custTable.Found)
{
// Get the value for the
customer's payment mode.
paymentMode = custTable.PaymMode;
}
return paymentMode;
}
public bool GetCustomerCreditLimit(string
accountNum,

string dataAreaId)
{
bool hasCreditLimit = false;
CustTable custTable = new CustTable();
// Search for the customer.
custTable =

2-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

CustTable.findByCompany(dataAreaId, accountNum);
if (custTable.Found)
{
// Get the value for whether the
customer has a credit limit.
hasCreditLimit =
(custTable.MandatoryCreditLimit == NoYes.No ? false :
true);
}
return hasCreditLimit;
}
}
}

To create a console application project to test the assembly

1. In Solution Explorer, right-click the solution ClassLibrary1 and


select Add > New Project.
2. Under the Installed Templates tree, click Visual C# > Windows,
select the Console Application project type and then click OK.
3. In Solution Explorer, add a reference to the ClassLibrary1 project by
right-clicking the References node under the ConsoleApplication1
project and then clicking Add Reference.
4. Click the Projects tab, select the ClassLibrary1 project and then
click OK.
5. In Solution Explorer, add a reference to the managed interop
assembly by right-clicking the References node under the
ConsoleApplication1 project and then clicking Add Reference.
6. Click the Browse tab, locate the
Microsoft.Dynamics.AX.ManagedInterop assembly and select OK.
This assembly is located in the Client\Bin directory. For example,
C:\Program Files (x86)\Microsoft Dynamics AX\60\Client\Bin. This
reference is necessary to use the Session object.

To call methods to display output to the console application

1. Open the Program.cs file and add the following code. This code calls
the GetCustomerPaymentMode and the GetCustomerCreditLimit
methods from the class that you created and displays the values in
the console window.

using System;
using ClassLibrary1;
using Microsoft.Dynamics.AX.ManagedInterop;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

2-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

// Create a session
using (Session session = new Session())
{
session.Logon(null, null, null,
null);

Class1 class1 = new Class1();


string accountNum ="3003";
string dataAreaId ="ceu";
string paymentMode = String.Empty;
string hasCreditLimitText =
String.Empty;
bool hasCreditLimit;

// Find the customer payment mode


and credit limit.
paymentMode =
class1.GetCustomerPaymentMode(accountNum, dataAreaId);
hasCreditLimit =
class1.GetCustomerCreditLimit(accountNum, dataAreaId);
hasCreditLimitText =
(hasCreditLimit == false ? " and does not have" : " and
has");

// Write the data to the console


Console.WriteLine("Customer " +
accountNum + " in company " + dataAreaId + " has a payment
mode of " + paymentMode + hasCreditLimitText + " a
mandatory credit limit." );
Console.ReadLine();
}
}
}
}

2. In Solution Explorer, set the console application to be the startup


project by right-clicking ConsoleApplication1 and then clicking Set
as StartUp Project.

To test the generated assembly

Run the application. If you have the sample data installed, the following output
will appear in the console window.

Customer 3003 in the CEU company has a payment mode of CHCK and does not
have a mandatory credit limit.

TIP: You might receive an error about the .NET target framework because both
projects target the .NET Framework 4 by default but the
Microsoft.Dynamics.AX.ManagedInterop assembly is a mixed-mode assembly
that targets the 2.0 runtime.

To resolve this error, you have two options— you can change the target
framework for both projects to .NET Framework 3.5 or you can add an attribute

2-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

to the app.config file of the console application project. To change the target
framework, right-click each project in Solution Explorer and then click
Properties. In the Target framework field, select .NET Framework 3.5.

If you want the console application project to target the .NET Framework 4, add
the useLegacyV2RuntimeActivationPolicy attribute to the startup element in the
app.config file and set it to true. For example, <startup
useLegacyV2RuntimeActivationPolicy="true">.

.NET Target Framework Error


You might receive an error about the .NET target framework because both
projects target the .NET Framework 4 by default. However, the
Microsoft.Dynamics.AX.ManagedInterop assembly is a mixed-mode assembly
that targets the 2.0 runtime. To resolve this error, you have two options— you
can change the target framework for both projects to .NET Framework 3.5 or you
can add an attribute to the app.config file of the console application project.

To change the target framework, right-click each project in Solution Explorer


and then click Properties. In the Target framework field, select .NET
Framework 3.5.

If you want the console application project to target the .NET Framework 4, add
the useLegacyV2RuntimeActivationPolicy attribute to the startup element in the
app.config file and set it to true. For example, <startup
useLegacyV2RuntimeActivationPolicy="true">.

Proxies and Exception Mapping


When an X++ object throws an exception, the exception value is an integer
element from the X++ Exception enum. If the X++ object is being managed by a
proxy object in the .NET Framework, the thrown element value of the enum is
automatically marshaled into an instance of a .NET Framework exception class.
This class is designed to represent the enum element.

Name Pattern

There is a pattern of name correspondence between values of the X++ Exception


enum and the .NET Framework exception classes that represent the enum values.
There are 15 elements in the Exception enum. The following table shows three
examples of the pattern. For example, the last row in the table shows that the
enum element and the exception class are both named with the word Deadlock.

X++ Exception enum Word in .NET Framework exception class


element common
Exception::Error Error Microsoft.Dynamics.AX.ManagedInt
erop.ErrorException
Exception::Warning Warning Microsoft.Dynamics.AX.ManagedInt
erop.WarningException

2-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

X++ Exception enum Word in .NET Framework exception class


element common
Exception::Deadlock Deadlock Microsoft.Dynamics.AX.ManagedInt
erop.DeadlockException

Inheritance Hierarchy of the .NET Exception Classes

The following indented list of .NET exception classes shows the inheritance
hierarchy of the ErrorException class. This is one of the exception classes that a
proxy object might encounter if the underlying X++ object has a problem. The
inheritance hierarchy is the same for the other exceptions such as
Microsoft.Dynamics.AX.ManagedInterop.WarningException.

FIGURE 2.5 INHERITANCE HIERARCHY

Exceptions Note from the X++ Object

A proxy object can encounter exceptions that are not related to the behavior of its
underlying X++ object. For example, if the AOS is stopped by the administrator,
the proxy can encounter a
Microsoft.Dynamics.AX.ManagedInterop.ServerUnavailableException. This
ServerUnavailableException class extends the
Microsoft.Dynamics.AX.ManagedInterop.ManagedInteropException class.

Interop from X++


Classes in assemblies that are managed by the common language runtime (CLR)
can be accessed in X++ code. This feature of Microsoft Dynamics AX is called
.NET interop from X++.

.NET interop from X++ is useful when you want your X++ code to access the
functionalities in a CLR managed assembly. This includes assemblies that are
installed with the .NET Framework. It also includes any assemblies that you
create with a language such as C# or Visual Basic.

2-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Access Static and Instance Members of the .NET


Framework Classes from X++
The X++ syntax for calling .NET Framework methods is different for calling
static methods than it is for calling instance methods. In both cases, the dot
character (.) is used to delimit all the namespaces of the fully qualified type
name. However, for calling static .NET Framework methods, you must use a
double colon (::) between the class name and the method name. This is consistent
with the double colon that you use when you call static methods that are written
in X++.

CAUTION: Starting in Microsoft Dynamics AX 2012, you rarely have to include


a "hanging" semicolon before the first statement in your X++ methods. However,
you must include the semicolon in X++ methods that call static methods in the
.NET Framework when the call to the managed static method is the first one in
the method.

In the following X++ code sample, the static and instance method calls are as
follows.

• Static: System.Convert::ToString
• Instance: netString.Substring

static void JobStaticInstanceSyntax95(Args _args)


{
System.Int32 netInt;
System.String netString;
str xppString;
netInt = 123456;

// static
netString = System.Convert::ToString(netInt);

// instance
netString = netString.Substring(3,2);

xppString = netString;
info(xppString);

/***** Actual infolog output


Message (05:58:20 am)
45
*****/
}

2-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Marshal Between X++ and CLR Primitive Types


In Microsoft Dynamics AX 2012, the X++ language does implicit conversion or
marshaling between several X++ primitive types and their counterpart types
managed by the CLR. This means that the X++ assignment operator, the single
equal sign (=), can be used between certain pairings of an X++ type with a CLR
type.

Implicit marshaling with the X++ assignment operator works in both directions,
either from X++ types to CLR types, or from CLR to X++.

Why Marshaling is Useful

A .NET managed assembly might provide a useful method that returns a


System.String object. You can call the method and capture the returned
System.String in a variable of that type that you declare in your X++ code.

However, if your next step is to pass that string into an X++ method that takes a
str, you must first marshal the System.String into a str.

Implicitly Marshaled Conversion Pairs

Each row in the following table lists a pairing of types that are implicitly
marshaled by the X++ assignment operator.

NOTE: There is no implicit marshaling between the X++ utcdatetime and the
.NET Framework System.DateTime type. For more information about how to
convert between utcdatetime and System.DateTime, refer to the How to: Convert
Between utcdatetime and System.DateTime
(http://go.microsoft.com/fwlink/?LinkId=238170) page on MSDN.

X++ Type CLR Type


boolean System.Boolean
date System.DateTime
int System.Int32
in64 System.Int64
str System.String
guid System.Guid
real System.Single or System.Double

2-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

The following code sample shows the marshaling between the .NET Framework
System.Boolean type and its X++ counterpart boolean.

static void JobBooleanMarshal(Args _args) // X++ job.


{
System.Boolean netBool; // .NET
boolean xppBool; // X++
;
// Marshal .NET to X++.
xppBool = false;
netBool = true;
xppBool = netBool; // Marshals.
if (true == xppBool)
{
info("A1. Good, .NET was marshaled to X++.");
}
else
{
info("A2. Bad, .NET was not marshaled to X++.");
}

// Marshal X++ to .NET.


netBool = true;
xppBool = false;
netBool = xppBool; // Marshals.

xppBool = true;
xppBool = netBool;
if (false == xppBool)
{
info("B1. Good, X++ was marshaled to .NET.");
}
else
{
info("B2. Bad, X++ was not marshaled to .NET.");
}
}

/***** Actual infolog output

Message (01:08:32 pm)


A1. Good, .NET was marshaled to X++.
B1. Good, X++ was marshaled to .NET.

*****/

TIP: For additional code samples for marshaling between the .NET Framework
types and the X++ counterparts, refer to the "How To: Marshal Between X++
and CLR Primitive Types (http://go.microsoft.com/fwlink/?LinkId=238171)"
page on MSDN.

2-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

IMPORTANT: Automatic marshaling works between the X++ int64 type and the
.NET Framework type System.Int64, just as marshaling works between the X++
int and the .NET System.Int32.

An X++ int does not marshal to a System.Int64, or the reverse. A System.Int32


does not marshal to an X++ int64, or the reverse.

IMPORTANT: As an option in X++, str variables can be declared with a


maximum length. The following str declaration sets the maximum length at eight.
The assignment would end with the value of myStr being "12345678", with the
"9" being truncated:

str 8 myStr ="123456789"; // The string is truncated, and the nine is removed.

The System.String type in the .NET Framework does not have a property that
corresponds to the maximum length of an X++ str, and string truncation does
not occur. This feature difference could lead to different behavior at run time in
the following cases:

X++ str is marshaled to .NET Framework.

X++ is compiled to .NET Framework common intermediate language (CIL), and


is run as CIL.

When X++ is run as p-code rather than as CIL, instances of str truncation can
be logged by Microsoft Dynamics AX.

Operators for CLR Primitive Types


In X++, when you work with .NET CLR primitive data types, you can use the
equal sign (=) assignment operator. However, no other operators can be used
between two CLR primitives. For example, you cannot use the comparison
operators, such as == or >. Also, you cannot use bitwise operators, such as & or |.

You cannot use a comparison operator with CLR primitive or value types
because they are represented as reference types or objects in the system. A
System.Int32 is an object that is converted to a value type temporarily during
assignment statements. A System.Int32 remains a reference type when it is used
with a comparison operator. Comparison operators such as >= are designed for
use between value types.

2-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

The following code sample shows that the X++ operator >= cannot be used
meaningfully between two System.Int32 variables. The sample also shows that
the .NET Framework has methods that provide the functionality of the
comparison operators. The method System.Int32.CompareTo is shown.

static void JobOperatorsForNet(Args _args)


{
System.Int32 netInt99, netInt8;
int xppCompare;
;
netInt99 = 99;
netInt8 = 8;

// Attempt with the >= operator.

if (netInt99 >= netInt8)


{
info("Unexpected.");
}
else
{
info("This proves the X++ >= operator cannot be
used"
+ " meaningfully between two .NET Int32 variables.");
}

// System.Int32.CompareTo method.

xppCompare = netInt99.CompareTo(netInt8);
if (0 < xppCompare)
{
info(strfmt("xppCompare is %1, which means 99 >
8. Good.", xppCompare));
}
else if (0 == xppCompare)
{
info(strfmt("xppCompare is %1, which means 99 ==
8. Unexpected.", xppCompare));
}
else // (0 > xppCompare)
{
info(strfmt("xppCompare is %1, which means 99 <
8. Unexpected.", xppCompare));
}

/***** Output
Message (11:50:53 am)
This proves the X++ >= operator cannot be used
meaningfully between two .NET Int32 variables.
xppCompare is 1, which means 99 > 8. Good.
*****/
}

2-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Compile and Run X++ that Calls CLR Manage Assemblies


When you write X++ code that calls into an assembly that is managed by the
CLR of the .NET Framework, you must make sure that the X++ compiler can
find the assembly.

How CLR Managed Assemblies are Found by the X++ Compiler

If your X++ code calls the .NET Framework class System.String, the X++
compiler finds the managed assembly because of two system configurations:

• In the AOT, there is a reference under the References node to the


assembly that contains the class.
• The assembly is in the Global Assembly Cache.

The installation of Microsoft Dynamics AX includes references to some typically


needed .NET Framework assemblies. If your X++ code calls into a CLR
managed assembly that you wrote, you must follow these steps.

1. Copy your assembly into the client\bin\ directory under the


Microsoft Dynamics AX installation directory.

TIP: Your full path might resemble C:\Program Files\Microsoft Dynamics


AX\version\client\bin\.

2. In the AOT, right-click References, and then click Add Reference.


3. Click the Browse button.
4. In the Select file dialog box, select your assembly file, and then click
Open.

Running on a Tier that Has Your Assembly


Your X++ code might be unable to run on the AOS tier, even though your X++
code compiles successfully on the client. A copy of each assembly that is needed
by your X++ code must exist on the AOS computer for your X++ code to run on
the AOS tier.

To run your X++ code on the AOS tier, you must copy your assembly to the
server\...\bin\ subdirectory on the AOS computer. This is located under the
Microsoft Dynamics AX installation directory.

It is not required to provide any reference to the assembly because the X++ code
is already compiled.

TIP: If you want to run CLR interop code on the server, you must assert
CLRInterop permissions.

2-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

CLR Interop Issues Across Tiers


CLRObject instances cannot be passed between Microsoft Dynamics AX tiers.

A method can run on particular tier either by virtue of the client or server
modifier for static methods, or by virtue of the class being RunOn property being
either client or server for instance methods.

For example, your server method named SS cannot return a .NET Framework
object to another method named CC that calls SS from the client tier.

Example:

The following X++ code example has a server method that is called by a client
method. The server method returns a .NET Framework object of type
System.String. However, .NET Framework objects cannot be serialized and de-
serialized by Microsoft Dynamics AX. Therefore they cannot be returned to a
caller that is running on a different tier (in this case, the client tier).

This X++ code represents the server method that is called


from the client:

public class RunOnTheServerClass


{
public static server System.String
GetASystemStringMethod()
{
System.String sNet;
// Enable CLR interop on a server method.
new
InteropPermission(InteropKind::ClrInterop).assert();

sNet ="The return value.";


return sNet;
}
}

This X++ code represents the client job that calls the
server method.

static void RunOnClientJob(Args _args)


{
System.String sNet;
str strXpp;
// This call fails.
sNet = RunOnTheServerClass ::GetASystemStringMethod();

strXpp = sNet;
info(strXpp);
}

An attempt to run this code example causes an error because the CLRObject is
not initialized.

2-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Catch Exceptions Thrown from CLR Objects


In Microsoft Dynamics AX, when your X++ code calls a .NET Framework
methods make sure that your code is designed to handle exceptions. When your
code catches exceptions it can relay valuable diagnostic information to the user.

The X++ code sample in this section calls methods that are in a .NET assembly.
As recommended, these calls are inside a try block.

To demonstrate the exception handling, the sample intentionally tries to create a


Windows event log source again that causes a duplicate name. The duplicate
causes the system to throw a .NET exception. The sample shows how to obtain
detailed diagnostic information from that exception.

The sample has a catch block for the X++ enum value Exception::CLRError. In
that catch block, the following steps are performed.

1. ClrInterop::getLastException is called.
2. ex.get_InnerException is called.

The following X++ code sample demonstrates how to handle exceptions that are
thrown from .NET methods.

// X++
static void JobCreateEventLog(Args _args)
{
#define.LogSource("Dynamics AX")
#define.LogName("Dynamics AX Log")
System.Exception ex;
System.Diagnostics.EventLog eventLog;
;
try
{
// Create the log if it does not already exist.
if
(!System.Diagnostics.EventLog::SourceExists(#LogSource))
{

System.Diagnostics.EventLog::CreateEventSource(#LogSource,
#LogName);
}

// Next line is an intentional bug for this


demonstration of CLR exceptions.
// It causes an exception because of a name
duplication.

System.Diagnostics.EventLog::CreateEventSource(#LogSource,
#LogName);

// Write to this newly created log source, if


the process comes this far.
eventLog = new System.Diagnostics.EventLog();

2-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

eventLog.set_Source(#LogSource);
eventLog.WriteEntry("The exception should
prevent this line from appearing in the Windows event
viewer.", System.Diagnostics.EventLogEntryType::Warning);
}

catch (Exception::CLRError)
{
ex = ClrInterop::getLastException();
if (ex != null)
{
ex = ex.get_InnerException();
if (ex != null)
{
error(ex.ToString());
}
}
}
// Clean up.

System.Diagnostics.EventLog::DeleteEventSource(#LogSource,
#LogName);
}
/*** Messages displayed in the Infolog:
System.ArgumentException: Source Dynamics AX already exists
on the local computer.
at
System.Diagnostics.EventLog.CreateEventSource(EventSourceCr
eationData sourceData)
at System.Diagnostics.EventLog.CreateEventSource(String
source, String logName)
***/

Additional Information
Use X++ Syntax for CLR Arrays

X++ has syntax that you can use to directly create and handle .NET Framework
arrays. The syntax is an alternative to constructing instances of System.Array
directly, and the underlying effect is the same. The syntax is easier to write than
the verbose alternative of using a variable declared as .NET Framework type
System.Array. For more information, refer to the How to: Use X++ Syntax for
CLR Arrays (http://go.microsoft.com/fwlink/?LinkId=238172) page on MSDN.

Substitute Primitive Parameters Types between the CLR and


X++

In Microsoft Dynamics AX, an X++ str type can be passed in a call to a .NET
Framework method or X++ method that requires a System.String parameter as its
input. However, substitutions in the other direction are not supported. An X++
method that requires an str parameter does not accept a System.String.

2-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The same rule applies to the other X++ primitive types and their .NET
Framework counterparts. Therefore an X++ int parameter can be passed to a
method that takes a System.Int32. However, a System.Int32 cannot be passed
into a method that takes an X++ int. For more information, refer to the How to:
Marshal Between X++ and CLR Primitive Types
(http://go.microsoft.com/fwlink/?LinkId=238171)page on MSDN.

It does not matter whether the method that takes the parameter is a .NET
Framework method or an X++ method.

Use the byref Keyword for CLR Interop

In X++, you use the byref keyword when you call a .NET Framework method
that takes parameters by reference.

For more information about how the byref keyword works with value types and
reference types, refer to the "Understanding the X++ Keyword byref for CLR
Interop (http://go.microsoft.com/fwlink/?LinkId=238174)" page on MSDN.

Reflect on .NET Elements of X++ Methods

In Microsoft Dynamics AX, the DictMethod system class has reflection methods
that can report on the .NET Framework types that an X++ method uses. The
.NET Framework types can be used for parameters, local variables, the return
type, and more. For more information about reflection, refer to the "Reflect on
.NET Elements of X++ Methods
(http://go.microsoft.com/fwlink/?LinkId=238175)" page on MSDN.

Deploy .NET Assemblies for Interop


The topics in this section explain how the .NET Framework assemblies that you
write are deployed for interoperation with Microsoft Dynamics AX.

References versus Visual Studio Projects for Assemblies


in the AOT
This topic describes the developer scenarios that involve .NET Framework
assemblies. You can find information about .NET Framework assemblies in the
following locations in the AOT of Microsoft Dynamics AX:

• AOT > References


• AOT > Visual Studio Projects

The AOS handles the items in these two AOT locations differently from one
another.

2-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

AOT > References


The information in the AOT > References nodes tells Microsoft Dynamics AX
the names of assemblies that it must try to load when they are needed to support,
compile, or run operations. The system looks for the assemblies first in the global
assembly cache (GAC). If the assembly is not found there, the system then looks
under the server\bin\ or client\bin\ directories.

This scenario starts with an existing .NET Framework assembly .dll file. It is not
relevant how the .dll became available. The following list shows the sequence of
events in this scenario:

1. You manually copy the .dll file into your client\bin\ directory.
This step is unnecessary if the assembly is already in the GAC on
your local computer.
2. In the AOT, right-click the References node, and then click Add
reference. The Add reference form is displayed.
3. If the assembly is not in the list, click Browse to open the Select file
form.
4. Browse to the client\bin\ directory and select your .dll file. Then
click the Open button. The Select file form closes.
5. Back in the Add reference form, the .dll file that you selected is
listed in the bottom grid. Select your .dll file.
6. Click OK. The form closes.

You can view your new entry under AOT > References.

AOT > Visual Studio Projects


The AOS and Microsoft Visual Studio work together to automate the deployment
of an assembly and its corresponding project into the metadata stores of the AOS.
After the AOS has this metadata, the AOS can distribute the assembly to clients
as needed.

The following list shows the sequence of events when you use Visual Studio to
write code and compile a .dll assembly file.

1. In Visual Studio you compile your .dll file.


2. Right-click your project node, and then click Add
YourProjectName to AOT. This causes your Visual Studio client to
pass to the AOS textual and binary parameters that represent your
.csproj and .dll files and other files. This adds your project under
AOT > Visual Studio Projects.

Each successive compilation causes Visual Studio to again call the AOS to pass
the latest files to the AOS.

2-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Ongoing Deployments

In the AOT > Visual Studio Projects scenario, you do not have to manually copy
any assembly files to a location. The system handles all the file management. The
AOS contains your assembly in the database that the AOS manages for storing
metadata.

Later, when the .dll file is needed for a process that runs on the AOS, the AOS
copies the .dll file from the database and stores the .dll file under the
server\bin\VSAssemblies\ directory on its local hard disk drive. (The exact
directory path might vary slightly between installations.)

NOTE: In production environments, the AOS has the security authority to write
under its local server\bin\ directory, whereas clients on other computers typically
do not.

If a client needs the .dll file to compile or run X++ code that references classes in
the .dll file, the client calls the AOS for a copy of the .dll file.

Hot-Swapping of .NET Assemblies in the AOS


In your development environment, you can use the hot-swap feature of the AOS
to use updated assembly .dll files without having to repeatedly stop and restart
the AOS. Restarting the AOS closes the connections from other developer
clients, which can be an inconvenience.

NOTE: The hot-swap feature applies only to assemblies that are used by X++
code that runs on the AOS, not for assemblies that are used on the client only.

The following sections explain the importance of application domains in the hot-
swap feature. An application domain is an instance of the .NET Framework class
named System.AppDomain.

Scenario: Hot-Swapping
The primary use for the hot-swap feature is in the following standard
development cycle with Microsoft Visual Studio. This involves the AOT >
Visual Studio Projects area, which is comparable to the Visual Studio Projects
area of the Application Explorer window for Microsoft Dynamics AX in Visual
Studio. The scenario begins with the following steps.

1. In Visual Studio, write the C# code for an assembly .dll that you will
call from X++ code.
2. Compile the .dll. Add more code, and compile again.

2-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

3. Add the Visual Studio project to the Application Explorer window.


Do this by right-clicking the project in Solution Explorer window of
Visual Studio, and then clicking Add YourProjectName to AOT.
This action causes Visual Studio to send various project files to the
AOS, including the assembly .dll file. The AOS saves the contents of
these files in its metadata stores.
4. Start a new Microsoft Dynamics AX AX32.exe client.
In some cases in which the project creates an .exe file instead of a
.dll file, an alternative is to press the F5 key in Visual Studio to run
the code. This also creates a client connection to the AOS.
5. In your AX32.exe client, run X++ code to test the new assembly .dll.
Find a bug that requires a fix.
6. In Visual Studio, modify the C# code, and then compile the assembly
again.
Each compile action sends the updated binary .dll file contents to the
AOS to replace the older version in the metadata stores.
7. Run X++ code to test the modified assembly.

A problem is encountered in the last step of the previous list. The AOS has
already loaded the earlier version of the assembly. You can start the hot-swap
feature to make the AOS load the updated version of the assembly for each new
connection.

The following sections describe the scenarios for the two possible states of the
hot- swap configuration option.

Scenario with Hot-Swapping Off

The hot-swap configuration value is set to off when Microsoft Dynamics AX is


installed. Under this default, one application domain is created when the AOS
starts. No additional domains will be created. All .NET Framework assemblies
that are loaded into the AOS share the single domain. Also, the single domain is
shared by all client connections.

To test the updated assembly, you must restart the AOS. Then connect an
AX32.exe client to the AOS, and run the tests. Having to restart the AOS after
every compilation is inconvenient. The inconvenience is increased if other
developers are sharing the same AOS, because their connections are broken with
each restart. Their connections can be from an AX32.exe client, and from Visual
Studio.

You do not have to stop and restart the AOS when you want the AOS to load a
new assembly that it has not loaded before.

Scenario with Hot-Swapping On

When the hot-swap configuration value is turned on, each new client connection
to the AOS is assigned to a new application domain that is dedicated to that
connection. Each connection has its own application domain. When you create
new application domains, they do not affect other connections.

2-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Each new application domain is populated with the versions of assembly .dlls
that are available to the AOS when the .dlls are loaded into the new domain. In
any given application domain, no updates can be made to any assembly .dll that
is already loaded into the domain.

In Visual Studio, after you modify your C# code and again compile the assembly
.dll, you have to start a new AX32.exe client to gain access to the updated
assembly for testing.

FIGURE 2.6 HOT-SWAPPING ON: EACH CLIENT HAS ITS OWN APPDOMAIN
IN THE AOS

You can turn on the hot swapping feature of the AOS by following these steps:

1. Open the Microsoft Dynamics AX server configuration utility by


clicking Start > Administrative Tools > Microsoft Dynamics AX
2012 Server Configuration.
To change the server configuration, you must run the utility with
administrative privileges.
2. On the Application Object Server tab, select Allow hot swapping
of assemblies when the server is running.
3. Click OK. A prompt will display that asks whether you want to
restart the AOS service. The change takes effect only after you
restart the AOS.

2-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

CAUTION: You should not use the hot-swap feature in your production
environment. The AOS might consume lots of memory caused by an accumulation
of application domains. Many assemblies would be loaded multiple times, which
would waste memory resources.

Summary
The Framework Features chapter introduced several different frameworks
available in Microsoft Dynamics AX.

Developers creating code that is customized by other users should create events
where customizations typically occur. Then, developers customizing the original
functionality in another layer can subscribe to an event. When the customized
functionality is tied to an event, the underlying application code can then be
rewritten and it will have little effect on the customization, if the same events are
raised in the same sequence from one version to the next.

There are many technologies that you can use to programmatically integrate
Microsoft Dynamics AX with other applications so that you can integrate
functionality or exchange data. These technologies include the following.

• Application Integration Framework (AIF)


• .NET Business Connector
• .NET Framework

You can use a proxy class for classes, tables, and enums. A proxy class is a .NET
Framework class that provides access to one X++ item type of Microsoft
Dynamics AX.

Additionally, you can use the .NET interop from X++ to access classes in
assemblies that are managed by the CLR in X++ code, and you can use AOT >
References or AOT > Visual Studio Projects to deploy your .NET assemblies
for interop.

2-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. What is the primary difference between using a reference versus a Visual


Studio project to deploy a .NET assembly for interop?

2. TRUE or FALSE? An X++ int does not marshal to a System.Int64, or the


reverse. A System.Int32 does not marshal to an X++ int64, or the reverse.
( ) TRUE
( ) FALSE

3. Match the eventing terms with their definitions.

_____ 1. The logic that contains the code that causes a. Event
a change. b. Delegate
_____ 2. The definition of the information passed c. Event payload
from the producer to the consumer when an event
d. Producer
occurs
e. Consumer
_____ 3. The application code that represents an
interest in being notified when a specific event
occurs.
_____ 4. A representation of a change that happened
in the producer.
_____ 5. The information that the event carries with
it.

4. TRUE or FALSE? You should only use the hot-swap feature in your
production environment.
( ) TRUE
( ) FALSE

2-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

5. Which of the following methods can be used to subscribe to an event? (Select


all that apply)
( ) Create an event handler underneath a method.
( ) Create an event handler underneath a delegate.
( ) In X++ by using the following command: [DelegateName] +=
EventHandler::[EventHandlerName]
( ) In X++ by using the following command" [EventHandlerName] +=
Delegate::[DelegateName]

6. You can build proxies for which of the following X++ item types? (Select all
that apply)
( ) Base enumerations
( ) Extended data types
( ) Tables
( ) Classes

2-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

2-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 2: Framework Features

Solutions
Test Your Knowledge
1. What is the primary difference between using a reference versus a Visual
Studio project to deploy a .NET assembly for interop?

MODEL ANSWER:

AOT > References require ongoing deployments, whereas AOT > Visual
Studio Projects do not require you to redeploy the .dll files.

2. TRUE or FALSE? An X++ int does not marshal to a System.Int64, or the


reverse. A System.Int32 does not marshal to an X++ int64, or the reverse.
(•) TRUE
( ) FALSE

3. Match the eventing terms with their definitions.

d 1. The logic that contains the code that causes a a. Event


change. b. Delegate
b 2. The definition of the information passed from c. Event payload
the producer to the consumer when an event occurs
d. Producer
e 3. The application code that represents an
e. Consumer
interest in being notified when a specific event
occurs.
a 4. A representation of a change that happened in
the producer.
c 5. The information that the event carries with it.

4. TRUE or FALSE? You should only use the hot-swap feature in your
production environment.
( ) TRUE
(•) FALSE

5. Which of the following methods can be used to subscribe to an event? (Select


all that apply)
(√) Create an event handler underneath a method.
(√) Create an event handler underneath a delegate.
(√) In X++ by using the following command: [DelegateName] +=
EventHandler::[EventHandlerName]
( ) In X++ by using the following command" [EventHandlerName] +=
Delegate::[DelegateName]

2-49
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. You can build proxies for which of the following X++ item types? (Select all
that apply)
(√) Base enumerations
( ) Extended data types
(√) Tables
(√) Classes

2-50
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

CHAPTER 3: APPLICATION FOUNDATION


FEATURES
Objectives
The objectives are:

• Describe how to set up and use the Global Address Book.


• Review the data model and classes for the Global Address Book
framework.
• Create a new entity for the Global Address Book.
• Modify the Extensible Data Security policy for the new Global
Address Book entity.
• Retrieve an address from the Global Address Book on a transaction.
• Describe how extensible data security policies can be used to help
secure your data.
• Create and use extensible data security policies.
• Describe how financial dimensions are used.
• Describe the various types of organizations available in Microsoft
Dynamics® AX 2012.
• Describe how the organization model is used throughout the system.
• Create a custom operating unit, and organization type.
• Describe how cases are used in Microsoft Dynamics AX 2012.
• Create a new case association type.
• Add case management to a form.
• Explain how policy rules are used.
• Review the data model for the policies framework.
• Create a new policy type and policy rule.

Introduction
There are many application foundation features in Microsoft Dynamics AX 2012.
This chapter introduces several of these features.

• Global address book: This feature serves as a central repository for


addresses throughout the system.
• Extensible data security policies (XDS): You can use the XDS
policies to control the security of data within the system.
• Financial dimensions: Financial dimensions provide additional
details in the general ledger and serve as segments in the chart of
accounts.

3-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Organization model: You can use the organization model to


structure legal entities and organization units for security, reporting,
and other functionality within the system.
• Case management: You can use cases to track information about
issues that are related to various data points within the system.
• Policies: Users can use policies to define rules in various modules to
help guide the flow of business inside a particular process.

Global Address Book


The global address book (GAB) framework in Microsoft Dynamics AX 2012 is
used to share information across Microsoft Dynamics AX companies and entities
through a central repository of users and organizations. It is improved to make
sharing easier.

This course highlights the patterns used to consume or update address book
controls. This includes party name/details and postal and electronic addresses.

Benefits and Features


Microsoft Dynamics AX 2009 introduced the address book framework. Each
person or organization in the address book is referred to as a party. Records
stored in the repository about parties are called party records. Party records
include name, address, contact information, and person/organization data.

In Microsoft Dynamics AX 2012, roles that are associated with party records are
referred to as party roles. Party roles include customer, vendor, prospect
(formerly known as business relations), contact, worker, applicant, competitor,
legal entities, operating units, teams, prospective vendors, and personal contacts.
A single party can be associated with one or more party roles in a Microsoft
Dynamics AX company. For example, the organization party of A. Datum
Corporation can be associated with a customer, prospect, and vendor in the
Microsoft Dynamics AX company CEE and can also be associated with a vendor
in the Microsoft Dynamics AX company CEU. Benefits of this shared data
include the following.

• Demonstrates how people and organizations have relationships with


other areas of the enterprise. The relationship and communication
between two organizations changes when one organization has more
than one role such as a vendor and customer. There might be special
agreements that can be negotiated to encourage a closer partnership
with the other organization.
• Ease of setup and maintenance. For example, when a change is made
to an address, the update only has to be made in one place; all of the
other associated records are updated automatically.

3-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Data Normalization
Most of the transactions and journals have address information for example: sales
orders have delivery addresses, and invoices have billing addresses. In earlier
versions of Microsoft Dynamics AX the address is stored on the header and each
line for each transaction. Additionally, the address is also stored with the journals
or packing slips that are generated from the transaction.

This pattern caused significant repetition of data. For example, entering a 10-line
quotation and moving it step-by-step to an invoice means the same address could
be stored 88 times. In Microsoft Dynamics AX 2012, address duplication is
reduced by storing the address one time and having each transaction or journal
table reference the address record.

Address Defaulting
An address defaulting methodology is implemented that lets users select which
address should be used as the default for a transaction. The customer, vendor,
legal entity, and prospect forms let the user specify a default address for a
specific purpose. Depending on the transaction, there are different defaulting
flows for addresses.

Terminology
The terms used with the GAB include the following.

• Party: A person or organization. A party can be internal or external


to an organization.
• Address book: Group of parties.
• Party roles: Entities that refer to customers, vendors, competitor,
worker, applicant, and prospect are a few examples.
• Non-party entities: Refers to inventory, bank group, bank accounts,
and so on.
• Location: Refers to either a postal address or electronic address
(contact information such as telephone, fax, URL, email, telex).

3-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Party and Address Book Data Model


The following figure shows the core party and address book data model.

FIGURE 3.1 CORE PARTY AND ADDRESS BOOK DATA MODEL

In the earlier versions, the party tables, including DirPartyTable, are striped by
dataArea, and are shared across companies by virtual tables.

In Microsoft Dynamics AX 2012, the use of dataArea is removed for party


related tables. This means that the party data is not saved for each company
(SaveDataPerCompany = No). Party tables are now shared, which means that the
need for setting up virtual tables is eliminated.

In Microsoft Dynamics AX 2012, names for organization and person are now
date-effective. Date-effective names are supported by the use of the
ValidTimeStateFieldType property of the table. The affected tables include
DirOrganizationName and DirPersonName.

3-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Postal Address and Contact Information Data Model


The following figure shows the postal address and contact information data
model.

FIGURE 3.2 LOCATION DATA MODEL

In the earlier versions, primary address and contact information for party entities
is stored in the table for each entity (vendor, customer, worker, contact person,
prospect (business relation), applicant, competitor, and external and internal
organizations.

In Microsoft Dynamics AX 2012, the Address table is now deprecated and is


replaced by the shared table LogisticsPostalAddress. All address fields are now
removed from party and non-party related tables. Information from these tables
moved to the LogisticsPostalAddress table. Contact information fields are now
also removed from party related tables and moved to the
LogisticsElectronicAddress shared table. Non-party related contact information
fields remain unchanged.

3-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

In Microsoft Dynamics AX 2012, the primary address and contact information is


now stored in the shared tables LogisticsPostalAddress and
LogisticsElectronicAddress. Unlimited numbers of records can be created for
postal address and contact information by using a relationship table. For
example, DirPartyTable uses DirPartyLocation to associate party record to
locations.

In Microsoft Dynamics AX 2012, postal address and contact information are


data-effective. This enables you to create future effective records and keeps track
of changes to these records.

DirPartyLookup Class
Both the DirPartyRecId and DirPersonRecId extended data types automatically
inherit the lookup for party or person without any filter.

If you need the lookup to be filtered, you can use the DirUtility::nameLookup()
or DirUtility::personNameLookup() to do this. This uses the
DirPartyLookupEntitiesFilter class to filter by the party role. For more
information, refer to the following code sample taken from the
AuditPolicyAdditionalOption form.

public Common lookupReference(FormReferenceControl


_formReferenceControl)
{
Common ret;
dirPartyLookupEntitiesFilter
dirPartyLookupEntitiesFilter;
dirPartyLookupEntitiesFilter =

dirPartyLookupEntitiesFilter::generateDirPartyLookupEntitie
sFilter(
(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::All ? NoYes::Yes :
NoYes::No),

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::CustomersOnly ?
FilterStatus::Set
: FilterStatus::Undefined),

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::VendorsOnly ?
FilterStatus::Set
: FilterStatus::Undefined),

(auditPolicyListParty.AddressBookRole ==

DirPartyRoleView::BusinessRelationsOnly ? FilterStatus::Set
: FilterStatus::Undefined),

3-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::CompetitorsOnly ?
FilterStatus::Set
: FilterStatus::Undefined),

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::ContactsOnly ?
FilterStatus::Set
: FilterStatus::Undefined),

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleView::EmployeesOnly ?
FilterStatus::Set
: FilterStatus::Undefined));

(auditPolicyListParty.AddressBookRole ==
DirPartyRoleViewApplicantsOnly ?
FilterStatus::Set
: FilterStatus::Undefined));

ret = DirUtility::namelookup(_formReferenceControl,

auditPolicyListParty,

DirPartyType::None,
element,
false,

dirPartyLookupEntitiesFilter);
return ret;
}

The AuditPolicyListParty table contains the list of monitored parties by an audit


policy. During audit policy execution, the list of monitored parties will be
returned defined for the policy and the documents associated with the parties will
be checked for audit policy violation.

Adding an Address to an Entity


When you add an address to an entity in Microsoft Dynamics AX, you must first
determine whether the entity should have one address or multiple addresses.

The following forms are examples that use single address logic.

• BankAccountTable
• BankGroup
• IntrastatParameters
• CustBankAccounts
• VendBankAccounts
• HcmWorkerBankAccounts

3-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

TIP: Because creating postal addresses involves large amounts of logic,


including validation, formatting, and field references; we recommend that you
use the LogisticsPostalAddress form to manage new addresses.

The following forms are examples that use multiple address logic.

• CustTable
• tutorial_Form_GABPrimitive
• HcmApplicantBasket
• InventLocation
• VendTable
• HcmWorker

Procedure: Add a Single Address to an Entity


To add a single address to an entity, follow these steps.

1. Use or extend the LogisticsPostalAddressFormHandler class to


implement single address on a form.

2. Create menu items for the New, Edit, Clear and Map buttons with the
following properties. When you are finished creating the menu items,
add them to the form in a button group.

a. Label = @SYS2055 (New), @SYS2475 (Edit), @SYS2079 (Clear),


@SYS136333 (Map)
b. ObjectType = Class
c. Object = LogisticsPostalAddressFormHandler
d. EnumTypeParameter = LogisticsLocationAddressActionButtons
e. EnumParameter = New, Edit, Clear or Map
f. OpenMode = New or Edit (do not set on Clear and Map)
g. NormalImage = 11045 (New), 7696 (Edit), 10563 (Clear), 10041
(Map)
h. ImageLocation = EmbeddedResource

3. On the form where the address part will be added do the following.

a. Add the form handler class in the classDeclaration.

public class FormRun extends ObjectRun


{
LogisticsPostalAddressFormHandler
addressController;
// or the new derived class
}

b. Add a form method called getAddressController.

3-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

public LogisticsPostalAddressFormHandler
getAddressController()
{
return addressController;
}

c. Override the main data source active method.

public int active()


{
int ret;
ret = super();
if (ret)
{
addressController.callerActive();

addressController.callerUpdateButtons(newAddress,
editAddress, clearAddress, mapButton);
}
return ret;
}

d. Add LogisticsPostalAddressTable as a data source and override the


validateWrite and write methods.

public boolean validateWrite()


{
return true;
}

public void write()


{
//super();
}

TIP: We recommend that you use the right-click > Duplicate feature in the
Application Object Tree (AOT) and the drag-and-drop functionality. This also
works for methods.

Procedure: Add Multiple Addresses to an Entity


To add a single address to an entity, complete the following steps.

1. Use or extend the LogisticsEntityPostalAddressFormHandler class to


implement unlimited address association.

2. Create menu items for the Add, Edit, Deactivate, Remove, Advanced
and Map buttons with the following properties.

a. Label = @SYS2318 (Add), @SYS2475 (Edit), @SYS23466


(Advanced), @SYS134283 (Deactivate), @SYS311855 (Remove),
@SYS136333 (Map)

3-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

b. ObjectType = Class
c. Object = LogisticsEntityPostalAddressFormHandler
d. EnumTypeParameter = LogisticsLocationAddressActionButtons
e. EnumParameter = 0 – New, 1 – Edit, 3 – Map, 4 – Delete, 5 –
Advanced, 6 – Deactivate
f. LinkedPermissionType = Form
g. LinkedPermissionObject = LogisticsPostalAddress
h. NormalImage = 11421 (Add), 10040 (Edit), 10106 (Advanced), 11438
(Delete), 10041 (Map), 10039 (Deactivate)
i. ImageLocation = EmbeddedResource
j. OpenMode = New, Edit, Auto (for Advanced, Map, Delete and
Deactivate)

3. Add these menu items on the Action Pane in your form.

4. Create a grid with LogisticsEntityPostalAddressView as the data source,


set as Passive linkType, AutoSearch=No. Do the following.

a. Add the placeholder variable for the selected/active postal address in


the classDeclaration.

public class FormRun extends ObjectRun


{
LogisticsLocationRecId postalAddressLocation;
}

b. Add a form method called parmPostalAddressLocation.

public LogisticsLocationRecId
parmPostalAddressLocation(LogisticsLocationRecId
_postalAddressLocation =
dirPartyPostalAddressView.Location)
{
postalAddressLocation = _postalAddressLocation;
return postalAddressLocation;
}

c. Override the main data source active method.

public int active()


{
int ret;
ret = super();
if (ret)
{

LogisticsEntityPostalAddressView_ds.executeQuery();
}
return ret;
}

d. Add LogisticsEntityPostalAddressView as a data source and override


the executeQuery method.

3-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

public void executeQuery()


{

DirPartyPostalAddressView::updateQuery(this.query().d
ataSourceName(this.name()), custTable.Party);
super();
this.updateButtons();
if (postalAddressLocation != 0 &&
postalAddressLocation !=
dirPartyPostalAddressView.Location)
{

this.findValue(fieldnum(DirPartyPostalAddressView,Loc
ation),SysQuery::value(postalAddressLocation));
}
}

Global Address Book Security


You can set security privileges to party records in the following ways:

• Secure by legal entity: Security privileges are based on the legal


entity that a party is associated with. If you secure party records by
legal entity, workers can only access the records that are associated
with any legal entity that the worker has access to.
• Secure by address book: Security privileges are based on teams.
With this method, only workers who are assigned to a team that has
access to an address book can view the party records in that address
book.
• Secure by both legal entity and address book: Security privileges
are based on both legal entities and teams.

You can create address books at any time and if you select, you can set security
parameters for the address books at any time. Setting security for address books
is not required in Microsoft Dynamics AX. However, if you do not restrict access
by legal entity, or if security privileges are not set for an address book, all
workers in your organization can view all party records. You can use the
Security policy options link in the Global address book parameters form to
select whether the enforcement of security privileges for address books is based
on teams, legal entities, or both.

Each method for setting security privileges on the global address book uses an
extensible data security (XDS) policy in the AOT. When you add a new global
address entity, we recommend that you add your address entity tables as
constrained tables to the appropriate security policies in the AOT.

3-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Extensible Data Security Policy Framework


Developers and administrations can use security policies to block access to
subsets of rows in tables. A policy resembles a where clause in an SQL select
statement. A security permission increases the access a user has to data. But a
security policy decreases access to data.

In the AOT, policies are displayed under Security > Policies.

Security policies are enforced in the Application Object Server (AOS). All access
mechanisms that route through the AOS are subject to policy enforcement. These
access mechanisms include forms, Enterprise Portal webpages, SSRS reports,
and calls from class methods.

FIGURE 3.3 CONCEPTUAL MODEL OF EXTENSIBLE DATA SECURITY

Concept Review
The following list defines the concepts of the XDS model.

Primary table
You can use a primary table to help secure the content of the related constrained
table. For example, in a policy restricts access to all sales orders based on the
CustGroup foreign key value, the Customer table would be the primary table.

Policy query
You can define a policy query by specifying a value for the Query property in the
AOT at Security > Policies > YourPolicy. You can use a policy query to help
secure the constrained tables specified in a given security policy. The query
selects data from a primary table. The values in that data are then used to restrict
the data returned from the constrained table.

3-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Constrained tables and views


A security policy could constrain the data access of the SalesTable to only those
records that have one particular CustAccount foreign key value. You can define
constrained tables and views in the AOT at Security > Policies > YourPolicy >
Constrained Tables.

Context
A policy context controls the circumstances under which a given policy applies.
The policy is not enforced unless the context is set. The types of policy contexts
are as follows.

• Role context: Can enable policies that are based on the roles to
which the user is assigned.
• Application context: Can enable policies that are based on
information which is set by the application.

Security Policies
A policy specifies the table row or record that can be accessed. This resembles
the WHERE clause in a SQL view or statement that specifies the table records to
be returned.

All security policies start with a query that is defined under AOT > Queries. The
VendProfileAccountPolicy query, shown in the following image, is the basis for
the policy that is described in this topic.

FIGURE 3.4 VENDPROFILEACCOUNTPOLICY QUERY

3-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Range Affects the Security Policy


This figure shows a range on the query. The range requires that the field
VendProfileAccountPolicy. User has a value of the (currentUserID()) (which
returns the user who is currently logged on), on every data record that users in the
associated role can view. This means the policy will prevent access to
VendProfileAccountPolicy table records that are not for the current user.

NOTE: There is a second range on the table that requires the


VendProfileAccountPolicy.ExternalEntityType to be equal to Vendor.

Relation Affects the Security Policy


This relation works in combination with the range. This relation means the policy
will prevent access to records in the UserExternalParty table unless those records
are related to a VendTable record that has User equal to the current user logged
on and the externalEntityType is equal to vendor.

The most important property of a policy is its Query property. The PrimaryTable
property is set to the first data source of the query.

The following figure has the VendProfileAccountpolicy node highlighted under


AOT > Security > Policies.

FIGURE 3.5 VENDPROFILEACCOUNT SECURITY POLICY

3-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

This figure shows the ConstrainedTable property of the policy.

• No: Means the policy does not restrict the data values in records that
are returned from the primary table.
• Yes: Means the policy does restrict the data values in records that are
returned from the primary table.

Trimming
The security configuration of each field is assessed for the current user. This
security behavior is called field trimming because the restricted fields are
trimmed out of the results before the results are sent from the AOS to the client.
The code sample scans all fields that are under AOT > Data Dictionary >
Tables, for a specified range of tables.

When a user runs a query, the system can refuse to send data from the AOS for
particular columns that the current user has no authorization to access. The
access is controlled by the AOSAuthorization property that is available on each
field during run time. This property value cannot be known at compile time. The
run time value of the AOSAuthorization property is controlled by the roles that
the user belongs to.

The following code sample scans the system tables to find fields that the current
user cannot access, on tables that he can otherwise access. The code prints
progress reports to the Print window while it runs. The final output of field
names appears in the Infolog window.

The macros near the top of the code sample are explained in a section that
follows the code sample.

static void GmTrimAccessFieldScan3Job(Args _args)


{
// Edit the following three macro values to your
needs. For example:
// ** Start: with a table whose name starts with an
'A'.
// ** Stop: with a table whose name starts with a 'Z'.
#define.SearchTableNameRangeStart("")
#define.SearchTableNameRangeStop("")
#define.TargetTableNameLikeFilter("*")

TreeNode tnTable,
tnField;
str sTableAosAuth,
sFieldAosAuth;
int nCountOfTpfTablesFound = 0,
nCountOfAotTables = 0,
nCountOfTrimmedFields = 0;

// Establish start node among the table nodes.


if (#SearchTableNameRangeStart =="")
{

3-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

tnTable = TreeNode::findNode
("\\Data
Dictionary\\Tables").AOTfirstChild();
}
else
{
tnTable = TreeNode::findNode
("\\Data (file://\\Data)
Dictionary\\Tables\\" + #SearchTableNameRangeStart);
}

while (true)
{
nCountOfAotTables++;
// Provide ongoing progress reports.
if ((nCountOfAotTables MOD 50) == 3)
{
print int2Str(nCountOfAotTables)
+ " tables examined to this point,
at " + tnTable.AOTname();
print int2Str(nCountOfTpfTablesFound) + "
TPF okay tables found to this point.";
print int2Str(nCountOfTrimmedFields) + "
trimmed fields found to this point.";
print "---------------- Wait...";
}
// Perhaps stop before the end of the AOT, for
convenience.
if (#SearchTableNameRangeStop < tnTable.AOTname()
&&
#SearchTableNameRangeStop !="")
{
break;
}

// Apply the table name wildcard filter.


if (tnTable.AOTname() like
#TargetTableNameLikeFilter)
{
sTableAosAuth =
tnTable.AOTgetProperty('AOSAuthorization');
// Test whether there is authority to
access the table, under TPF.
if (sTableAosAuth != 'None')
{
nCountOfTpfTablesFound++;
// Loop through the fields on
this table.
for (tnField =
TreeNode::findNode
('\\Data
Dictionary\\Tables\\'
+
tnTable.AOTname()

3-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

+
'\\Fields').AOTfirstChild();
tnField;
tnField =
tnField.AOTnextSibling()
)
{
sFieldAosAuth =
tnField.AOTgetProperty('AOSAuthorization');
// Test whether there is
authority to access the field.
if (sFieldAosAuth !=
'No')
{

nCountOfTrimmedFields++;
info(strFmt('%1 %2
is a trimmed field that you cannot access.',
tnTable.AOTname(),
tnField.AOTname()));
}
} // for each field in AOT
} // if table is guarded by the Table
Protection Framework (TPF).
} // name is Like

// Prepare for next iteration of this loop.


tnTable = tnTable.AOTnextSibling();
if (tnTable == null) break;

} // for each table in AOT

print "-------- Final Report (see also the Infolog)


--------";
print int2Str(nCountOfAotTables)
+ " tables examined to this point,
at end.";
print int2Str(nCountOfTpfTablesFound) + " TPF tables
found to this point, at end.";
print int2Str(nCountOfTrimmedFields) + " trimmed
fields found to this point, at end.";
print "-------- Done. --------";
pause;
}

TIP: You can import the AX2012_ENUS_DEVIV_03_TRIMMINGJOB.xpo


provided with your training image. The file contains the code sample provided.

3-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Demonstration: Create a Simple Default Security Policy


The following steps demonstrate how to add an XDS policy for specific customer
groups.

Inspect that Data You Want to Help Secure

1. Open the Microsoft Dynamics AX client.


2. Open Accounts receivable > Setup > Customers > Customer
groups.
3. Verify that the Major customers customer group has an ID value of
20. You will create a policy so that an application user can only work
with data for this customer group.

Create a Query for Your Security Policy

Each security policy relies on a query. The ranges of the query are a primary
element of the security policy. You can create a new policy query by following
these steps:

1. Create a policy query by right-clicking the Queries node in the


AOT, and then clicking New > Query. Rename the new query to
MajorCustomersPolicyQuery.
2. Locate Data Sources under the MajorCustomersPolicyQuery node.
Add a new data source.
3. In the Properties window for the new data source, set the Name
property to CustGroup_1, and the Table property to CustGroup.
4. Right-click the Ranges node and select New Range.
5. In the Properties window for the new range, set the Field property
to CustGroup, and the Value property to 20.
6. Locate Fields under the MajorCustomersPolicyQuery > Data
Sources > CustGroup_1 node.
7. In the Properties window for Fields, set the Dynamic property to
Yes. The Yes value indicates that all fields are queried.

Create a Security Policy

You can create a security policy by following these steps:

1. Expand the Security node in the AOT window, and then right-click
the Policies node and select New Security Policy. Rename the new
security policy to MajorCustomersPolicy.
2. In the Properties window for MajorCustomersPolicy, set the
following properties:
o Name = MajorCustomersPolicy
o Label = Restrict data to major customers
o PrimaryTable = CustGroup
o Query = MajorCustomersPolicyQuery

3-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

o PolicyGroup = Customer group based policy


o ConstrainedTable = Yes
o Enabled = Yes
o Operation = All operations

3. Save and compile the security policy.

The security policy is now ready for deployment and testing. Notice that the
ContextType property is currently set to the value ContextString, but the
ContextString property is empty. This combination implies that when it is
enabled, this security policy will always be applicable for all users.

Verify that the Security Policy is Enforced

As an application user, you can now verify that the security policy that you have
created is enforced by the system.

1. Assign an application user to the Sales manager role. Open System


administration > Setup > Security > Assign users to roles.
2. Log on to the system as that application user.
3. Open Accounts Receivable and open Setup > Customers >
Customer groups.
4. Verify that the application user can view only the Major customers
customer group.
5. Try to insert a record and verify that the application user cannot add
any other customer group.

When you try to insert a record, the code output to the Infolog window is visible
, and you receive the following error message.

"Cannot create a record in Customer Groups (CustGroup). Security Policy


permission denied."

Demonstration: Constrain Access to Related Tables


In this demonstration a pre-existing security policy is modified to reduce the
range of data records that roles and users can access in the CustTable table and
the SalesTable table. You do this by adding the two tables under the Constrained
Tables node of the pre-existing policy.

The security policy already exists for the CustGroup table. The pre-existing
security policy is named MajorCustomersPolicy. The PrimaryTable property of
the policy names the CustGroup table.

Foreign key relations are used by the policy to determine which data records the
users are authorized to access on the constrained tables. The CustGroup table is a
parent of the CustTable table, which has a foreign key field that references the
primary key of the CustGroup table. And the CustTable table is a parent of the
SalesTable table.

3-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Add to the List of Constrained Tables on the Policy

You can add tables to the list under the Constrained Tables node of a security
policy. The policy denies access to some data records in the constrained tables.
The particular records that are denied are determined by the foreign key
relationships among the tables in the policy. A record on a constrained table can
be accessed only if the foreign key value in the record matches the primary key
value of a record that can be accessed in the primary table of the policy.

You can add the CustTable table as a constrained table by following these steps:

1. Right-click the Constrained Tables node on policy


MajorCustomersPolicy, and then click New > Add table by
relation.
2. Set the Table property to CustTable.
3. Set the property TableRelation to CustGroup.

Chains of Constrained Tables in a Policy

In this section, you constrain the SalesTable table. You constrain it by associating
it to the constrained CustTable table that you added in the previous section. The
SalesTable table is related to the CustGroup table indirectly through the
CustTable table.

You constrain the SalesTable table by following these steps:

1. Right-click the node MajorCustomersPolicy > Constrained


Tables > CustTable, and then select New > Add table by relation.
2. Set the Table property to SalesTable.
3. Set the TableRelation property to OrderCustomer.

Constrain Views by the Policy

There are no named relations between a view and a table, the way there are
between two tables where a formal foreign key is defined. However, in a security
policy under its Constrained Tables node, you can define a relation between a
view and one of the tables that the view references. You do this by setting the
Value property of the view to a value that has the following format:
(Table.FieldName=View.FieldName). You can also enter multiple field relations
in the following format: ((Table.Field1=View.Field1) &&
(Table.Field2=View.Field2)).

In the following steps, you improve the security policy to constrain access to data
from a view.

1. Right-click the MajorCustomersPolicy > Constrained Tables >


CustTable node and select New > Add table or view by free form
expression.
2. Set the Value property of the view to (smmCustomerView.Party =
CustTable.Party).

3-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Verify that the Security Policy is Enforced on Related Tables


and Views

As an application user, you can now verify that the security policy that you have
created is enforced by the system.

1. Manually assign an application user to the Sales manager role by


using the System administration form.
2. Log on to the system as that application user.
3. Open Accounts Receivable and open Common > Customers > All
Customers. Verify that only customers in customer group 20 are
shown. Confirm that you can personalize the form and add the
Customer.CustomerGroup field to the form.
4. Verify that the application user can only see the Major customers
customer group.
5. Open Sales and marketing and open Common > Sales orders >
All sales orders.
6. Verify that you can only view the sales orders for customers of the
Major customers group.

Demonstration: Add Role Context to a Security Policy


In this demonstration a policy is modified to apply it to security roles.

Change the Security Policy to Specify a Security Role

1. Change the ContextType property on the policy node


MajorCustomersPolicy to RoleName.
2. Set the RoleName property on the policy node to
TradeSalesManager.

Verify that the Security Policy is Enforced

As an application user, you can now verify that the new security policy is
enforced by the system.

1. Manually assign an application user to the Sales manager role by


using the System administration form.
2. Log on to the system as an application user.
3. Open Accounts Receivable > Setup > Customers > Customer
groups.
4. Verify that the application user can only view the Major customers
customer group.

NOTE: You can run another test as another user who is not assigned to the Sales
manager role, but does have access to customer groups to verify that all
customer groups are available when the Sales manager role is not assigned.

3-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 3.1 - Extensible Data Security Policies


This lab demonstrates how to create a new extensible data security policy for a
specific group of customers.

Estimated time to complete this lab: 15 minutes

Scenario

Claire, the HR Manager, should only be able to view vendors that are in the
employee vendor group. Employees are currently assigned to the "Other" vendor
group.

Simon, the Business Systems Developer, must create a new extensible data
security policy to restrict the HR Manager role to only view Other vendors.

Challenge Yourself!
Use the information that is provided to create a new extensible data security
policy for the HR Manager role that restricts access to view only vendors in the
Other group.

Need a Little Help?

1. Review the Vendor groups form in Accounts payable > Setup.


2. Create a new query for the VendGroup table.
3. Create a new security policy that uses the query that you created.
4. Add table constraints for the VendTable and PurchTables.
5. Set the ContextType and Role properties on the security policy.

Step by Step
Inspect the Data You Want to Help Secure

1. Open the Microsoft Dynamics AX client.


2. Open Accounts payable > Setup > Customers > Customer
groups.
3. Verify that the Other vendors vendor group has an ID value of 80.
You will create a policy so that an application user can only work
with data for this vendor group.

3-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Create a Query for Your Security Policy

To create a new policy query, follow these steps.

1. Expand the Security node in the AOT window, and then right-click
the Policies node and select New Security Policy. Rename the new
security policy to OtherVendorsPolicyQuery.
2. Locate Data Sources under the SecurityPolicy >
OtherVendorsPolicyQuery node. Add a new data source.
3. In the Properties window for the new data source, set the Name
property to VendGroup_1, and the Table property to VendGroup.
4. Right-click the Ranges node and select New Range.
5. In the Properties window for the new range, set the Field property
to VendGroup, and the Value property to 80.
6. Locate Fields under the OtherVendorsPolicyQuery > Data
Sources > VendGroup_1 node.
7. In the Properties window for Fields, set the Dynamic property to
Yes. The Yes value indicates that all fields are queried.

Create a Security Policy

To create a security policy, follow these steps:

1. Create a security policy query by right-clicking the AOT, and then


clicking New > Security > Security Policy. Rename the new
security policy to OtherVendorsPolicy.
2. In the Properties window for OtherVendorsPolicy, set the following
properties:
o Name = OtherVendorsPolicy
o Label = Restrict data to other vendors
o PrimaryTable = VendGroup
o Query = OtherVendorsPolicyQuery
o PolicyGroup = Vendor group based policy
o ConstrainedTable = Yes
o Enabled = Yes
o Operation = All operations

3. Save and compile the security policy.

Constrain Tables

You can add the VendTable table as a constrained table by following these steps:

1. Right-click the Constrained Tables node on the


OtherVendorsPolicy policy, and then click New > Add table by
relation.
2. Set the Table property to VendTable.

3-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

3. Set the property TableRelation to VendGroup.


4. You constrain the SalesTable table by following these steps:
o Right-click the node OtherVendorsPolicy > Constrained
Tables > VendTable, and then select New > Add table by
relation.
o Set the Table property to PurchTable.
o Set the TableRelation property to OrderVendor.

Specify a Security Role

1. Change the ContextType property on the policy node


OtherVendorsPolicy to RoleName.
2. Set the RoleName property on the policy node to
HCMHumanResourceManager.

TIP: You can import the AX2012_ENUS_DEVIV_03_01_LAB_SOL.xpo file to


verify and compare your solution.

3-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Financial Dimension Framework


You can use financial dimensions to track additional dimension values when
entered in account entry controls along with a main account. The order in which
these dimensions are entered and constraints of the valid values are defined by
account structures, and optionally by account rules and rule structures.

• System-defined: The values of these financial dimensions are


derived from an existing entity also known as the backing entity. For
example, the Customer system-defined dimension uses the values
from the CustTable. You do not need to maintain a separate list of
customers in dimensions and cannot add new values specifically as
dimension values that are not already used as a customer directly
somewhere else. The values in the backing entity table (CustTable in
this example) are automatically used as the dimension values.
• User-defined: The values for these financial dimensions are
maintained solely within the financial dimensions module and have
no meaning or usage outside of financial dimensions. To create a
user-defined financial dimension, select < Custom dimension > in
the Use values from list field on the Financial dimensions form.

Dimensions in the System


Out of the box, no financial dimensions are provided. The user must define each
financial dimension to be tracked and for user-defined dimensions, the list of
values to select from. The dimensions must then be added as segments to an
account structure or an advanced rule structure to be used throughout the system.
Once these structures are activated and added to the chart of accounts,
transactions in each legal entity that the chart of accounts is linked to can use the
dimensions.

Dimension values can be defined on master data such as customers or vendors.


The dimension information is then merged to transactional data such as purchase
orders and sales orders as default values, which the user can override. For
example, when a sales order invoice is generated, the dimensions are merged to
the update tables that are used for invoicing, and then merged to the customer
transactions, invoice tables, and general ledger transaction tables when the
document is posted.

Development with the Financial Dimension Framework


Your business requirements might require that you extend the financial
dimension framework. There are two basic ways that you can use the framework.

• Making a table dimensionable by adding it as a system-defined


dimension. This is done by creating new DimAttribute[entityName]
views.

3-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Adding account entry or dimension controls to the user interface.


This is done by using one of the financial dimension controller
classes that are provided with Microsoft Dynamics AX 2012. A few
examples of controllers that can be used include
LedgerDimensionAccountController,
LedgerDimensionDefaultAccountController, and the
DimensionDefaultingContoller classes.

NOTE: For more information about the financial dimension framework and
examples of adding controls to forms and creating a new system-defined
dimension, refer to the “Use and Design of the Ledger Module” chapter in this
course.

Organization Model Framework


The organization model represents internal control, data security access, and
performance reporting structures designed to divide responsibility for human and
operations resources and work processes.

The organization model in Microsoft Dynamics AX 2012 introduces two new


concepts—legal entity and operating unit.

Legal Entities
A legal entity is an organization with a registered or legislated legal structure that
is granted the authority to enter into legal contracts that is required to prepare
statements that report on its performance.

A legal entity and company in Microsoft Dynamics AX 2012 are semantically


the same. However, some functional areas in the application are still based on a
data model that uses company (or DataArea). These areas can have the same
limitations as in Microsoft Dynamics AX 2009, and can have an implicit data
security boundary.

Operating Units
An operating unit is an organization that divides the control of economic
resources and operational processes among people who have a duty to maximize
the use of scarce resources, to improve processes, and to account for their
performance.

Several types of operating units are available out of the box.

• A business unit is primarily an operating organization with a focus


on industries or product lines that the organization is supposed to
serve.
• A cost center is a type of operating unit that describes an
organization used for tracking costs or expenses. It is a cost
accumulator, and is used to manage costs.

3-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

• A department is a type of operating unit that can have profit and loss
responsibility and could be a grouping of cost centers. Departments
are also frequently created based on functional responsibility or skill,
such as sales and marketing.
• A value stream is a type of operating unit typically used in lean
manufacturing. In lean manufacturing, a value stream owns one or
more production flows that describe the activities and flows needed
to supply a product, good, or service to the consumers of the product.

A team is also a type of an internal organization. However, it is an informal


group of people primarily created for a specific purpose over a short duration.
Teams can be created for specific projects or services. The other types previously
described are more permanent, although there might be major restructuring
related changes or frequent minor updates.

When legal entities and operating units are arranged into hierarchies and used for
reporting rollup, security access, and business policies, they help enable internal
control of your business.

Organization Hierarchies
You can set up organizational hierarchies to visually model your business from
different perspectives. For example, you can set up a hierarchy of legal entities
for tax, legal, or statutory reporting. Then you can set up another hierarchy that is
based on operating units that represents the way that you report financial
information that is not legally required. However, that is used for internal
reporting. For example, you can create a purchasing hierarchy to control
purchasing policies, rules, and business processes.

IMPORTANT: The only way to report based on the hierarchy is through


dimensions. Microsoft Dynamics AX 2012 does not use the hierarchy for
financial reporting.

TIP: Microsoft Dynamics AX 2012 does not support the hierarchies in the
account structures. If you have at least two segments backed by an organization
unit in the hierarchy, you can select the hierarchy in the Configure account
structure form by clicking the Relationships button. When you do this, the system
will adhere to the hierarchy and not force users to also set up the constraints in
the account structure.

Organizations in a hierarchy can share parameters, policies, and transactions. An


organization can inherit or override the parameters of its parent organization.
However, shared master data, such as products and address books, applies to the
whole organization and cannot be overridden for individual organizations.

3-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

NOTE: For more information about how to plan and implementing the
organization model, refer to the Organization Model chapter in the Installation
and Configuration course, or the "Implementing and Extending the Organization
Model" white paper.

Application Scenarios
The organization model is integrated with the application modules in Microsoft
Dynamics AX. There are two types of scenarios:

• The organization model framework is integrated with other


application frameworks.
• Transaction scenarios use integrations to create end-to-end scenarios.

The organization model is tightly integrated with following frameworks.

Address Book

All internal organizations—legal entity, operating unit, and team—are types of


the Party entity. This means that these organizations take advantage of the
capabilities of the address book to store address and contact information.

Financial Dimensions

Legal entities and operating units can be used to define financial dimensions, and
those financial dimensions can be used in account structures.

By using organizations as financial dimensions, you can perform an analysis of


an organization’s financial performance. The relationships between organizations
described through hierarchies can also be used as constraints if two types of
organizations are used as separate financial dimensions in the account structure.

Policy Framework

In Microsoft Dynamics AX 2012, a business policy can be defined for an


organization by using the policy framework. The policy framework can be used
to define policies for expense reports, purchase requisitions, audit control of
documents, and vendor invoice payments.

The policy framework provides support for override and default behavior for
organizations based on their hierarchies, and enables internal management
control of organizations to facilitate cost control, fraud detection, better operating
efficiency, and better performance generally.

Extensible data security

Companies provided the data security boundary for most application data in
previous releases. The new extensible data security framework provides
capabilities to help secure data based on any condition.

3-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

A common scenario for data security is to filter master data or transaction data
based on a user’s association to internal organizations. The master data or
transaction data entity must have a foreign key relationship (field on the entity
table) with the organization to be able to set up a security policy.

Transaction Scenarios
There are several application areas that use the new organization model
framework. The primary effect is in the following modules. Here is a brief
description of the usage. For a complete description and steps for the scenarios in
these areas, refer to the Help documentation.

Procurement and sourcing

The lines of a purchase requisition are created for a buying legal entity, and they
are received in an operating unit such as a cost center or department. A purchase
requisition is created for a requester and is prepared by a preparer. Various
scenarios are enabled where you could view or create purchase requisitions for
all buying legal entities and receiving operating units in which you have access to
create requisitions.

Human resources

In human resources, workers hold employment contracts in a legal entity and


have a position in a department. All transaction scenarios in human resources
take advantage of these concepts to view and modify data.

Travel and expense

Expense reports and lines carry a legal entity to which the expense line item
should be charged from a statutory perspective, and they also carry an operating
unit for internal reporting.

Development
You can extend the organization model to support customization or special
configuration scenarios.

One of the core extensibility scenarios is extending the organization model for
specific industry vertical requirements such as retail, professional services, or
public sector. Branches, stores, schools, and school districts are basically
organization concepts. You can model them as new types of operating units. The
framework of the new organization model supports this extensibility by allowing
you to define a new type of custom operating unit.

3-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

NOTE: In Microsoft Dynamics AX 2012, existing entities such as warehouse,


site, and project are not organizations. There are two options if you want to take
advantage of the organization model framework for these entities. The first
option is to model them as cost centers or departments so that you can
incorporate them in the hierarchy and use the framework. We recommend that
you use this option. The second option is to model them as custom operating
units. In both options, you must manage data separately and keep it consistent.
Also, data security access, policies, and dimensions that are defined for
organizations that correspond to these entities will not apply to the actual
entities. A customization is required if these limitations must be addressed. This
customization is out of the scope of this course.

Demonstration: Create a Custom Operating Unit


In the following example, you will configure an operating unit called Branch. To
configure Store, do the following.

• Define a new Base Enum value for the OMOperatingUnitType that


corresponds to the new type of operating unit.
• Define a query OMStoreQuery for the new type of operating unit.
• Define a view OMStoreView based on the OMStoreQuery query.
• Optionally, define a new menu item that corresponds to this
operating unit to create new instances of this type of operating unit.

To define a new Base Enum value for the OMOperatingUnitType that


corresponds to the new type of operating unit, follow these steps.

1. In the AOT, right-click Data Dictionary > Base Enums >


OMOperatingUnitType and then click New Element.
2. In the Properties window, enter Store in the Name and Label.
3. Save the base enumeration.

To define a query for the new type of operating unit, follow these steps.

1. In the AOT, right-click Queries and then click New Query.


2. In the Properties window, type OMBranchQuery in the Name.
3. Right-click OMStoreQuery > Data Sources and then select New
Data Source.
4. In the Properties window, select OMOperatingUnit in the Table
property and then press Enter.
5. Expand the new OMOperatingUnit_1 data source and select the
Fields node.
6. In the Properties window, set the Dynamic property to Yes.
7. Right-click the OMStoreQuery > OMOperatingUnit_1 > Ranges
node and select New Range.
8. In the Properties window, set the Field to OMOperatingUnitType,
and the Value to =Store.

3-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

9. Right-click the OMStoreQuery > OMOperatingUnit_1 > Data


Sources node and select New Data Source.
10. In the Properties window, set the Table to DirPartyTable and the
FetchMode to 1:1.
11. Expand the new DirPartyTable_1 data source and select the Fields
node.
12. In the Properties window, set the Dynamic property to Yes.
13. Right-click the Relations node on the new DirPartyTable_1 data
source and select New Relation.
14. In the Properties window, set the Field to RecID and the
RelatedField to RecID.
15. Save the query.

To define a view based on the query that you defined, follow these steps.

1. In the AOT, right-click Data Dictionary > Views and then click
New View.
2. In Name, type OMStoreView.
3. In the Properties window, set the following values.
o Label = Store
o Query = OMStoreQuery
o TitleField1 = RecID
o TitleField2 = modifiedBy

4. Drag the following fields from the DataSource > Field nodes to the
OMStoreView > Fields node.
o OMOperatingUnitType
o LanguageId
o NameAlias
o Memo
o PartyNumber
o InstanceRelationType
o KnownAs
o Name
o OMOperatingUnitNumber
o OMOperatingUnitRecId

5. Drag the following fields into the Field Groups > AutoReport
node.
o RecId
o Name

6. Save the view.

3-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

To define a new menu item to create new instances of this type of operating unit,
follow these steps. This menu item will open an operating unit form only for
creating operating units of the type Store. This step is optional.

1. In the AOT, right-click Menu Items > Display and then click New
Menu Item.
2. In Name, type OMStore.
3. In Label, type Store.
4. In Object, type OMOperatingUnit.
5. In EnumTypeParameter, type OMOperatingUnitType.
6. In EnumParameter, type Store.

The integration of the organization model with other frameworks provides


visibility into this new type of operating unit. You can define new instances of
these organizations by using the Operating unit form. (You can also use a
parameterized version of the form opened by using the menu item if you
performed the optional preceding procedure.) You can use the new instances of
the custom operating unit in building new hierarchies within the hierarchy
designer without any further changes. You can define data security access for
these organizations based on the hierarchies. You can also use the policy
framework to set policies for these types of organizations.

Hierarchy Designer Extensibility


In Microsoft Dynamics AX 2012, there is limited support for extensibility of
hierarchy designer. The hierarchy designer control can be customized for four
parameters of organization nodes within the hierarchy: border color, node image,
top gradient color, and bottom gradient color.

The following sample code changes to OMHierDesignExtClass to support new


values for border, top gradient, and bottom gradient colors based on the type of
the organization.

class OMHierDesignExtClass
{
#ResAppl
#define.LegalEntityTopGradient("#FFA5CDFF")
#define.LegalEntityBottomGradient("#FF7EB8FF")
#define.LegalEntityBorderColor("#FF3F5C80")
#define.BusinessUnitTopGradient("#FF89C3E7")
#define.BusinessUnitBottomGradient("#FF4C9FD2")
#define.BusinessUnitBorderColor("#FF004b78")
#define.CostCenterTopGradient("#FFE2FFA6")
#define.CostCenterBottomGradient("#FFD6FF80")
#define.CostCenterBorderColor("#FF6B8040")
#define.DepartmentTopGradient("#FFA6ECFF")
#define.DepartmentBottomGradient("#FF80E3FF")
#define.DepartmentBorderColor("#FF407280")
#define.ValueStreamTopGradient("#FFFFCEA6")
#define.ValueStreamBottomGradient("#FFFFB980")

3-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

#define.ValueStreamBorderColor("#FF805D40")
#define.DefaultTopGradient("#FFDC143C")
#define.DefaultBottomGradient("#FFDC143C")
#define.DefaultBorderColor("#FF004b78")
FormRun m_HDForm;
OMOrganizationHierarchy m_omOH;
}

A similar customization can be done for a new type of operating unit by


customizing this class to add a new border color, top gradient color, and bottom
gradient color. Without the customization, the hierarchy designer uses default
colors for a new type of operating unit.

You can add a new custom purpose by customizing the


OMHierarchyPurposeTableClass class and HierarchyPurpose base Enum. The
customization must extend to the application scenario where this custom purpose
will be used. For more information about an example of doing this refer to the
"Policy Framework" topic in this course.

A more complex customization of the OMHierarchyPurposeTableClass class is


required if you want to force the design of balanced hierarchies. In a hierarchy,
all nodes at a fixed depth from the root node define a level. In a balanced
hierarchy, specific operating unit types are allowed at each level.

You can set up a new end-to-end scenario or customize an existing end-to-end


scenario. The high-level steps are as follows.

1. Define or change the data model.


o Create a new transaction table or make a Per company
transaction table by changing the metadata property from
SaveDataPerCompany = yes to SaveDataPerCompany = No.
o Include relevant organizations as Foreign keys (FK) on the table.
It is sufficient to carry an operating unit because the relationship
with the legal entity is established through organization
hierarchies.
o If the transaction table carries redundant data of the legal entity
field, set up business logic constraints between legal entities and
operating units to maintain data consistency.

2. Build a new form (for example, a list page) for the transaction
scenarios, or change the existing user experience to view or maintain
transactions. The custom filters can help view or manage data across
organizations.
3. Apply default organizations on the transaction table in financial
dimensions by including them in account structures.
4. Create XDS policies for data security based on access to the
organizations of the user.
5. Use the policy framework to set up specific policies that are applied
while you are creating a new transaction in the application scenario.

3-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Special considerations can apply for intercompany trade and intercompany


accounting if the transactions are between two legal entities of the same business
implemented in one instance of Microsoft Dynamics AX 2012.

You must make special considerations if master data entities are referenced in the
application scenario because they have a relationship in the data model with the
transaction table.

Case Management Framework


Typically, case management is a reference to customer service. However, many
business operations can benefit from case management, as described here.

• Customer service: Customer questions, issues, complaints, and


suggestions have to be tracked.
• Purchasing and receiving: Your organization is a customer to your
suppliers, and while you track your customer issues, you should also
track issues that you have with your suppliers, such as incorrect or
damaged items and late deliveries. Employees working in purchasing
and receiving need a place to record issues and complaints about
vendors and the products they purchase. This is especially true
because this can cause your organization strife, delays in production,
and reduce customer satisfaction.
• Human resources and payroll: Employees are customers of human
resources (HR) and payroll departments. These departments have to
record any incidents and grievances reported by their workers. Even
more than customer service, HR has to follow strict procedures for
resolving these issues—not only for legal reasons, but because many
unions require documentation of any complaints.
• Auditing: Typically, the auditor is responsible for the manual job of
reviewing expenses and contracts, and identifying compliance
violations. Even when the auditor finds violations, many times there
is no form or table record these issues for a historical reference.
• Collections: Collection agents have to keep a record of the
communications and interactions with the people and businesses they
are working with. Microsoft Dynamics AX 2012 case management
fulfills the needs of these business operations.

Microsoft Dynamics AX 2012 case management fulfills the needs of these


business operations.

While the goal is to resolve issues as swiftly as possible, not all issues and
questions can be resolved quickly and easily. They frequently require more than
one interaction in addition to collaboration and research before they can be
closed. Organizations need the ability to record and report on these issues.

3-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Case management provides the tools to handle issues more quickly and improve
customer, employee, and vendor relationships, and includes the following.

• Track and manage defects or improvement requests with integrated


action processes.
• Create, manage, and resolve customer, vendor, and employee cases
more easily by automatically tracking all communication activities
that go into finding satisfactory resolutions.
• Let you log dependent cases for complex issues that require more
than one resolution path.
• Associate many records in the system by tying together several
components. A case opened for a customer can also be associated
with a sales order and a specific item. Linking all the necessary
records provides the case worker with the ability to view everything
related to a case.
• Use service level agreements because responding in a timely,
effective manner is extremely important to the success of your
organization. To meet and exceed expectations, you have to track
and measure how quickly you react to issues and escalate to bigger
levels of support and management for cases that are not resolved in a
timely manner.

Case Process
Organizations need all cases to be handled consistently according to company
policies and procedures. To make sure that this occurs, case processes can be
defined to guide your workers through a simple checklist or a more elaborate
step-by-step set of stages and actions. This provides consistency in resolving
cases, and helps new case workers to become efficient and perform at a high
level in a short period of time. After a case process is defined, it can be
associated with a specific case category so that your case workers will know
what has to be completed for each situation.

In addition to case processes, workflow can be defined so that cases can be


assigned to queues, which can be picked up by any case worker in a specific area,
such as auditing.

Knowledge Articles
To resolve cases efficiently, case workers need easy access to processes and
procedures, answers to frequently asked questions, how-to documentation, and
other organizational knowledge collateral. The ability to create and store
knowledge articles provides case workers with the information that they must
have to resolve cases quickly. To help ensure even faster resolution, you can
associate specific knowledge articles with a case category, which will default the
knowledge articles to any case by using that category. This functionality reduces
the time that you have to have for a case worker to search for documentation.

3-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Scenario: Extending the Case Management Framework


Your business might require you to extend the case management framework to
other data entities. This might include the ability to associate a case to another
record, or the ability to create new cases for other types of records.

Scenario:

Vince, the Operations Manager, has noticed an increase in the number of calls
and the issues when vehicles are rented and returned. He wants a way to record
these issues when they are reported so that they can be followed up on. He has
decided to start by using case management to help with this process.

Case management already exists for customers, so he will be able to track


customer calls and requests. However, there is currently no way to create a case
for a specific vehicle or rental. Vince wants to create cases for specific vehicles
to track the maintenance issues, history, and damage to the vehicles.
Additionally, he wants to be able to create cases for specific rentals to help
control the return process for vehicles. He wants the inspectors to record
information that is collected during the return such as the issues the customer had
with the vehicle and the damage that is found on the vehicle when it is returned.

3-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Case Management Data Model


The following figure shows the data model for case management.

FIGURE 3.6 CASE MANAGEMENT DATA MODEL

The CaseDetailsBase is the primary table for storing all cases regardless of where
the case is created from or which records the case is related to. Each case is
assigned a case category. Case categories are stored in the
CaseCategoryHierarchyDetail table. Each case can have logs or notes related to
the case. Each log entry related to a case is stored in the CaseLog table. When a
case is related to another case, this reference is stored in the CaseDependancy
table.

The CaseAssociation table is used to store a reference to each record that a case
is related to. The CaseAssociation table is then related to the primary table for
each type of association based on the CaseEntityType and RefRecId. For
example, when a case is related to a sales order, the CaseEntityType field would
store the enum value for the sales order table, and the RefRecId field would store
the RecID from the sales order that the case is related to.

3-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When a case is created from the Enterprise Portal the user details are stored in the
CaseWebDetails table.

When a Knowledge article is related to a case, it is populated in the


TmpSmmKACaseRelation temporary table. Records can be inserted into this
temporary table automatically when a case is created based on the set up of the
knowledge article or they can be manually added. Each
TmpSmmKACaseRelation record is related to a smmEncyclopediaItems table
record which is the primary table for knowledge articles. The actual document,
URL, or note that is related to a knowledge article is stored in the DocuRef table.
This table is the primary table that is used for document handling throughout the
system.

Case Associations
Out of the box, cases can be related to the following data entities and tables.

Data Entity Table


Lead smmLeadTable
Opportunity smmOpportunityTable
Customer CustTable
Vendor VendTable
Prospect smmBusRelTable
Project ProjTable
Sales order SalesTable
Purchase order PurchTable
Worker HcmWorker
Service order SMAServiceOrderTable
Item InventTable
Customer transaction CustTrans
Expense report line TrvExpLine
Expense report TrvExpTable
Vendor invoice VendInvoiceJour
Vendor invoice line VendInvoiceTrans
Purchase order line PurchLine

Each case can have multiple associations and multiple associations of the same
type. For example, a case related to a specific customer, could also be related to
customer transactions.

3-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Demonstration: Create a Case Association Entity Type


To create a new case association entity type, follow these steps.

1. Add a new element to the CaseEntityType base enum for the table
that you want to relate to. In this example, Vehicles for Fleet
management will be used.
2. Add a case statement to the smmAssociationLink.performLookup
method for the new entity. Use the following code sample to guide
you.

case CaseEntityType::Vehicle: oSysTableLookup =


SysTableLookup::newParameters(tablenum(FMVehicle), callerControl);
oqbds = oQuery.addDataSource(tablenum(FMVehicle));

oSysTableLookup.addLookupfield(fieldnum(FMVehicle, VehicleID));
oSysTableLookup.addLookupfield(fieldnum(FMVehicle, VehicleModel));
oSysTableLookup.addLookupfield(fieldnum(FMVehicle, Description));
oSysTableLookup.parmQuery(oQuery);
oSysTableLookup.performFormLookup();

break;

3. Add a case statement to the smmAssociationLink.performJumpRef


method to open the main form for the new entity. Use the following
code sample to guide you.

case CaseEntityType::Vehicle:
menuItemName = menuitemdisplaystr(FMVehicle);
break;

4. Add a case statement to the


smmAssociationLink.entityType2TableId method to specify the
table number for the new entity. Use the following code sample to
guide you.

case CaseEntityType::Vehicle:
tableId = tablenum(FMVehilce);
break;

5. Add a case statement to the smmAssociationLink.entityType2FieldId


method to specify the field number for the primary field on the
entity. Use the following code sample to guide you.

case CaseEntityType::Vehicle:
fieldId = fieldnum(FMVehicle, VehicleId);
break;

3-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. Add a case statement to the


smmAssociationLink.entityType2FieldName method to specify the
field number for the primary field on the entity. Use the following
code sample to guide you.

// Fleet management vehicle


case tablenum(FMVehicle):
returnValue = CaseEntityType::Vehicle;
break;

7. Modify the CaseDetail form to add a "more information" group to


the Case Association FastTab.
o Add a data source to the form for the entity you want. In this
example add the FMVehicles table. Make sure that you relate the
table to the CaseAssociation data source on the form.
o Create a new Group in the Group:Group_MoreInformation area
of the TabPage:AssocitationsTabPage. Make sure that you auto
declare the new group. Call the new tab page
CaseMoreInformation_FMVehicles.
o Add fields to the tab page from the data source. You can also
choose to use a field group. For example, select the DetailsGroup
in the DataGroup property of the new group.
o In the showMoreInformation method on the form, declare a new
boolean for your entity type. Use the following code sample to
guide you.

boolean showFMVehicle = (caseAssociation.EntityType ==


CaseEntityType::Vehicle);

o In the showMoreInformation method on the form, add an OR


statement to the boolean showMoreInformationGroup variable.
Use the following code sample to guide you.

3-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

boolean showMoreInformationGroup =

( showTrvExpTable || showTrvExpTrans ||
showsmmLeadTable || showsmmOpportunityTable ||
showInventTable || showServiceOrderTable ||
showHcmWorker || showPurchLine ||
showPurchTable || showSalesTable ||
showProjTable || showsmmBusRelTable ||
showVendTable || showCustTable ||
showCustTrans || showVendInvoiceJour ||
showVendInvoiceTrans || showFMVehicle);

o In the showMoreInformation method on the form, add an IF


statement to make the new group visible when the case
association record is for a vehicle. Use the following code
sample to guide you.

if (caseMoreInformation_FMVehicles.visible() != showFMVehicle)
{
caseMoreInformation_FMVehicles.visible(showFMVehicle);
FMVehicle_DS.refresh();
}

Demonstration: Use the New Case Association Entity


Type
To test the new case association type, follow these steps.

1. Open Home > Area Page > Common > Cases > All cases.
2. Click Case in the New group of the Action Pane.
3. Select General > GEN1 in the Case category field.
4. Click Create.
5. Click No on the Create activity dialog box.
6. On the Associations FastTab of the Case form, click Add.
7. In the Entity type field, select Vehicle.
8. In the ID field, select a vehicle.
9. Save the record.
10. Click the Details button.
11. The Vehicles form should open to the vehicle you selected in step 7.
Close all the forms.

3-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Demonstration: Extend Cases to a Form


Once you have created a new case association entity, the cases can be created
from any of the Cases list pages in the Home module. To add cases directly from
a form, you must add a menu item button to the form that calls the
CaseDetailFormCreate class. This class is designed to call the
CaseDetailForm::writeCreateCase() method which creates a case and then calls
the smmAssociationLink::createCaseAssociation(). This method creates a case
association for the record that you have selected. To add the cases buttons to a
new form, follow these steps.

1. Create a new Display menu item that calls the CaseDetailFormCreate


class. View the CaseDetailNewSales for an example of this.
2. On the form where you want to add the buttons do the following.
a. If a General tab does not exist on the Action Pane, add one.
b. Add the menu item that you created in step 1 to the form.
c. Add the CaseDetails menu item to the form.

TIP: You can copy and paste the buttons from the SalesTable form onto the
FMVehicle form.

3-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Make sure that you specify an image resource, and set the data source property
on both menu items. The Vehicle form should resemble the following figure
when you are finished.

FIGURE 3.7 VEHICLE FORM

To test that the new buttons work correctly, follow these steps.

1. Open Fleet management > Common > Vehicles > All vehicles.
2. Select a vehicle.
3. Click the General tab on the Action Pane.
4. Click Create case.
5. Select a Case category.
6. Click Create.
7. Click No on the Create activity dialog box.
8. On the Associations FastTab, verify that an association is created for
the vehicle that you created the case for.
9. Close the forms.

3-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 3.2 - Extend Case Management


This lab demonstrates how to extend case management to add a new case
association entity type for rentals.

This lab is designed for self-study. Completing this lab takes approximately 20
minutes.

Scenario

Vince, the Operations Manager, has noticed an increase in the number of calls
and the issues when vehicles are rented and returned. He wants a way to record
these issues when they are reported so that they can be followed up on. He has
decided to start by using case management to help with this process.

He wants to create cases for specific rentals to help control the return process for
vehicles. The inspectors will then record information that is collected during the
return such as the issues the customer had with the vehicle and the damage that is
found on the vehicle when it is returned.

So, Simon, the Business Systems Developer, must extend the case management
framework to allow cases to be associated to rentals.

Challenge Yourself!
Use the information that is provided to add rentals as a case association entity
type. Make sure that you add buttons on the Rental form to create the case and
automatically add an association.

Need a Little Help?

1. Modify the CaseEntityType base enum.


2. Modify the following methods in the smmAssociationLink class.
o performLookup
o performJumpRef
o entityType2TableId
o entityType2FieldId
o entityType2FieldName

3. Modify the CaseDetail form to add a "more information" group to


the Case Association FastTab.
4. Test the new case association type by adding a case in the All cases
list page in the Home module.
5. Add the cases buttons to the Rentals form.
6. Test the cases buttons on the Rentals form.

3-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Step by Step
To create a new case association entity type, follow these steps.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_03_02_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

1. Add a new element to the CaseEntityType base enum for Rentals.


2. Add a case statement to the smmAssociationLink.performLookup
method for the new entity. Use the following code sample to guide
you.

case CaseEntityType::Vehicle: oSysTableLookup =


SysTableLookup::newParameters(tablenum(FMRental), callerControl);
oqbds = oQuery.addDataSource(tablenum(FMRental));

oSysTableLookup.addLookupfield(fieldnum(FMRental, RentalID));
oSysTableLookup.addLookupfield(fieldnum(FMRental, Customer));
oSysTableLookup.addLookupfield(fieldnum(FMRental, Vehicle));
oSysTableLookup.parmQuery(oQuery);
oSysTableLookup.performFormLookup();

break;

3. Add a case statement to the smmAssociationLink.performJumpRef


method to open the main form for the new entity. Use the following
code sample to guide you.

case CaseEntityType::Rental:
menuItemName = menuitemdisplaystr(FMRental);
break;

4. Add a case statement to the


smmAssociationLink.entityType2TableId method to specify the
table number for the new entity. Use the following code sample to
guide you.

case CaseEntityType::Rental:
tableId = tablenum(FMRental);
break;

5. .Add a case statement to the


smmAssociationLink.entityType2FieldId method to specify the field
number for the primary field on the entity. Use the following code
sample to guide you.

3-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

case CaseEntityType::Rental:
fieldId = fieldnum(FMRental, RentalId);
break;

6. Add a case statement to the


smmAssociationLink.entityType2FieldName method to specify the
field number for the primary field on the entity. Use the following
code sample to guide you.

// Fleet management vehicle


case tablenum(FMRental):
returnValue = CaseEntityType::Rental;
break;

7. Modify the CaseDetail form to add a "more information" group to


the Case Association FastTab.
a. Add a data source to the form for the entity you want. In this
example add the FMRental table. Make sure that you relate the
table to the CaseAssociation data source on the form.
b. Create a new Group in the Group:Group_MoreInformation area
of the TabPage:AssocitationsTabPage. Make sure that you auto
declare the new group. Call the new tab page
CaseMoreInformation_FMRental.
c. Add fields to the tab page from the data source. You can also
choose to use a field group. For example, select the DetailsGroup
in the DataGroup property of the new group.
d. In the showMoreInformation method on the form, declare a new
boolean for your entity type. Use the following code sample to
guide you.

boolean showFMRental = (caseAssociation.EntityType ==


CaseEntityType::Rental);

e. In the showMoreInformation method on the form, add an "or"


statement to the boolean showMoreInformationGroup variable.
Use the following code sample to guide you.

boolean showMoreInformationGroup =

( showTrvExpTable || showTrvExpTrans ||
showsmmLeadTable || showsmmOpportunityTable ||
showInventTable || showServiceOrderTable ||
showHcmWorker || showPurchLine ||
showPurchTable || showSalesTable ||
showProjTable || showsmmBusRelTable ||
showVendTable || showCustTable ||

3-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

showCustTrans || showVendInvoiceJour ||
showVendInvoiceTrans || showFMRental);

f. In the showMoreInformation method on the form, add an IF


statement to make the new group visible when the case
association record is for a vehicle. Use the following code
sample to guide you.

if (caseMoreInformation_FMRental.visible() != showFMRental)
{
caseMoreInformation_FMRental.visible(showFMRental);
FMRental_DS.refresh();
}

To test the new case association type, follow these steps.

1. Open Home > Area Page > Common > Cases > All cases.
2. Click Case in the New group of the Action Pane.
3. Select General > GEN1 in the Case category field.
4. Click Create.
5. Click No on the Create activity dialog box.
6. On the Associations FastTab of the Case form, click Add.
7. In the Entity type field, select Rental.
8. In the ID field, select a rental. If there are no rentals, create one in
the Rentals form.
9. Save the record.
10. Click the Details button.
11. The Rental form should open to the rental you selected in step 7.
Close all the forms.

To add buttons to the Rental form, follow these steps.

1. Create a new Display menu item that calls the CaseDetailFormCreate


class. View the CaseDetailNewSales for an example of this.
2. On the FMRental form do the following.
o If a General tab does not exist on the Action Pane, add one.
o Add the menu item that you created in step 1 to the form.
o Add the CaseDetails menu item to the form.

3-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

TIP: You can copy and paste the buttons from the SalesTable form onto the
FMVehicle form. Make sure that you specify an image resource, and set the data
source property on both menu items.

TIP: You can import the AX2012_ENUS_DEVIV_03_02_LAB_SOL.xpo file to


verify and compare your solution.

3-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Policy Framework
Microsoft Dynamics AX 2012 introduces a policy framework that can be used to
define policy rules in modules to help guide the flow of business. The framework
provides a common pattern and rich feature set that users can take advantage of
to enforce simple rules or to evaluate and act on several different rules in a
complex organizational hierarchy. The actual rules used by businesses, and the
actions that these rules allow, prevent, or alter are outside the scope of the
framework. However, this white paper does provide examples of the policy types
and rule types that that are included with Microsoft Dynamics AX 2012.

NOTE: The policy framework is only used for defining and enforcing business
rules. It is not related to the framework that creates extensible data security
policies also being introduced in Microsoft Dynamics AX 2012.

There are three perspectives from which the policy framework can be viewed and
used, depending on the role of the user.

• A developer introduces the policy types and rule types to be


evaluated.
• A software developer writes the logic that retrieves date-effective
rules for a given user. It does this to enforce these rules as the
module requires (for example, in form logic to allow or prevent
certain actions).

NOTE: One person often performs the role of developer and software developer.

• An administrator, in a manager role, defines specific rule data that


will be enforced.

Developers and administrators can use the policy framework to improve their
business processes by enforcing rules for Microsoft Dynamics AX 2012 users.
Examples of rules include the following.

• Expense reports submitted by employees for items above a certain


currency amount are disallowed or result in an appropriate warning.
• Employees in one organization can view a specific procurement
catalog while other employees (for example, those in a different
country or region with different suppliers) are required to view a
different catalog.
• Employees with a particular title can approve lines only up to a
certain amount of currency.
• Documents must be validated against certain criteria, and violations
of those criteria must be flagged.

3-49
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

For each of these cases, a developer specifies the type of data that is stored in the
policy and how various forms and classes behave with that data. An
administrator then defines and manages who the policies will affect (and when)
and specifies the exact data values for each rule.

Framework Components
The policy framework consists of three main components that provide the
functionality that corresponds to the developer and administrator roles described
earlier.

• A unified, extensible schema that gives the developer a basic


platform on which to build a policy solution.
• An Application Programming Interface (API) that provides
developer with the way to retrieve policy rules. Policy rules take the
developer directly to the data needed to execute the appropriate
business logic.
• A common entry point for both the policy administrator and the
developer, who can use it to manage policies. Little customization is
required beyond entry of their business data.

These components provide the flexibility that developers and administrators must
have to achieve their objectives without problems. They also give the user the
same appearance and behavior as the rest of the policy user interface (UI) in
Microsoft Dynamics AX 2012.

Policy Types
A policy type is a collection of all the rule types that apply to a given module or
feature area.

A user in a manager role can be granted permission to define policies of a given


type through a menu item that opens a list page. The list page displays all the
policies of a particular policy type.

Microsoft Dynamics AX 2012 includes six policy types. These types are
specified with the following SysPolicyTypeEnum enumeration values.

• ApprovalPolicy
• AuditPolicy
• PurchasingPolicy
• TrvExpensePolicy
• TrvRequisitionPolicy
• VendInvoicesPolicy

3-50
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Each policy type is associated with a “hierarchy purpose” (specified in the


HierarchyPurpose field in the SysPolicyType table) that defines the
organizational hierarchies that can be assigned to these policies. For example, a
developer can only assign organizations in the hierarchies that are designated for
“Procurement internal control” to PurchasingPolicy policies. The same
organizational hierarchy can be assigned to multiple hierarchy purposes.

Rule Types
Rules are at the core of any policy. The necessary data that defines how policies
will be enacted is located in rules. After a developer defines policy types and rule
types and he or she creates a policy, the policy administrator can add rules to that
policy. For example, suppose that an administrator adds a catalog rule to a
purchasing policy. The catalog rule is configured to specify the “Adventure
Catalog” for internal procurement. After the purchasing policy is associated with
a particular organization, all employees of that organization will see the
Adventure Catalog when they browse the internal procurement site.

Rules are date-effective, which gives you a set of powerful options for
manipulating policy events over time. You can define rules that take effect in the
present and expire sometime in the future, or that never expire. You can also set
up rules that will take effect at some specified point in the future. By defining
date-effective rules, you prevent multiple rules from being active at any given
time, when they might provide conflicting data.

After a rule has gone into effect, it can only expire or be discontinued. It can
never be removed from the policy. This constraint provides enhanced auditing
capability and historical policy retention. The policy framework can be queried
for the rules that were in effect at a specific time, if it is necessary.

As mentioned earlier, each rule is associated with a corresponding form. The


developer implements the form, which displays and stores data in the data model.
The administrator can then interact with this form to define and update the rule as
needed.

Organization Assignment
Before a policy can affect anyone, it must be associated with an organization.
The administrator configures the association with the organization on the
SysPolicy form after a policy is created. In the business logic, the developer
queries the API for rules that are in effect for a specific organization.

All hierarchies with a specific hierarchy purpose can be sources from which to
select organizations. An additional source from which to select organizations is
the “flat list” of legal entities in the CompanyInfo table, which are designated in
the policy framework as “Companies.” (An example would be a legal entity with
a DataAreaId of “DAT.”) Although not a true hierarchy, this can be thought of as
a default hierarchy type that is always available.

3-51
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

You can assign only organizations from a single hierarchy type to a given policy
(this is the typical scenario). If organizations from multiple hierarchy types
require the same policy, you must create multiple policies. For example, if you
have to create an AuditPolicy policy for employees of organizations in a
procurement hierarchy and for employees of companies in the “flat list” in
Microsoft Dynamics AX 2012, you will have to create a separate policy for each
group.

Policies Data Model


Before you start to develop policies, you should understand the underlying data
model. There are only three core tables with which you have to be familiar.

• The SysPolicyRule table


• The SysPolicyType table
• The SysPolicyRuleType table

SysPolicyRule table

The SysPolicyRule table is the main table with which you will interact. To
demonstrate the design options that this table allows, you start with the output
and work backward. When you query the policy API (by using the
SysPolicies::getPolicyRuleIds method) for a list of rules for a given policy type,
rule type, and organization, the API returns an array of RecIds to the
SysPolicyRule table, which holds a list of specific rule instances. With this
strategy you can follow one of two general patterns shown for storing and
accessing your rule data. Select the pattern that best suits your requirements.

• One set of data for each rule

This is the more common pattern. There is just one set of data for each
rule, which is stored in one row in a table. To implement this pattern,
create a table that is a subtype of the SysPolicyRule table and add all the
fields required for your feature. A RecId that you receive from the policy
API will now directly correspond to a date-effective row in your table
(which is managed by the policy framework). You can directly query
your table without having to know that it extends the SysPolicyRule
table. You can view examples of this pattern in the
CatCatalogPolicyRule and TrvPolicyRule tables. For more information,
view the ER diagram.

3-52
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

• Many entities for each rule

Use this pattern when you have to store several rows of information for
each rule (meaning, the rules are displayed as a grid on the rule form). In
this case, create a table with the fields that you must have that is not a
subtype of the SysPolicyRule table. Instead, add a foreign key to the
SysPolicyRule table to establish a many-to-one relationship. By doing
this, you can reference many rows of data in your table with one
SysPolicyRule RecId. You can view examples of this pattern in the
ProcCategoryPolicyParameter and ProcCategoryAccessPolicyParameter
tables.

3-53
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

SysPolicyType and SysPolicyRuleType tables

The SysPolicyType and SysPolicyRuleType tables store the core type


information that defines your policy and its rules. This information is static;
therefore, after it is configured, the rows in these tables should not have to
change, and no UI is provided for doing this.

FIGURE 3.8 POLICIES DATA MODEL

3-54
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

NOTE: This figure shows the key relationships among all the tables in the data
model. None of the related tables will be directly queried. However, the diagram
provides a good basis for understanding the entity relations involved in the
policy framework.

Procedure: Create a Policy Type


To create a new policy type, follow these steps.

1. Open the Development Workspace.


2. In the AOT, right-click Data Dictionary > Base Enums >
SysPolicyTypeEnum and then select New Element.
3. Enter a name and label for the element such as
FleetManagemetPolicy or SalesPolicy.
4. Save the base enum.
5. Create a row for the new policy type in the SysPolicyType table.
You can add a row to the SysPolicyType table in one of two ways-
update the SysPolicySetup class or write a simple job to insert the
row.

Update the SysPolicySetup Class

To update the SysPolicySetup class, follow these steps.

1. 1. Open the Development Workspace. 2.


2. In the AOT, right-click Classes > SysPolicySetup and then click
Edit.
3. In the Code Editor change the classDeclaration method by
optionally adding a SysSetupConfigurationKeyAttribute for the
configuration key that enables the functionality for your policy.
4. Create a new method for your policy type called
load<PolicyTypeName>PolicyData. In this example the method
would be called loadFleetManagementPolicyData.
a. Add a line of code to the method to add the Fleet management
policy type.

SysPolicyType policyType =
SysPolicySetup::addPolicyType(SysPolicyTypeEnum::FleetMan
agementPolicy, HierarchyPurpose::PurchaseControl);

NOTE: This example uses the PurchaseControl hierarchy purpose. If you have
created a new hierarchy purpose, make sure that you select that purpose.

3-55
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

b. Later you will have to add a line of code for each rule type
related to the policy type. The format is as follows.

SysPolicySetup::addRuleType(policyType,
SysPolicyRuleTypeEnum::<PolicyRuleName>,
formstr(<PolicyRuleFormName>));

Where <PolicyRuleName> is the name of the policy rule


enumeration value and the <PolicyRuleFormName> is the name
of the form that you created for the rule type.

NOTE: This step cannot be completed until after you have created rule types and
forms for each rule type.

5. Modify the loadData method to call the method that you created in
step 4. Optionally you can add an IF statement to only call the
method if the configuration key is enabled.

Because this class is an implementation of the SysSetup class, its loadData


method (which fills the policy and rule type tables) is called on installation or
upgrade of Microsoft Dynamics AX 2012, on activation of the configuration
keys, and on full synchronizations of all the tables. You can also write a job to
manually invoke the SysPolicySetup.loadData method.

The only two required fields in the SysPolicyType table are PolicyType and
HierarchyPurpose. The PolicyType field must match the value that you add to
the SysPolicyTypeEnum enumeration. The remaining fields are optional settings.

Procedure: Add an Entry Point for the Policy


To create a basic working path for your new policy type, you have to add a menu
item that points to the SysPolicyListPage form. You must set three properties on
this menu item to filter to the new policy type. To create a new menu item,
follow these steps.

1. Open the Development Workspace.


2. In the AOT, right-click Menu Items > Display and select New
Menu Item.
3. In the Properties window, set the following values.
o EnumTypeParameter = SysPolicyTypeEnum.
o EnumParameter = The name of the new policy type (for
example, TrvRequisitionPolicy) that has been added to the
SysPolicyTypeEnum enumeration.
o Parameters = An integer that represents the enumeration value of
the new policy type (for example, 3).

4. Save the menu item.

3-56
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Adding a new menu item also requires you to add the menu item to a menu and
to a privilege. Knowledge of how to do this is assumed and is not discussed in
this course.

Procedure: Create a Rule Type


The process for creating new rule types resembles the process for creating a new
policy type. You have to perform the same two basic steps—add rows in the
table, and add new enumerations (if the rule types are known).

In this example, it is assumed that your rule types are static and known at design
time. If your requirements require that the rule types must be dynamic (meaning
that is defined by the user) and added at run time, refer to the
SysPolicySourceDocumentRuleType form in the AOT for an example of this
pattern.

To add rule types to the SysPolicyRuleType table, edit the SysPolicySetup class
by completing step 4.b. in the “Create a Policy Type” procedure for each rule
type. There are several instances of this procedure in the class code that you can
follow as examples.

NOTE: This step cannot be completed until you have created a form for each
rule type.

The required fields are as follows:

• Name: Should match the name of the enumeration that is added.


• PolicyType: A foreign key to the SysPolicyType table.
• RuleFormName: The AOT form name of the form that will be
launched when configuring a rule of this type. For more information,
refer to the “Creating rule forms” section later in this training
material.
• IncludeParentRules: A flag that enables the IsInherited flag on rule
instances. This flag is usually set to “Yes” so that rules can be set at
a parent organization level to affect all organizations below it in the
hierarchy.
• IsPrecedenceSupported: A flag that tells the framework whether
the hierarchy precedence for a policy type can be overridden at a
rule-type level.

3-57
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Create Rule Forms


To allow an administrator to fill your rule table with data, you must create a form
that displays and saves that data. The name of the form or menu item pointing to
that form is stored in the RuleFormName field of the SysPolicyRuleType table.
The only data that you are required to show on this form are the effective date
(which defaults to the current date and time) and the expiration date (which
defaults to “Never”). These dates are stored in the ValidFrom and ValidTo
fields in the SysPolicyRule table. The basic flow of this form is that, when it is
opened, it shows either the values of the rule that is currently open or the default
values to use when creating a new rule. When the user closes the form, the
appropriate records should be saved to the SysPolicyRule table and to any other
tables that are used to store your rule data.

Several of these forms are included with Microsoft Dynamics AX 2012. Because
forms are feature-specific, more precise guidance cannot be provided about how
to design them. We recommend that you view the forms listed in the
RuleFormName column of the SysPolicyRuleType table for examples. The
following figure shows the CatCatalogPolicyRule form. It is the simplest
example because it contains just one piece of data for each rule.

FIGURE 3.9 CATALOG POLICY RULE FORM

Procedure: Retrieve Date-Effective Rules


When rules are defined and are in effect in the system, your application logic can
query for these rules and take appropriate action. The
SysPolicies::getPolicyRuleIds method is provided to make this process easier. At
a minimum, this method must be passed the policy type and the rule type that you
set up earlier, and the organization that you want to check for rules. The method
returns references to the SysPolicyRule table for the rules that are active in the
specified organization. From there, querying for the needed values in the table
that you added (which can be either a subtype of, or contain a foreign key to, the
SysPolicyRule table) will depend on your business logic. Refer to the XML
documentation for a complete, up-to-date description of the getPolicyRuleIds
method.

3-58
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

After the developer has finished setting up the policies, a policy administrator
can configure policies as required by their business needs.

Summary
The Application Foundation Features chapter reviewed several features that are
used throughout the system.

The global address book is a central repository for addresses and contact
information. You can extend the global address book framework to create new
party types. You can also use the extensible data security policy framework with
the global address book framework to help secure address information across
legal entities, or teams, or both.

Developers and administrators can use security policies to block access to subsets
of data rows in tables. A policy resembles a where clause in an SQL select
statement. A security permission increases the access a user has to data, but a
security policy decreases access to data.

You can use financial dimensions to create "attributes" that you can use as
account segments for a shared chart of accounts. There are two basic types of
financial dimensions.

The organization model represents internal control, data security access, and
performance reporting structures designed to divide responsibility for human and
operations resources and work processes. The organization model in Microsoft
Dynamics AX 2012 introduces two new concepts—legal entity and operating
unit. You can extend the organization model framework to create new types of
operating units or new purposes for a hierarchy.

Case management provides the tools to handle issues more quickly and improve
customer, employee, and vendor relationships. You can extend the case
management framework to work with any data entity.

Microsoft Dynamics AX 2012 introduces a policy framework that is used to


define policy rules in modules to help guide the flow of business. The framework
provides a common pattern and rich feature set that users can take advantage of
to enforce simple rules or to evaluate and act on several different rules in a
complex organizational hierarchy. You can extend the policy framework to
create new policy types or new policy rule types.

3-59
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Which class is used to implement a single address on a form?


( ) DirUtiltity
( ) DirPartyLookup
( ) LogisticsEntityPostalAddressFormHandler
( ) LogisticsMultiEntityPostalAddressFormHandler

2. Which of the following are valid types of operating units that are available
out of the box? (Select all that apply)
( ) Department
( ) Cost Center
( ) Legal Entity
( ) Business Unit

3. Fill in the blanks with the name of the table that best describes the content of
the table to test your knowledge of this section.

Stores a reference to each record that a case is related to. _____

Stores the log entries related to each case. _____

The primary table for storing all cases. _____

Stores the parent child relationship between cases when a case is related to
another case. _____

4. Put the following steps in order:

Step:

_____: Review the entity to add a policy to.

_____: Add table constraints.

_____: Test the security policy.

_____: Create a new security policy.

_____: Create a new query.

_____: Set the context type and role.

3-60
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

5. Which of the following classes are used to add financial dimension controls
to a form? (Select all that apply)
( ) FinancialDimensionAccountController
( ) FinancialDimensionDefaultAccountController
( ) LedgerDimensionAccountController
( ) LedgerDimensionDefaultAccountController

6. Categorize the following items:

_____ 1. A person or organization. a. Address book


_____ 2. A group of parties. b. Non-party
_____ 3. Entities that refer to customers, vendors, entities
competitors, workers, applicants, and so on. c. Location
_____ 4. Entities that refer to inventory, bank d. Party
groups, bank accounts, and so on. e. Party roles
_____ 5. Refers to either a postal address or an
electronic address such as email, telephone or fax.

7. List the four basic steps for creating a new operating unit type.

8. Describe what "trimming" is.

3-61
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

3-62
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 3: Application Foundation Features

Solutions
Test Your Knowledge
1. Which class is used to implement a single address on a form?
( ) DirUtiltity
( ) DirPartyLookup
(•) LogisticsEntityPostalAddressFormHandler
( ) LogisticsMultiEntityPostalAddressFormHandler

2. Which of the following are valid types of operating units that are available
out of the box? (Select all that apply)
(√) Department
(√) Cost Center
( ) Legal Entity
(√) Business Unit

3. Fill in the blanks with the name of the table that best describes the content of
the table to test your knowledge of this section.

Stores a reference to each record that a case is related to. CaseAssociation

Stores the log entries related to each case. CaseLog

The primary table for storing all cases. CaseDetailsBase

Stores the parent child relationship between cases when a case is related to
another case. CaseDependancy

4. Put the following steps in order:

Step:

1 : Review the entity to add a policy to.

4 : Add table constraints.

6 : Test the security policy.

3 : Create a new security policy.

2 : Create a new query.

5 : Set the context type and role.

3-63
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Which of the following classes are used to add financial dimension controls
to a form? (Select all that apply)
( ) FinancialDimensionAccountController
( ) FinancialDimensionDefaultAccountController
(√) LedgerDimensionAccountController
(√) LedgerDimensionDefaultAccountController

6. Categorize the following items:

d 1. A person or organization. a. Address book


a 2. A group of parties. b. Non-party
e 3. Entities that refer to customers, vendors, entities
competitors, workers, applicants, and so on. c. Location
b 4. Entities that refer to inventory, bank groups, d. Party
bank accounts, and so on. e. Party roles
c 5. Refers to either a postal address or an
electronic address such as email, telephone or fax.

7. List the four basic steps for creating a new operating unit type.

MODEL ANSWER:

Define a new Base Enum value for the OMOperatingUnitType that


corresponds to the new type of operating unit.
Define a query OMStoreQuery for the new type of operating unit.
Define a view OMStoreView based on the OMStoreQuery query.
Optionally, define a new menu item that corresponds to this operating unit to
create new instances of this type of operating unit.

8. Describe what "trimming" is.

MODEL ANSWER:

The security configuration of each field is assessed for the current user. This
security behavior is called field trimming because the restricted fields are
trimmed out of the results before the results are sent from the AOS to the
client.

3-64
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

CHAPTER 4: USE AND DESIGN OF THE LEDGER


MODULE
Objectives
The objectives are:

• Describe currencies, exchange rates, fiscal calendars, and periods.


• Describe the components that comprise the chart of accounts.
• Review the steps for adding financial dimension controls to a form.
• Create a new system-defined dimension.
• Describe how journals and transactions are used to update the
general ledger.
• Describe how the Budgeting module is used.
• Review the data model and key classes used for budgeting and
budget checking.
• Describe how the Fixed assets module is used.
• Review the data model for fixed assets.

Introduction
The following section describes a series of tasks that show the functionality used
in the General ledger, Budgeting, and Fixed assets modules. Participants will
be given the opportunity to understand the purpose of these modules from a
user’s viewpoint. Additionally, several of the key data and object models related
to these modules will be reviewed.

4-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

General Ledger Overview


The general ledger is used to define and manage a legal entity’s financial records.
It is a formal ledger that contains a company’s accounting records, and is a
register of debit and credit entries. These entries are classified by using the
accounts that are listed in a chart of accounts.

You can allocate, or distribute, monetary amounts to one or more accounts or


account and dimension combinations based on allocation rules. There are two
types of allocations—fixed and variable. You can also settle transactions between
ledger accounts and revalue currency amounts. At the end of a fiscal year, you
must generate closing transactions and prepare your accounts for the next fiscal
year.

You can use the consolidation functionality to combine the financial results for
several subsidiary legal entities into results for a single, consolidated
organization. The subsidiaries can be in the same Microsoft Dynamics® AX
database or in separate databases.

You can use the tools for forecasting cash flow and currency requirements to
estimate your legal entity’s future cash needs. You can then calculate, view, and
print forecasts of the cash flow. You can also calculate and display currency
requirements.

To make the general ledger functional in Microsoft Dynamics AX 2012, you


must set up the chart of accounts, fiscal calendars, legal entities, and currencies.
The chart of accounts is a list of main accounts and financial dimensions that are
allowed by one or more account structures.

Fiscal calendars specify what time period financial data is posted, while currency
setup determines which currencies are available for business transactions.

Currency and Exchange Rate Setup


Currency setup is a mandatory step in Microsoft Dynamics AX and is used to
record financial transactions.

Multi-currency functionality can be used if your company does business in more


than one currency. If your organization has multiple legal entities and transacts in
multiple currencies, then maintaining currencies and their corresponding
exchange rate is essential.

In Microsoft Dynamics AX, all currencies are provided by default. The


currencies are loaded the first time a user opens the General ledger parameters
form.

4-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

To view currencies open General ledger > Setup > Currency > Currencies.

FIGURE 4.1 CURRENCIES FORM

Accounting and Reporting Currencies


Microsoft Dynamics AX uses the concept of Accounting currency and
Reporting currency.

• Accounting Currency: The customary monetary unit of measure


used to record the converted monetary value of economic
transactions in ledger accounts. The previous releases of Microsoft
Dynamics AX called this the company currency.
• Reporting Currency: The monetary unit of measure used to record
the converted monetary value of economic transactions in ledger
accounts for financial and management reporting purposes.

An example of this would be if you had a subsidiary company in Canada, and


your primary company is in the United States. When running reports you want to
see the results of the business operations in Canadian dollars (CAD). To
accomplish this, you must convert your U.S. dollars (USD) to CAD; the system
uses the exchange rate defined on the Exchange rates form to convert the
amounts for reporting purposes.

Revaluation of foreign currency balances is a periodic task in the General ledger


module. If the account in question is controlled by another module, such as the
Customers or Vendors, then exchange rate adjustments should be performed in
the Accounts receivable or Accounts payable module instead of the General
ledger module.

4-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Currency Calculation
Four pieces of information are necessary to perform a currency calculation in
Microsoft Dynamics AX 2012.

• From currency
• To currency
• Date
• Exchange rate type

When performing a calculation in the context of a given legal entity, the


exchange rate type and one of the currencies can be derived from the ledger that
is associated with that legal entity. For example, assume that an accounting
currency of USD and an exchange rate type of SELL are set up for a given
ledger. When that ledger is passed to the calculation engine and the
calculateTransactionToAccounting method is called, the calculation engine is
able to automatically determine that the accounting currency is USD and the
exchange rate type is SELL.

In most cases, calculations will be performed in the context of a given ledger.


When performing a calculation outside of the context of a ledger, it is still
possible to provide all of the necessary information by using the methods that are
prefixed with parm on the calculation engine.

CurrencyExchangeHelper Class
The CurrencyExchangeHelper class is introduced in Microsoft Dynamics AX
2012. It is the recommended Application Programming Interface (API) to
perform calculations between currencies. The following examples illustrate its
usage for the most common scenarios.

This example calculates the amount in the context of the current ledger. This is
indicated by passing Ledger::current() to the constructor method of the
CurrencyExchangeHelper class.

CurrencyExchangeHelper currencyExchangeHelper;
TransDate transactionDate;
CurrencyCode transactionCurrency = 'CAD';
AmountCur amountToConvert = 100.50;
boolean shouldRoundResult = true;
AmountMst result;

currencyExchangeHelper =
CurrencyExchangeHelper::newExchangeDate(
Ledger::current(),
transactionDate);

result =
currencyExchangeHelper.calculateTransactionToAccounting(

4-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

transactionCurrency,
amountToConvert,
shouldRoundResult);

info(strrfmt("%1",result));

NOTE: Additional code samples for calculating the transaction currency from
the accounting currency, and calculating the amounts by using an exchange rate
that is entered are available in the Shared Currencies and Exchange Rates
(http://go.microsoft.com/fwlink/?LinkId=238176)white paper.

ExchangeRateHelper Class
The same information used to perform currency calculations is used to work with
exchange rates.

• From currency
• To currency
• Date
• Exchange rate type

Retrieving exchange rates

Two exchange rates (ExchangeRate1 and ExchangeRate2) must always be


considered when retrieving or using exchange rates in the application. This is
because the calculation for the currency amount will include triangulation if any
currency involved in the calculation is set up as the triangulation currency or is a
denomination currency. This results in scenarios where a currency calculation
requires two exchange rates.

• Under normal circumstances, amounts could be converted directly


from Great British Pounds (GBP) to United States Dollars (USD),
which would require only one exchange rate.

1. GBP > USD


2. ExchangeRate1 would be non-zero
3. ExchangeRate2 would be zero

• Assuming that GBP is a denomination of the euro (EUR) currency


which is set up as the triangulation currency, amounts would require
two exchange rates (triangulation) to calculate GBP to USD.

1. GBP > EUR > USD


2. ExchangeRate1 would be non-zero
3. ExchangeRate2 would be non-zero

4-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

There are nine possible triangulation scenarios, three of which require two
exchange rates. As a result, all code must assume that two exchange rates are
possible and must always take this into account when storing them or passing
them to the calculation engine.

If a subsystem uses one exchange rate, most likely it is incorrect unless that rate
is a true cross rate that factors in both exchange rates. (Note that the
getCrossRate and getCrossRateReciprocal methods on the
ExchangeRateHelper class do factor in triangulation.)

Another important concept to understand is that the rates are always stored in
terms of the transaction (or reporting) currency to the accounting currency.
Therefore, when calling the exchange rate engine, make sure to set the “from”
and “to” currency accordingly. This is illustrated in the following example.

ExchangeRateHelper exchangeRateHelper;
TransDate transactionDate;
CurrencyCode transactionCurrency = 'CAD';
CurrencyExchangeRate exchangeRate1;
CurrencyExchangeRate exchangeRate2;

exchangeRateHelper = ExchangeRateHelper::newExchangeDate(
Ledger::current(),
transactionCurrency,
transactionDate);

exchangeRate1 = exchangeRateHelper.getExchangeRate1();
exchangeRate2 = exchangeRateHelper.getExchangeRate2();

info (strfmt("ExchRate1= %1; ExchRate2= %2”,


exchangeRate1, exchangeRate2));

4-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Currency and Exchange Rate Data Model


The following figure shows the data model for the currency, exchange rate, and
ledger data model.

FIGURE 4.2 CURRENCY AND EXCHANGE RATE DATA MODEL

Periods and Fiscal Year Setup


The fiscal year in Microsoft Dynamics AX can be set to any length, divided into
any number of periods and may be shared across multiple legal entities.

Both fiscal year and periods can be set up by the following measurements of
time—years, months and/or days.

Each period (at the ledger level) can be closed completely or put on hold to block
transaction postings, or set to enable selected users to continue an update of one
or more modules. To do this, open General ledger > Setup > Ledger, and then
click the Ledger calendar button.

The periods and fiscal year feature is useful for the preparation and reconciliation
of periodic and yearly accounts.

4-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Fiscal calendars are shared across multiple legal entities. The benefits of sharing
fiscal calendars include the following.

• Will support multiple fiscal calendars for each legal entity. For
example, fixed assets could require two calendars—one for auditing
purposes and one for tax purposes. If you have multiple calendars
you can run parallel depreciations.
• Reduces the amount of setup required for each legal entity because it
is possible to use the same fiscal calendar for multiple legal entities.
Before posting transactions, a new fiscal year must be divided into
periods since transactions cannot post unless a period is created for
the posting date.

Chart of Accounts
A chart of accounts is a set of main accounts tracked by Microsoft Dynamics
AX. It captures financial information that is used to make sound financial
decisions. Each account is assigned an account number as a unique identifier.
Each chart of accounts contains the account structures used by the chart of
accounts to define the segments and the valid combinations of main accounts and
financial dimension values. The chart of accounts is shared and it is also a list of
main accounts and structures, used to define a chart of accounts in use by one or
more ledgers.

Multiple Chart of Accounts


Many large organizations use the same chart of accounts across multiple
companies. You can define company specific data, such as the default sales code
on the main account, and inactivate financial dimension values for a specific
company. The following entities/objects will have company specific data.

• Main account
• Dimension values

The following elements comprise the shared chart of accounts.

• Chart of accounts
• Main accounts
• Account structures
• Advanced rules
• Financial dimensions
• Financial dimension values

4-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Financial Dimensions
Characteristics of financial dimensions include the following.

• Provide a more detailed description of a transaction.


• Simplify the accounting process when you enable detailed analysis
without the creation of a detailed chart of accounts.
• Defined to analyze and classify financial transactions as follows.
o Financial transactions usually are organized according to
voucher and account number.
o Additional grouping and classification options are available
when you assign several dimensions to transactions.

• View the data file from different perspectives to improve the


effectiveness in tracking figures across accounts.
• Can be used throughout the system, and add dimensions to base data
such as:
o Ledger accounts
o Customers
o Vendors

• Can be copied to transactions automatically.

You can use the Financial dimensions form to create financial dimensions that
you can use as account segments for shared charts of accounts. Open General
ledger > Setup > Financial dimensions > Financial dimensions. There are two
basic types of financial dimensions.

• System-defined: Select a system-defined entity to base the financial


dimension on. Financial dimension values will be created from this
selection. For example, to create dimension values for projects,
select Projects. A dimension value will be created for each project
name.
• User-defined: To create a user-defined financial dimension, select <
Custom dimension >.

Financial Dimension Values

After you have created the financial dimensions, use the Financial dimension
values form to assign additional properties to each financial dimension. When
you define a dimension that is based on a system-defined entity, you cannot add
values in the Financial dimension values form. However, you can view the
values. To add new values, you must access the main form for system entity. For
example, for the Customer entity you must add a customer in the Customer
form.

4-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Financial Dimension Templates

Dimension templates can be used for common patterns to distribute source


document amounts. Use the Financial dimension default templates form to
create a template of percentage and financial dimension value combinations. The
information in the template will be used to display default financial dimension
values when you distribute source document amounts.

Financial Dimension Sets

Financial dimension sets have several purposes. Financial dimension sets are
used to determine how reports and inquiries related to the general ledger are
rendered. They are also used to calculate balances during the posting process.
Balances can also be scheduled for calculation or manually updated.

Balances are stored based on the financial dimension set and are calculated based
on the option to calculate with posting or batch schedule. Financial dimension
sets also drive the data displayed in the Trial balance list page.

The order in which financial dimension sets are considered in reporting effect
how transactions are sorted and fields are presented. For example, the set
Department and Cost center indicates that the Department dimension type is
first and Cost center second. Therefore, the considered financial set is the
composite of Department and Cost center. Department amounts are presented
first and Cost center amounts are presented second.

The defined financial dimension set can be used alone or in pairs when inquiring
or reporting on financial transactions. The selection of a primary and secondary
financial dimension set is considered when presenting the results. The secondary
financial dimension set details the figures of the primary dimension set. The
selection of a secondary financial dimension set is limited to dimension types that
do not share a dimension type with a primary dimension set. Therefore, if the
primary dimension set is the composite of Main account and Department, these
cannot be selected in the secondary financial dimension set.

Account Structures
You can use the Configure account structures form to create one or more
account structures. Open General ledger > Setup > Chart of accounts >
Configure account structures.

Accounts structures provide the segments and order of entry for the account
number. Main account is a required segment for an account structure, but it does
not have to be the first segment. The account structures are used to define the
valid combinations which, together with the main accounts, form a chart of
accounts. Multiple account structures allow a legal entity to track information for
specific accounts without affecting information in other accounts.

To change an existing account structure, and to enable some of the controls in


this form, you must click Edit, so that the account structure has a Draft status.

4-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Data Patterns
Default Account

The default account pattern consists of a single segment, main account. The
default account is a separate pattern from the main account because of the
additional business logic built into its underlying control. This business logic
handles data restrictions in lookups and other critical functionality that would
have to be developed separately in each uptake scenario without the control. A
foreign key representing a default account is a 64-bit integer field that contains
the data from the corresponding RecId field in the
DimensionAttributeValueCombination (or LedgerDimension) table.

Foreign key fields for default accounts are named LedgerDimension because that
is the alias used for the DimensionAttributeValueCombination table.

Main Account

The main account pattern represents just one of the possible segments in a ledger
account. A main account is required in a ledger account, but it does not have to
be the first segment. When referencing a main account as a foreign key, the
developer should set up a reference to the RecId field in the MainAccount table.

Ledger Account

A ledger account contains the main account, account structure, and the financial
dimension values that are needed to populate the related account structure and
account rule structures. A foreign key representing a ledger account is a 64-bit
integer field that contains the data from the corresponding RecId field in the
DimensionAttributeValueCombination (or LedgerDimension) table. Foreign key
fields for ledger accounts are named LedgerDimension because that is the alias
used for the DimensionAttributeValueCombination table.

Multi-type Account

The multi-type account pattern consists of an account type field and its related
ledger account or default account. In this pattern, a ledger account or default
account can store accounts other than ledger accounts. When the account type
field for the related account is set to “ledger,” this pattern becomes the default
account or ledger account pattern (depending on the extended data type used for
the field). If the account type field is not set to “ledger,” the pattern stores a
system-generated account structure (used to specify which account number
should be stored in the field) and an account number for the related account type.
For example, if the account type field is set to “customer,” the related account
number field will contain a customer number with a related account structure that
indicates that the account number field should contain a single customer value.

4-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

This pattern is primarily used for the setup and entry of financial journals. In this
case, a multi-type account will store one of six types of accounts, based on the
related account type field (asset, bank, customer, vendor, project, or ledger). A
foreign key representing a multi-type account is a 64-bit integer field that
contains the data from the corresponding RecId field of the
DimensionAttributeValueCombination (LedgerDimension) table. Foreign key
fields for multi-type accounts are named LedgerDimension because that is the
alias used for the DimensionAttributeValueCombination table.

4-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The following figure shows the data model for the chart of accounts.

FIGURE 4.3 CHART OF ACCOUNTS DATA MODEL

Default Dimensions

The default dimension pattern represents a set of financial dimensions and their
related values. A customer will set the values for given financial dimensions on
master data records for defaulting purposes or directly on some transactions. In
Microsoft Dynamics AX 2012, this pattern is represented by a single field. The
single field is a foreign key reference to the RecId field in the
DimensionAttributeValueSet table. This value references the correct record in the

4-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

DimensionAttributeValueSet (or Default Dimension) table. The data model in


previous releases limited storage to 10 financial dimensions, the new model
allows you to store an unlimited number of financial dimensions and their values.

Dimension Set

The dimension attribute set pattern represents a set of financial dimensions and
their related enumeration values. This pattern is used in advanced general ledger
processing where different financial dimensions can be handled differently, based
on these stored enumeration values.

The dimension attribute set pattern is used to store a set of financial dimensions
and related data, such as enumeration values. This pattern is used in places where
it is necessary to store additional information about dimensions, such as whether
they are optional or required. For an example of this implementation, refer to the
VendPaymMode form under Forms in the Application Object Tree (AOT). A
foreign key representing a dimension attribute set is a 64-bit integer field that
contains the data from the corresponding RecId field of the
DimensionAttributeSet table. The new model allows you to store an unlimited
number of financial dimensions.

4-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The following figure shows the data model for the financial dimensions.

FIGURE 4.4 FINANCIAL DIMENSIONS DATA MODEL

Procedure: Add a Default Dimension Control to a Form


The Default Account control is a combination of the Segmented Entry control
and the LedgerDimensionDefaultAccountController class. The
LedgerDimensionDefaultAccountController class handles the events raised by
the Segmented Entry control.

4-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Changes needed on the form

In simple scenarios, the changes needed on the form are as follows:

TIP: You can create a new form, or you can use the VendPaymMode form in the
Hyper-V training environment to implement these changes.

1. Verify that the table that will hold the foreign key to the
DimensionAttributeValueCombination table as a data source on the form.

2. Drag the LedgerDimension field from the data source to the desired location
on the form design. This should add a Segmented Entry control at this location
on the form with appropriate DataSource and ReferenceField property values.
Alternatively, you can complete this step by adding a Segmented Entry control to
the design and manually setting the DataSource and ReferenceField properties.

3. Override the following methods on the form.

public class FormRun extends ObjectRun


{

//Declare the ledgerDimensionDefaultAccountController


LedgerDimensionDefaultAccountController
ledgerDimensionDefaultAccountController;
}

public void init()


{
super();

//Instantiate a new instance of the class


ledgerDimensionDefaultAccountController =
LedgerDimensionDefaultAccountController::construct(myTable_
ds,
fieldstr(MyTable, LedgerDimension));
}

4. Overload the following methods on the Segmented Entry control instance in


the form design.

public void jumpRef()


{
ledgerDimensionDefaultAccountController.jumpRef();
}

public void
loadAutoCompleteData(LoadAutoCompleteDataEventArgs _e)
{

ledgerDimensionDefaultAccountController.loadAutoCompleteDat
a(_e);
super(_e);
}

4-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

public void
segmentValueChanged(SegmentValueChangedEventArgs _e)
{

ledgerDimensionDefaultAccountController.segmentValueChanged
(_e);
super(_e);
}

public void loadSegments()


{
super();
// (Optional parm*() specification should go here, see
the Control options section.)

ledgerDimensionDefaultAccountController.parmControl(this);

ledgerDimensionDefaultAccountController.loadSegments();
}

public boolean validate()


{
boolean isValid;
isValid = super();
isValid =
ledgerDimensionDefaultAccountController.validate() &&
isValid;
return isValid;
}

5. Overload the following methods on the data source field that backs the
Segmented Entry control.

public Common resolveReference(FormReferenceControl


_formReferenceControl)
{
return
ledgerDimensionDefaultAccountController.resolveReference();
}

Control Options

There are four parameter methods available for specifying items that the control
can link to and validate. These parameter methods should be called in the
loadSegments method. These methods are called every time that the control
receives focus. Always declaring the parameters in one method ensures that
developers can easily verify whether all parameters have been correctly set.

• parmCurrentLedgerCOA: Specifies a particular chart of accounts


for a legal entity from which to derive the list of main accounts and
structures. The default value is the chart of accounts in the current
legal entity.

4-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• parmFilterLedgerPostingType: Specific main accounts can be


excluded from the lookup based on the posting type, but the values
are allowed to be entered manually. The default value is None,
meaning all accounts are valid.

NOTE: The parameter name (LedgerPostingType) differs from the one for the
Ledger Account control because, in this case, it only restricts what is shown in
the lookup when the filter is selected. For account entry, it prevents entry of
values entirely.

• parmIncludeFinancial and parmIncludeTotal: Specific main


accounts can be excluded from the lookup and prevented from being
entered manually. The IncludeStatistical and IncludeTotal
parameters are used for validation and lookup to restrict valid values.
The default value for each parameter is false.

NOTE: There is no special control for the main account pattern. This pattern
uses a foreign key that has a standard pattern in Microsoft Dynamics AX 2012.

Procedure: Add a Ledger Account Control to a Form


When you need to add a Ledger account control to a form, use the same process
that is used in the "Add a Default Dimension Control to a Form" procedure.
Instead of using the LedgerDimensionDefaultAccountController class, use the
LedgerDimensionAccountControllerclass. This class has similar methods and can
be called in the same way.

Control Options

The LedgerDimensionAccountController has several additional parameters


available for validating, looking up, and saving ledger accounts from the
Segmented Entry control. The following methods are used to set these
parameters.

• parmCurrency: Specifies the currency code associated with the


control being managed. The Currency parameter is used for
validation and lookup to restrict valid values. The default value is
empty and no restriction or validation is done against the currency.
• parmLockMainAccountSegments: Specifies whether the main
account segment can be modified. The default value is false.
• parmJournalName: Specifies the journal name associated with the
control being managed. The JournalName parameter is used for
validation and lookup to restrict valid values. The default value is
empty and no restriction or validation is done against the journal
name.

4-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

• parmPostingType: Specifies the posting type associated with the


control being managed. The PostingType parameter is used for
validation and lookup to restrict valid values. The default value is
empty and no restriction or validation is done against the posting
type.
• parmTaxCode: Specifies the tax code associated with the control
being managed. The TaxCode parameter is used for validation and
lookup to restrict valid values. The default value is empty and no
restriction or validation is done against the tax code.
• parmUser: Specifies the user associated with the control being
managed. The User parameter is used for validation and lookup to
restrict valid values. The default value is the current user.

These parameters should be specified in the loadSegments method. They are


called every time the control receives focus. Always declaring the parameters in
one method ensures that developers can easily verify if all parameters have been
correctly set.

System-Defined Dimensions
With system-defined dimensions, it is not necessary to maintain two separate lists
of values for an entity you want to track details for in the general ledger. When
you set up a system-defined dimension, the values for the entity are automatically
copied from the entity table into the dimension values. Any time the data is
modified or a new record is inserted into the backing entity table, the information
is automatically updated in the dimension values.

Scenario

Ken, the Controller, wants to track the vehicle details in the general ledger.
Simon, the Business System Developer, needs to create a new system-defined
dimension for vehicles so that Ken will not need to maintain a custom list of the
vehicles in the Financial dimensions form.

After the new system-defined dimension is created, Ken must set up the new
financial dimension to be linked to the vehicles backing entity. Then, he must
add the new financial dimension to the account structure or advanced rules for
the chart of accounts. Simon also needs to add defaulting logic to the Vehicles
form so that when a new vehicle is created, the financial dimension for vehicles
will default to the current vehicle ID and cannot be changed. Then he must add
logic to the Rentals form to copy the financial dimensions from the vehicle to the
rental record.

Demonstration: Add a System-Defined Dimension


The options available in the Use values from field on the Financial dimensions
form are retrieved by using the DimensionEnabledType class. The
getSystemDefinedDimensionServer method searches for views with a name
beginning with DimAttribute. The view must have three fields named Key,
Value, and Name that are used to display the list of values from the table.

4-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

To add a new system-defined dimension, follow these steps.

1. Open the Development Workspace.


2. Expand the Data Dictionary node in the AOT window.
3. Right-click the Views node and then click New View.
4. In the Properties window for the new view, set the following
properties.
a. Name = DimAttributeFMVehicle

IMPORTANT: This name must begin with "DimAttribute" or it will not be


selected by the getSystemDefinedDimensionServer method.

b. Label = Vehicles

NOTE: This is the description that will appear in the Use values from drop-
down list on the Financial dimensions form.

c. FormRef = FMVehicle
d. SingularLabel = Vehicle

5. Expand the Metadata node of the DimAttributeFMVehicle view.


6. Open a new AOT window, and then locate the FMVehicle table and
drag it to the Data Sources node of the DimAttributeFMVehicle
view.
7. In the Properties window for the new data source, enter
BackingEntity in the Name property, and then save the view.
8. Expand the Fields node of the DimAttributeFMVehicle view and the
Fields node of the BackingEntity data source.
9. Drag the RecID field from the BackingEntity > Fields into the Fields
node for the view.
10. In the Properties window for the RecID field, enter Key for the
name.
11. Drag the VehicleId field from the BackingEntity > Fields into the
Fields node for the view.
12. In the Properties window for the VehicleId field, enter Value for the
name.
13. Drag the Description field from the BackingEntity > Fields into the
Fields node for the view.
14. In the Properties window for the Description field, enter Name for
the name.

CRITICAL: The three fields must be named Key, Value, and Name for the
dimension to function correctly.

4-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

15. Click Save all to save the view.


16. Restart the Application Object Server (AOS). This step is required to
clear the cache.

Demonstration: Test the System-Defined Dimension


To test the new system-defined dimension, follow these steps.

1. Open Microsoft Dynamics AX 2012.


2. Open Fleet management > Setup > Fleet setup.
3. On the Vehicle make and models tab, click New in the Make grid,
and then enter a vehicle make.
4. In the Model grid click New, and then enter a model and model
specification.
5. Close the Fleet management configuration form.
6. Open Fleet management > Vehicles > All vehicles.
7. Click Vehicle in the New group of the Action Pane.
8. Click Create on the dialog box.
9. Enter a Vehicle ID if one is not created for you.
10. Enter a VIN number.
11. Select a Vehicle model from the list.
12. Close the Vehicle form.
13. Open General ledger > Setup > Financial dimensions > Financial
dimensions.
14. Click New.
15. In the Use values from field, select Vehicles.
16. Click the Financial dimension values button.
17. Notice the vehicle that you created in step 7, and that the New icon is
disabled. Close all the forms.

NOTE: At this point, you have created a system-defined dimension and set it up
as financial dimensions. Additional steps would be required to add the dimension
to an account structure or advanced rule. Additional coding would also be
required to default the dimension value on the vehicle and to copy the value from
vehicles to rentals.

4-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 4.1 - Create a System-Defined Dimension


This lab demonstrates how to create a new system-defined dimension.

This lab is designed for self-study. Completing this lab takes approximately 20
minutes.

Scenario

Ken, the Controller, wants to track the rental details in the general ledger. Simon,
the Business System Developer, needs to create a new system-defined dimension
for rentals so that Ken will not need to maintain a custom list of the rentals in the
Financial dimensions form.

After the new system-defined dimension is created, Ken must set up the new
financial dimension to be linked to the vehicles backing entity.

Challenge Yourself!
Use the information provided to create a new system-defined dimension for
rentals. The table that stores rentals is called FMRentals.

Need a Little Help?

1. Create a new project to store the development changes.


2. Create a new view and make sure to name the view correctly.
3. Add the FMRental table to the view.
4. Add three fields to the view for the Key, Value, and Name.
5. Save the view and then restart the AOS.
6. Test your work by adding a new financial dimension.

Step by Step
To add a new system-defined dimension, follow these steps.

1. Open the Development Workspace.


2. Expand the Data Dictionary node in the AOT window.
3. Right-click the Views node and then click New View.
4. In the Properties window for the new view, set the following
properties.
a. Name = DimAttributeFMRental
b. Label = Rentals
c. FormRef = FMRental
d. SingularLabel = Rental

5. Expand the Metadata node of the DimAttributeFMRental view.

4-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

6. Open a new AOT window, and then locate the FMRental table and
drag it to the Data Sources node of the DimAttributeFMRental view.
7. In the Properties window for the new data source, enter
BackingEntity in the Name property, and then save the view.
8. Expand the Fields node of the DimAttributeFMRental view and the
Fields node of the BackingEntity data source.
9. Drag the RecID field from the BackingEntity > Fields into the Fields
node for the view.
10. In the Properties window for the RecID field, enter Key for the
name.
11. Drag the RentalId field from the BackingEntity > Fields into the
Fields node for the view.
12. In the Properties window for the RentalId field, enter Value for the
name.
13. Drag the Comments field from the BackingEntity > Fields into the
Fields node for the view.
14. In the Properties window for the Comments field, enter Name for
the name.
15. Save the view.
16. Close Microsoft Dynamics AX.
17. Open Start > Administrative Tools > Services. Locate the
Microsoft Dynamics AX service and then click Restart service.

To test the new system defined dimension, follow these steps.

1. Open Microsoft Dynamics AX 2012.


2. Open General ledger > Setup > Financial dimensions > Financial
dimensions.
3. Click New.
4. In the Use values from field, select Rentals.
5. Close the form.

TIP: You can import the AX2012_ENUS_DEVIV_04_01_LAB_SOL.xpo file to


verify and compare your solution.

4-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Journals and Transactions


Although many activities are automatically reflected in the general ledger,
information can also be entered manually by using journals. These journals
contain information that is not included in automatic postings and in the
manually entered corrections of automatic postings.

Journals Overview
A journal is a worksheet you can use before you manually enter postings into the
system. Before you use financials in Microsoft Dynamics AX, you must
complete the setup procedures for journals. The procedures include the basic
setup of journals such as journal names, controls, and texts. You can use journals
quickly and efficiently when you set them up correctly.

Both manual and system generated journals exist in Microsoft Dynamics AX.
Examples of system generated journals are allocation journals and elimination
journals. These journals are created automatically and are never created
manually. Manual journal entries are generated by postings entered into the
system such as a general journal entry. When you use a manual journal entry the
transactions are not posted immediately. Before you post a manual entry, the
journal can be changed, reviewed, approved, or deleted.

In Microsoft Dynamics AX, you can use journals to do the following.

• Control different kinds of entries. You can apply an approval system


so that special journals are posted only after they are approved.
• Review data imported from external ledger systems. You can ensure
that all valid fields contain a value and that all restrictions for the
transaction are fulfilled.
• Make sure that the necessary voucher series is set up before you
create journals. You can set up number sequences and attach them to
the appropriate references.

Users can post transactions to the following accounts by using a general journal.

• General ledger
• Bank
• Customer
• Vendor
• Projects
• Fixed assets

4-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

In a general journal, users enter the following information for the transaction.

• Posting date
• Amount
• Accounts to post to

The information users enter in a general journal is temporary and can be changed
if it remains unposted within the journal.

4-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Journals Data Model


The following figure shows the data model for journals.

FIGURE 4.5 LEDGER JOURNAL DATA MODEL

The LedgerJournalName table contains defined journal names. Each journal


name has a set of parameters that are implemented as fields in this table. The
table contains journal names that are used in the Ledger, Customer (accounts
receivable), Vendor (accounts payable), and Project modules.

4-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The LedgerJournalControl table contains restrictions on the transactions posted


in the related journal name. Restrictions can refer to company, posting layer,
transaction type, account number, or user group.

The LedgerJournalTable table contains one record for each journal. A journal is a
set of journal transactions with a given status—either created or posted. Each
journal is related to a journal name and has a journal number. When a journal is
created, many of its parameters are copied from the corresponding record in
LedgerJournalName and can be set up individually for each journal. Records in
LedgerJournalTable are also used to block the journal while it is being posted.

The LedgerJournalParmPost table contains parameters that are used when you
post multiple journals by the batch. This is a periodic function, and it is an
alternative to activating posting directly from the current journal.

The LedgerJournalTrans table contains individual journal lines. When a journal


is posted, all journal lines are either posted or moved to another non-posted
journal. A journal cannot contain both posted and non-posted lines at the same
time. Each journal line has a line number that is used to sort journal lines. This
field should not be used to identify a journal line, because it does not have to be
unique. If you must have a unique reference for a journal line, you should use the
RecId field. Asset and Project transaction information is stored in the
LedgerJournalTrans_Asset and LedgerJournalTrans_Project tables related to the
LedgerjournalTrans table record.

The LedgerJournalTxt table can be used to store typically used transaction texts.
Each text is associated with an alias that can be used when you enter information
in the journal line’s Description field. This table is not related to other tables that
are used by the ledger journal.

Journals Posting Framework


The LedgerJournalCheckPost class handles the validation and posting of a ledger
journal.

The postJournal() method selects the lines of the journal. For each journal line
postTrans() is called.

The class can be activated directly from X++ by using the following lines:

ledgerJournalCheckPost =
LedgerJournalCheckPost::newLedgerJournalTable(

ledgerJournalTable,

NoYes::Yes);

ledgerJournalCheckPost.run();

4-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The second parameter specifies whether the journal should be posted (true) or
validated (false).

The update of the individual journal line is handled by the class hierarchy
LedgerJournalTransUpdate.

FIGURE 4.6 LEDGERJOURNALTRANSUPDATE TYPE HIERARCHY


BROWSER

The check() method is used when validating the journal. The checkWhenPost()
method is used when validating the journal during posting and the updateNow()
method handles the update of the posting.

The posting is handled over to the LedgerVoucher class.

Transactions Overview
The General ledger module records the value of all company assets. This
includes cash, accounts receivable, bank accounts, stocks, bonds, inventory,
buildings, and machinery. Any event that changes the value of these assets
should be reflected in ledger transactions.

4-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The following figure shows General ledger module interfaces with other
Microsoft Dynamics AX modules:

FIGURE 4.7 GENERAL LEDGER INTEGRATIONS

The Inventory and warehouse management module keeps track of items


available for sale. Every time an item is bought or sold, the corresponding figure
that represents the inventory value in the General ledger module will change.
These transactions come from inventory journals, sales orders, purchase orders,
transfer orders, or other inventory transactions.

The sales and purchase orders facilitate trade with vendors and customers.
Related stock changes are handled by the Inventory and warehouse
management module. Invoice payments occur through the Accounts payable
and Accounts receivable modules by using invoice journals and payment
journals. Every sales order generates revenue and a corresponding cost of goods
sold. Both are reflected in the General ledger module.

The Cash and bank management module keeps track of company bank
accounts, whose balance values are also reflected in the General ledger module.
When payments are posted to customer or vendor accounts using the payment
journals the customer and vendor balances are updated at the same time.

The Project management and accounting module keeps track of projects. This
includes registration of hours and customer invoicing. Revenues and related costs
are posted in the General ledger module. The periodic revenue assessment on
fixed price projects is also reflected in related transactions in the General ledger
module.

4-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The Fixed assets module keeps track of material assets used for operations such
as buildings and machinery and are not intended for sale like inventory products.
These asset values are recorded in the General ledger module, just as asset
revaluation and depreciation are also reflected there.

The Budgeting module keeps track of plans or budget amounts for the chart of
accounts. These estimated or budgeted amounts can then be compared to actual
amounts in the general ledger. The budget amounts are often times generated
based on the actual amounts from the general ledger.

Transactions Data Model


When a transaction is posted to the General ledger the information is recorded in
several different tables. This includes manual journals and other types of
automatic transactions such as sales order invoices, or inventory transfers. The
following figure shows the ledger transactions data model.

FIGURE 4.8 GENERAL LEDGER TRANSACTIONS DATA MODEL

Ledger Posting Framework


The ledger posting framework is the API used to post to the general ledger and
includes the LedgerVoucher, LedgerVoucherObject, and
LedgerVoucherTransObject classes and related classes. Developers can use the
factory methods in the LedgerVoucherTransObject class to create instances of
these classes.

Multiple factory methods exist to support different input scenarios. After using
one of these methods to create a class instance, a developer can customize the
instance by using the parm methods.

4-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The LedgerVoucherTransObject class exposes the fields in the following tables:

• GeneralJournalAccountEntry
• LedgerEntry
• GeneralJournalEntry
• LedgerEntryJournal

LedgerVoucher Class
The task of the LedgerVoucher class is to control ledger transaction postings.
You can use this class when you post ledger journals and other updates that
contribute to ledger transactions. It verifies the posting is correct and that the
voucher balances. The LedgerVoucher class holds all the vouchers in temporary
storage (a list array) until the End method is called. The End method creates
ledger transaction records from the temporary postings.

An instance of LedgerVoucher can handle several individual vouchers in one


transaction. All vouchers handled will be updated in the sum tables in one
consolidated step.

Each voucher is represented by an instance of LedgerVoucherObject.

LedgerVoucherTransObject contains individual transactions that will be created.


A LedgerTrans variable is defined in the class declaration to contain the future
transaction. The class structure resembles the following.

Posting (LedgerVoucher)

• Voucher (LedgerVoucherObject)
o Trans (LedgerVoucherTransObject)
o Trans

• Voucher
o Trans
o Trans

If new fields are added to the ledger transactions, this object can also hold the
new information. The remaining task is to initialize the new fields which
involves the following two steps.

1. Creating parm-method(s) to assign values to the field(s).


2. Changing the static method new() to include the new parm-methods.

LedgerVoucher can handle posting with aggregated transactions. LedgerVoucher


uses a RecordSortedList to sum up aggregated transactions. The sort order is
defined in initLedgerTransList(), whereas the aggregation is calculated in the
postGroup() method which handles all numeric fields that will be aggregated.

4-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The steps in posting ledger transactions by using LedgerVoucher are:

ttsbegin;

ledgerVoucher = LedgerVoucher::newLedgerPost(….)
ledgerVoucher.addVoucher(LedgerVoucherObject::newVoucher(…)
);
ledgerVoucher.addTrans( LedgerVoucherTransObject::new…(…));
ledgerVoucher.addTrans( LedgerVoucherTransObject::new…(…));
ledgerVoucher.addTrans( LedgerVoucherTransObject::new…(…));
ledgerVoucher.addVoucher(LedgerVoucherObject::newVoucher(…)
);
ledgerVoucher.addTrans( LedgerVoucherTransObject::new…(…));
ledgerVoucher.addTrans( LedgerVoucherTransObject::new…(…));
ledgerVoucher.end();

ttscommit;

AXLedgerJournalTrans Class
The Ax-classes provided with Microsoft Dynamics AX are an encapsulation of
records and are typically used when importing data to Microsoft Dynamics AX.

It is a best practice to import transactions by importing the data to a journal and


letting the standard application handle the posting and generation of transactions.

An import to LedgerJournalTrans can be handled by the classes


AxLedgerJournalTable and AxLedgerJournalTrans.

4-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Lab 4.2 - Import Ledger Transactions


This lab demonstrates how to import data into a journal and let the standard
application generate the transaction.

Estimated time to complete: 40 minutes

Scenario

Actively participating during this workshop will help you with the following.

• Understand the concept of how to import data into a journal and let
the standard application generate the transaction.
• Become familiar with the use of Ax-classes to import data to
Microsoft Dynamics AX tables.
• Extend the generic framework for importing data to be implemented
for a specific task with minimal effort.

Requirement
Create a solution that contains a function to import ledger transactions into the
general journal.

The file consists of records with the following information:

• Ledger account
• Transaction date
• Voucher number
• Transaction text
• Currency code
• Amount in currency

A sample of the file will resemble the following.

"606200","2006/09/10","ext00005","Insurance third
quarter","EUR",100.00

"606300","2006/09/10","ext00005","Pencils","EUR",200.00

"110180","2006/09/10","ext00005","Misc. cash
expenses","EUR",-300.00

"606300","2006/09/11","ext00006","Copy paper","USD",70.00

"110180","2006/09/11","ext00006","Copy paper","USD",-70.00

4-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Technical Issues
Base Import

A generic import class is included in your Hyper-V training image that can be
extended to the specific import tasks.

The AXABaseImport class is a generic class for importing files.


AXABaseImport is abstract and extends RunBaseBatch. A dialog box that can
browse for a file is implemented for the reading of the file. Three methods are
implemented. All three methods are called from the run method in
AXABaseImport.

• preImport(): This method is called once before importing data.


• importRecord(): This method is called once for each record read in
the file. This method takes a container as argument. This container
contains the data from one record read in the file.
• postImport(): This method is called once after all the records in the
file are read.

To create a class which can import from a file, you extend this class and override
these three methods.

Vouchers

When transactions are manually entered in the ledger journal, the vouchers are
typically allocated automatically by using a number sequence. To assign the
voucher during the import, the journal used should be set up with a manual
number sequence for vouchers.

4-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The number sequence is specified on the journal name in the LedgerJournalName


table and the specification of the manual allocation is specified on the set up of
the number sequence in the NumberSequenceTable table:

FIGURE 4.9 NUMBER SEQUENCES FORM

Step by Step
To import ledger transactions into general journal, follow these steps.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_04_02_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

1. Import the file AX2012_ENUS_DEVIV_04_02_LAB.xpo that


contains the AXABaseImport and the
AXALedgerImportTransactions classes. Do not be concerned about
the dialog or reading of the file. This is already implemented so that
you can stay focused on the General ledger module.
2. Change the AXALedgerImportTransactions class.
a. Override the preImport() method to create a journal header in the
LedgerJournalTable table by using the AxBC interface
AxLedgerJournalTable. Use the following code sample to guide
you.

4-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

protected void preImport()


{
super();

axLedgerJournalTable = AxLedgerJournalTable::construct();
axLedgerJournalTable.parmJournalName(journalName);
axLedgerJournalTable.save();
}

b. Override the importRecord() method to create the individual


journal line in the LedgerJournalTrans table by using the AxBC
interface AxLedgerJournalTrans. Use the following code sample
to guide you.

void importRecord(container _c)


{
#Define.PosLedgerAccount(1)
#Define.PosTransactionDate(2)
#Define.PosVoucherNumber(3)
#Define.PosTransactionText(4)
#Define.PosCurrencyCode(5)
#Define.PosAmountCurrency(6)

AxLedgerJournalTrans axLedgerJournalTrans;
AmountCur amountCur;

;
axLedgerJournalTrans =
AxLedgerJournalTrans_CustPaymJour::newLedgerJournalTable(axLedgerJourn
alTable.ledgerJournalTable());

axLedgerJournalTrans.parmAccountType(LedgerJournalACType::Ledger);
axLedgerJournalTrans.parmLedgerDimension(
conpeek(_c,#PosLedgerAccount));
axLedgerJournalTrans.parmTransDate( conpeek(_c,#PosTransactionDate));
axLedgerJournalTrans.parmVoucher( conpeek(_c,#PosVoucherNumber));
axLedgerJournalTrans.parmTxt( conpeek(_c,#PosTransactionText));
axLedgerJournalTrans.parmCurrencyCode(
conpeek(_c,#PosCurrencyCode));

amountCur = conpeek(_c,#PosAmountCurrency);
if (amountCur > 0)
{
axLedgerJournalTrans.parmAmountCurDebit(amountCur);
}
else
{
axLedgerJournalTrans.parmAmountCurCredit(abs(amountCur));
}

4-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

axLedgerJournalTrans.save();
}

c. Override the postImport() method to post the journal after the


import, if the option is selected in the dialog box. Use the
following code sample to guide you.

protected void postImport()


{
LedgerJournalCheckPost ledgerJournalCheckPost;
;
if (postJournal == NoYes::Yes)
{
ledgerJournalCheckPost =
LedgerJournalCheckPost::newLedgerJournalTable(axLedgerJournalTable.ledge
rJournalTable(),NoYes::Yes);
ledgerJournalCheckPost.run();
}

super();
}

NOTE: The sample mentioned in the requirement section is available in the file
that is named AX2012_ENUS_DEVIV_04_02_SAMPLEFILE.txt.

TIP: You can import the AX2012_ENUS_DEVIV_04_02_LAB_SOL.xpo file to


verify and compare your solution.

Test
As described earlier, you need a journal related to a manual number sequence to
assign voucher numbers read from the file. This includes the following steps:

1. Create a number sequence by using the path Organization


administration > Common > Number sequences > Number
sequences. Mark the sequence as manual on the General FastTab.
2. Change the parameters in the ledger module by using the path
General ledger > Setup > General ledger parameters. Clear the
Check for continuous numbers check box.
3. Create a new journal name by using the path General ledger >
Setup > Journals > Journal names. Use the journal type Daily and
relate the journal name to the voucher series created in the first step.

4-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

4. Open the AXALedgerImportTransaction class. Then, specify the


location of the file
AX2012_ENUS_DEVIV_04_02_SAMPLEFILE.txt and the journal
name created in step 3.

After a successful import, you will find the journal created by using the path
General ledger > Journals > General journal.

You can repeat the test if you change the data file to use different voucher
numbers. Every time that the function is activated, a new journal is created.

NOTE: The Ledger dimension values provided in the sample file are record IDs.
In a more realistic import, additional code would be required to lookup the recID
for the dimension value combination that is entered by the user in the file.

4-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Budgeting Overview
You can use the Budgeting module to set up, create, and view budgets.
Budgeting can include budget control, used to monitor the budget funds that are
available for planned and actual purchases and expenditures. You can create
budget register entries for the original budget, budget transfers, and budget
revisions. You can also create budget register entries to manually reserve budget
funds for purchases and planned expenditures by using the encumbrance or pre-
encumbrance budget types. Budget register entries can be created automatically
when budgets are transferred to the general ledger from other modules such as
Project management and accounting or Fixed assets.

You can determine which financial dimensions from the chart of accounts will be
available for basic budgeting and budget control. When you configure budget
control, you define budget intervals, budget cycle time spans, budget thresholds,
budget managers, budget groups, and the calculation that is used to check for
available budget funds. The available budget funds can be verified when source
documents and accounting journals are entered. You can view the status and
history of budget register entries, budget control statistics, actual versus budget
amounts, budget details, and budget funds available.

FIGURE 4.10 BUDGETING BUSINESS PROCESS

One of most important management tools a company can use to make plans is to
compare planned performance to actual performance. Planning for the general
ledger is performed by creating budgets in the Budgeting module. A budget is a
set of expected ledger transactions. Although a budget can be as finely detailed as
actual transactions, budgets are more typically prepared at an aggregate level.

4-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Budgets are also used in balance sheet reports, where planned figures are
compared with actual values.

Basic Budgeting Set Up


You can use basic budgeting to define the financial dimensions for budgets,
create budget models, and set up and use budget register entries. You can also set
up optional Budgeting workflows to automate the review of budget register
entries, including budget transfers.

Before you use basic budgeting, complete the steps that are described in the
following topics. If you use budget control, you must set up basic budgeting
before you configure budget control.

• Required: Define budget exchange rates


• Required: Define budgeting parameters and number sequences
• Required: Define financial dimensions for Budgeting
• Required: Create budget models
• Required: Define budget codes
• Optional: Define budget transfer rules
• Optional: Set up budgeting workflows
• Optional: Set up budget allocation terms

Budget Control Set Up


Budget control is a method of ensuring that sufficient budget funds are available
for planned or actual purchases. After you set up basic budgeting, you can set up
budget control.

You can set up basic budgeting and budget control based on the ledger for a legal
entity. The ledger provides the chart of accounts, accounting and reporting
currencies, and fiscal calendar. You can determine which financial dimensions
from the chart of accounts will be available for budgeting and budget control.
Additionally, you can define the following.

• Budget intervals
• Budget cycle time spans
• Budget thresholds, budget managers
• Budget groups
• Calculation used to check for available budget funds

4-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The available budget funds can be verified when source documents and
accounting journals are entered. The following figure shows the data model for
the budget control configuration.

FIGURE 4.11 BUDGET CONTROL CONFIGURATION DATA MODEL

The following areas are integrated with budget control.

• General journals
• Allocation journals
• Project expense journals
• Fixed asset journals
• Accounts payable invoice journals
• Accounts payable invoice approval journals
• Accounts payable invoice registers
• Vendor invoices
• Purchase orders

4-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Purchase requisitions
• Travel requisitions
• Expense reports

NOTE: The Project management and accounting module also uses its own
budget control. It is only integrated with the Budgeting modules budget control
through the Project expense journal. For more information about Project
management and accounting budgeting functionality, refer to the Advanced
Projects in Microsoft Dynamics AX 2012 course.

Budget Amounts
After you have set up and configured basic budgeting you can begin to enter
budget amounts. If you plan to use budgeting workflows, create the workflows,
and then assign them to budget codes before you begin to make budget register
entries. Also, if you plan to use budget control, configure budget control before
you enter budget amounts.

The budget data is entered through the Budget register entry form that consists
of a header and lines. The header information is applied to the whole budget
register entry and the lines (account entries) are where budget amounts for
specific dimension combinations are entered.

4-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

The following figure shows the data model for budget register entries.

FIGURE 4.12 BUDGET REGISTER ENTRY DATA MODEL

When you have completed entering the budget register entries, you must update
the budget balances. This step is similar to posting a general journal and updates
the budget amounts based on the budget account entries.

The BudgetTransactionPost class is used to update the budget amounts from a


single budget register entry. The checkHeader(), checkLine(), and checkLines()
methods are used to validate the data that is entered. The run() method invokes
these checks and has additional logic to check for workflow status when
workflow is enabled for budgeting.

The call to the postToGeneralLedger() method is called after the validation is


completed. This method checks whether budget appropriations are enabled and if
they are then a new journal is created to post the amount directly into the general
ledger.

When the postToGeneralLedger() method completes, the status of the budget


register entries are updated to completed.

The BudgetTransactionMultiPost class is used to invoke several instances of the


BudgetTransactionPost class based on the selection criteria that is entered by the
user.

4-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The BudgetCalculateBalance class queries for budget and posted ledger amounts
by fiscal period and uses the information to create records in the
BudgetTmpBalance temporary table. This class supports the Actuals vs. Budget
inquiry & report and role center chart.

Budget Checking
When budget control is enabled for a specific source document, budget checks
are completed automatically when the record is saved. The check is based on
options specified in the budget control configuration except for the budget
register which always perform a check on line save.

You can also manually perform a budget check on a transaction. Budget checks
are processed by using the BudgetControlProcessor class. There are core
integrations to the Budget control framework through the following classes as
well:

• BudgetControlSourceDocumentProcessor
• BudgetControlBudgetTransactionProcessor
• BudgetControlAccountingJournalProcessor

These classes handle common patterns for formulating the budget control check
request for the BudgetControlProcessor based on the type of integrator.

The BudgetControlCheckRequest class is used to capture the information that is


required to check for available budget that relates an integrator to budgetary
control. When this class is constructed, the BudgetCheckDetail,
BedgetReturnDetails, and BudgetReleivingDetails classes (which all extend the
BudgetSourceDetail class) are used to capture the ledger dimension and the
currency amount details for the budget funds available check.

NOTE: A portion of the budget control checking logic occurs through stored
procedures on the SQL Server. The code for the SQL logic is contained in the
BudgetControlSQLObjects class and the T-SQL code is deployed to the SQL
Server at activation of the budget control configuration or first budget check.

When a budget check is completed and returns an error or warning, you can use
the Budget check errors or warnings form to view the details.

4-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Fixed Asset Overview


Fixed assets are items of value, such as buildings, vehicles, land, and equipment
owned by an individual or corporation, and used in operations. You can set up
and enter acquisition information for fixed asset records, and then manage fixed
assets by depreciating them and setting a capitalization threshold to determine
depreciation. You can calculate adjustments to the fixed assets, and also dispose
of them.

When you use the Fixed assets module, you can view the current value of all
fixed assets. The way in which fixed assets are handled must correspond to both
international accounting standards and the accounting legislation in each
country/region. Requirements might include rules for recording acquisition and
disposal transactions, depreciation, lifetimes, and write-ups and write-downs of
fixed assets. The fixed assets functionality incorporates many of these standards
and rules.

FIGURE 4.13 FIXED ASSET BUSINESS PROCESS

NOTE: The transfer of fixed assets to a low-value pool is an Australian feature


and is not a part of the core functionality.

You must enter transactions to track the acquisition, depreciation, and disposal of
fixed assets. Sometimes you must change the value of an asset. For example, the
value of land that your organization owns might increase, or you might have to
reflect the fair market price of a specific asset.

4-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Fixed Assets versus Current Assets


In a company's balance sheet, assets are divided into two groups—fixed assets
and current assets.

It is important to define the differences between fixed and current assets before
discussing how to account for each. The classification of assets is not based on
the physical nature of the asset, but instead on the purpose of the ownership of
the asset.

Current assets are those that a company depletes in the typical course of business
over the next year or business cycle, whichever is shorter. Examples of current
assets include cash, accounts receivable, prepaid expenses, or inventory.

Fixed assets are assets that a company owns and uses in the day-to-day
operations of the company and are not intended for resale to customers. The
useful lives of these assets spans multiple years. Examples of fixed assets include
automobiles, computers, machinery, buildings, copyrights or trademarks (a
special class of assets frequently called intangible assets).

Based on these definitions, the same asset can be classified as a fixed asset in one
company and as a current asset or inventory item in another. An example of a
company where the same asset can be classified as both fixed and current is an
automobile dealership. The vehicles held for sale are inventory items in addition
to current assets, whereas the manager's company car is a fixed asset.

Fixed Asset Module Overview


The Fixed assets module provides subledger detail that supports a controlling
account in the general ledger the same way the Accounts receivable and
Accounts payable modules provide subledger detail to support the associated
controlling accounts in the general ledger. This relationship between the
subledgers and the general ledger is achieved through setups where specifications
are provided for one or more ledger accounts.

In addition to supporting the general ledger, the Fixed assets module in


Microsoft Dynamics AX 2012 includes the following functionality.

• Provides detailed documentation for the company's assets.


• Simplifies the tracking of depreciation.
• Allows for write-ups or write-downs.
• Allows for the acquisition and disposal of assets.
• Allows the accounting of assets for tax preparation.

Because most fixed assets represent a significant investment for companies, the
ability to track and keep sound financial records on fixed assets is important.

4-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Fixed Asset Integration


At a minimum, the Fixed asset module is integrated to the general ledger. All
asset transactions posted in the Fixed asset module must also update the asset
values in the company's chart of accounts.

This integration to the general ledger represents the minimum functionality that
the Fixed assets module must provide. Microsoft Dynamics AX 2012 provides
many additional features including the following.

• Accounts receivable integration


• Accounts payable integration
• Budgeting
• Inventory journal integration
• Purchase order integration
• Project accounting integration
• Country- or region-specific functionality for many countries and
regions

Fixed Asset Setup


Many options are available in the setup of the Fixed asset module. The basic
setup that is required represents a small part of all available options. Most setup
options are used when advanced or country and region-specific features are
needed.

Most of the basic setup steps are accessed by opening Fixed assets, and then
clicking Setup. The standard steps are as follows.

• Depreciation profiles
• Depreciation books
• Value models
• Fixed asset groups
• Posting profiles
• Parameters

Fiscal calendars must also be set up in the General ledger module.

4-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Fixed Asset Data Model


The following figure shows the data model for fixed assets.

FIGURE 4.14 FIXED ASSETS DATA MODEL

The AssetTable is the primary table for storing fixed assets. Each asset has one
record in this table. Each fixed asset is assigned to a fixed asset group. The fixed
asset groups are used to help simplify the setup of assets, for reporting and
inquiries, and to serve as a template with default information for setting up an
asset. The fixed asset groups and default data are stored in the AssetGroup table.

Each asset can have several value models that are stored in the AssetBook. The
default information for value models is stored in the AssetBookTable.
Additionally, each asset can have several depreciation books. Each depreciation
book for an asset is stored in the AssetDepBook table. The default information
for a depreciation book is stored in the AssetDepBookTable. Depreciation books
do not post to the general ledger like value models, so there is no accounting
related to them. The depreciation books are used to calculate various values of
the assets based on the depreciation profile selected for reporting purposes.

4-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Each value model and depreciation book is related to a depreciation profile.


Depreciation profiles are used to define rules for calculating depreciation.
Creating profiles is required for depreciable assets. This usually refers to tangible
assets, but intangible assets can also use depreciation profiles. This information is
stored in the AssetDepreciationProfile table.

Fixed assets transactions are posted by using a journal. This process is similar to
the general journal. The data model and classes used for posting fixed assets are
similar.

Summary
This chapter introduced currencies and exchange rates. Microsoft Dynamics AX
2012 supports multiple currencies and making conversions between currencies.
The CurrencyExchangeHelper and ExchangeRateHelper classes can be used to
make currency conversions.

Additionally, the chapter introduced the chart of accounts. The chart of accounts
consists of main accounts and financial dimensions. The main accounts and
dimensions are then constrained by the account structures and advanced rules in
use by the chart of accounts. You can define two types of financial dimensions—
system-defined and custom lists. Financial dimensions and main accounts can
also be combined to create dimension sets that are used to group and report on
specific combinations of dimensions.

Journals and transactions comprise the details of the general ledger. Journals are
used to make manual adjustments and are posted by using the journal framework
and the LedgerJournalCheckPost class. Other transactions such as sales order
invoices or expense reports are posted by using automatic journals with the
LedgerVoucher class hierarchy.

You can use the Budgeting module to create budget amounts for a specified
combination of the main account and financial dimensions. However, the main
account is not required for budgeting. You can use budget control checking to
enable a budget check on certain source documents. With this check you can
warn a user or prevent a user from posting a transaction that exceeds specified
budget thresholds.

The Fixed asset module is also used to create and track information related to
your companies fixed assets. You can keep multiple sets of books for each asset,
and use the fixed asset journal to acquire, depreciate, or adjust assets.

4-49
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Which of the following tables are used for a new budget register entry?
(Select all that apply)
( ) BudgetTransactionHeader
( ) BudgetTransactionLine
( ) LedgerBudgetHeader
( ) LedgerBudgetLine

2. Which class holds a list of transactions that are going to be posted for a
particular voucher?
( ) LedgerVoucher
( ) LedgerVoucherObject
( ) LedgerVoucherObjectTrans
( ) LedgerVoucherTransObject

3. Name the two types of financial dimensions in Microsoft Dynamics AX 2012


and describe what each type is used for.

4. Which class is used to post a general journal?


( ) LedgerJournalPost
( ) LedgerJournalCheckPost
( ) LedgerVoucher
( ) LedgerVoucherPost

5. Which table is the primary table used for storing fixed asset information?
( ) AssetBook
( ) AssetTable
( ) AssetTrans
( ) AssetGroup

4-50
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

6. Which of the following tables are part of the ledger journal data model?
(Select all that apply)
( ) LedgerJournalName
( ) LedgerJournalTable
( ) LedgerJournalLines
( ) LedgerJournalTrans

7. Which of the following are valid field names to be used in a view for a new
system-defined dimension? (Select all that apply)
( ) Key
( ) Group
( ) Value
( ) Name

4-51
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

4-52
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 4: Use and Design of the Ledger Module

Solutions
Test Your Knowledge
1. Which of the following tables are used for a new budget register entry?
(Select all that apply)
(√) BudgetTransactionHeader
(√) BudgetTransactionLine
( ) LedgerBudgetHeader
( ) LedgerBudgetLine

2. Which class holds a list of transactions that are going to be posted for a
particular voucher?
( ) LedgerVoucher
(•) LedgerVoucherObject
( ) LedgerVoucherObjectTrans
( ) LedgerVoucherTransObject

3. Name the two types of financial dimensions in Microsoft Dynamics AX 2012


and describe what each type is used for.

MODEL ANSWER:

System-defined: Select a system-defined entity to base the financial


dimension on. Financial dimension values will be created from this selection.
For example, to create dimension values for projects, select Projects. A
dimension value will be created for each project name.

User-defined: To create a user-defined financial dimension, select < Custom


dimension >

4. Which class is used to post a general journal?


( ) LedgerJournalPost
(•) LedgerJournalCheckPost
( ) LedgerVoucher
( ) LedgerVoucherPost

5. Which table is the primary table used for storing fixed asset information?
( ) AssetBook
(•) AssetTable
( ) AssetTrans
( ) AssetGroup

4-53
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. Which of the following tables are part of the ledger journal data model?
(Select all that apply)
(√) LedgerJournalName
(√) LedgerJournalTable
( ) LedgerJournalLines
(√) LedgerJournalTrans

7. Which of the following are valid field names to be used in a view for a new
system-defined dimension? (Select all that apply)
(√) Key
( ) Group
(√) Value
(√) Name

4-54
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

CHAPTER 5: USE AND DESIGN OF THE PRODUCT


INFORMATION MANAGEMENT MODULE
Objectives
The objectives are:

• Describe how products are set up, released, and finalized.


• Describe how inventory dimensions and groups are used to manage
product information.
• Review the data model for inventory dimensions.

Introduction
A product is an item, service, or right that results from an economic activity. In
Microsoft Dynamics® AX 2012, all product data is shared across all companies,
and the virtual table collection concept is no longer available for product data .
The item representation (InventTable) used in earlier versions still exists, and this
table can still be included in a table collection. However, it now has a foreign key
to the shared product instance (EcoResProduct hierarchy), and it represents the
released product concept or a given enterprise product that is now authorized for
use inside a legal entity.

This chapter highlights the new patterns used to represent item-product master
data. This document does not describe all new functionality within the item-
product data management feature. Instead, this document focuses on the
development patterns and how they are implemented. A complete list of new
tables and their replacements can be found in the Implementing the Item-Product
Data Management Framework for Microsoft Dynamics AX 2012 white paper at
https://go.microsoft.com/fwlink/?LinkId=246121.

5-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Products
Product information management in Microsoft Dynamics AX 2012 targets the
creation and maintenance of an Enterprise Products Repository. It supports larger
organizations in a centralized structured approach in creating and maintaining
core master data such as product definitions. Smaller organizations that require a
more decentralized approach can, with some restrictions, create and maintain
their products while they are automatically added to the shared products
repository.

Product Maintenance
Product definitions are created independently of a legal entity, and core values
such as product number, type, and name are shared values.

Some core values can be overridden by a legal entity, an example is the search
name. Other values are kept as key definition attributes and they cannot be
changed other than on the actual product definition.

From a decentralized process, you can create and maintain products directly from
the Released products list page in the Product information management
module. A product definition is created by the system when a product is created
directly from the Released products list page.

Product Types and Subtypes


Two core types of products can be defined manually in Microsoft Dynamics AX
2012.

• Products
o These are clearly identifiable products that do not have
variations associated with them. You can think of them as
standard or base products.
o Use the Products list page in the Product information
management module to view and manage products.

• Product masters
o These serve as templates or models for variants. The variants of
a product master can be predefined or created in sales scenarios
by using a product configurator. A product master is associated
with one or more product dimensions or for some configurations
or product attributes.
o Use the Product masters list page in the Product Information
Management module to view and manage product masters.

5-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

To view all products and product masters use the All products and product
masters list page by using the following path:

Product information management > Common > Products > All products and
product masters

FIGURE 5.1 ALL PRODUCTS LIST PAGE

As in Microsoft Dynamics AX 2009, the product type classifies if a product is


tangible or intangible (an item or a service). In Microsoft Dynamics AX 2012,
this difference is made as a sub classification of the product.

There are three subtypes of products—product master, distinct product, and


product variant. Product variants will be variants of product masters.

This concept is designed as a super-type/subtype table hierarchy to decouple


specific properties between different entities that are of the same nature.
A product master is associated to the EcoResProductDimensionGroup and can
have a range of predefined product dimensions available. For example, a t-shirt
could be a product master with various sizes (small, medium, large) and colors
(blue, green). The product variant represents variations of the product master.

By contrast, a distinct product cannot have variations (meaning it cannot have


any product dimensions specified).

5-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Product Creation Process


To create a new product, follow this four-step process:

1. Create and define the product.


2. Release the product to legal entities.
3. Define legal entity specific data.
4. Use the product.

When you create a new product definition the type and subtype are the key
attributes to enter—they determine the additional functions and required setup.

The product type classifies if a product is tangible or intangible (item or service),


whereas the sub-type introduced in Microsoft Dynamics AX 2012 is a sub-
classification of the product.

The following figure lists all shared product definition attributes.

FIGURE 5.2 SHARED PRODUCT DEFINITION ATTRIBUTES

5-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Product Patterns
This pattern applies to the following tables.

• EcoResProduct
• EcoResProductMaster
• EcoResDistinctProductVariant
• EcoResDistinctProduct

All products are stored as system master data, and are used by organizations to
create and maintain shared product definition data.

The "product master" concept includes the product definition, and can have
variants in product dimensions (color, size, and configuration).

The "product variant" concept includes a product that has several of the
associated product dimension values (color, size, and configuration). It replaces
the previous "item combination" concept. Be aware that a product variant has all
the attributes and functionality of any other type of product.

The "distinct product" concept includes a product that does not vary in product
dimensions and therefore cannot have a product dimension group associated to it.

The products in a system can be released to a legal entity to become available for
various processes (sales, purchase, and production). The same shared product
variants can be available for production in one company, but not available for the
production in another legal entity.

5-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Product dimension values such as colors, sizes, and configuration are stored in
the system tables (EcoResColor, EcoResConfiguration, and EcoResSize) and are
immutable. The InventDim product dimensions values point to the
EcoResColor.Name, EcoResConfiguration.Name, and EcoResSize.Name
fields.

FIGURE 5.3 PRODUCT DATA MODEL

Releasing Products
The product release process is designed to enable users in an enterprise to move
or copy product definitions to various organizational units. By releasing a
product or a product master you associate it with a legal entity and authorize the
product definition for use in the legal entity.

5-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Before you can use a product master on a transaction, such as a sales order or
purchase order, both the product master and one or more of its variants must be
released to each legal entity, if the configuration technology is set to be
predefined variants. When products are released, many combinations of products,
product masters, product variants, and legal entities can be released such as the
following:

• Single products or multiple products.


• Single product variants or multiple product variants.
• Single legal entity or multiple legal entities.

You can release products from the following locations.

• Product information management > Common > Product > All


products and product masters list page, and then click Release
products.
• Product information management > Common > Product >
Product master list page, and then click Release products.
• Product information management > Common > Product >
Product list page, and then click Release products.

5-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• From the Product details form click Release products. The


Product details form is opened by double-clicking a product in any
of the Product information management list pages.

FIGURE 5.4 RELEASE PRODUCTS FORM

Finalizing Product Set Up


After you release a product to a legal entity, you must finalize it before the
product can be on a transaction, such as a sales order or purchase order.

You must finalize a product in each legal entity where you have released it. In
Microsoft Dynamics AX there are four fields that must be set up on the Released
product form (open Product information management > Common >
Released products) before you can use the product on a transaction. You can
manually enter, or use a template to enter the following fields.

• Item model group


• Item group
• Storage dimension group (only if it is not specified on the product
definition)
• Tracking dimension group (only if it is not specified on the product
definition)

To make sure these four mentioned fields are set up, you can run a validation
check on the product in the respective legal entity. When you click Validate in
the Maintain group of the Action Pane, the system will check for the attributes
and produce a warning if no value exists.

5-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Additional Item Setup


When you have finished creating a product there are many additional details that
can be completed for each product.

• Warehouse items: Warehouse items are used to define information


about items and the related warehouse and counting settings. The
settings can be made specific based on the items configuration and
vary from warehouse to warehouse. Warehouse items are stored in
the InventItemLocation table.
• Default order and Site specific order settings: The default and site
specific order settings are used by master planning to generate sales
orders, purchase orders, and inventory orders. The settings are stored
in the InvetItemPurchSetup, InvnetItemSalesSetup, and
InvetItemInventSetup tables. The InventItemSetupSupplyType table
is used to store the default order type. The main settings involve the
following areas:
o Defining a warehouse to use for each module when orders are
created.
o Defining the settings that modify order quantities for each
module when orders are created.
o Defining the type of planned order to be created when master
planning is run.

• Product images: Each item can have multiple images linked to it.
The images are stored in the document handling system by using the
DocuRef table.
• Barcodes: You can define barcodes for each item. The
InventItemBarcode table contains information about the bar codes
that are used for items.
• GTIN: You can define Global Trade Item Numbers (GTIN) for each
item. GTIN is a 14-digit data structure used to uniquely identify
trade products. The InventItemGTIN table contains information
about items and their related GTINs.

Additional Functionality
The following sections describe additional functionality that is available to help
further classify and define the product information.

Category Hierarchies and Categories

You can use category hierarchies to classify products for reporting and analysis
purposes. Each category hierarchy consists of a structure of subcategories. An
organization can create more than one category hierarchy. For example, your
organization might create one category hierarchy for classifying purchased
products and another hierarchy for classifying vendors.

5-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Product Attributes

You can use product attributes to identify the details that you want to maintain
for your products such as, Stock Keeping Unit (SKU) number, product version,
and so on. Product attributes also provide additional details that your
organization might want to record for a particular product or category. You can
associate product attributes together with a product through the category that the
product belongs to. When you add a category and its associated products to your
procurement catalog, the attributes assigned to the procurement category are
imported into the catalog and can display on the procurement site.

When you define product attributes, you must first define the attribute type and
then assign the attribute type to the attribute. The attribute type identifies the type
of data that can be entered for a specific attribute and a list or range of valid
values that can be used for the attribute. The attribute is the value that is
displayed with the product to provide the requester additional details about the
product.

Product Translation

When you use the Text translation form, you can create product translations by
entering descriptions and product names for multiple languages. However, the
product name and description are optional, only the product number is required.
The product translations are mainly used for output on external documents, and
the data values will always be shown in the system language, for example, when
you open and view the product related list pages and forms.

On external documents the product name will be displayed according to the


company language or the preferred language by the customer or vendor.

To open the Text translation form click the Translations button in the Action
Pane of All products and product masters forms or list pages.

Product Translations Pattern

This pattern applies to the EcoResProductTranslation table.

In Microsoft Dynamics AX 2012, users can define multilanguage translations for


shared product definitions. Out-of-the box, the product localization attributes are
the product name and the product description. The Product search name is used
to control shared and legal-entity–specific values to the product "alias"
functionality. By default, the product has its name and translation in the system
language (enterprise organizational language).

5-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

The pattern that is applied to model product localization is consistent across the
application to model localization support for shared entities. The general system
translation forms are used to manage product translation. This enables a
consistent user experience in the way that the user interacts with the various
entities in the system for multilanguage translation (product, attributes, catalog
descriptions, and so on).

FIGURE 5.5 PRODUCT TRANSLATIONS DATA MODEL

Product and Item Identification Pattern


This pattern applies to the following:

• ProductNumber
• ItemId
• EcoResProductIdentification
• EcoResProduct.DisplayProductName
• InventTable.ItemId

5-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

In Microsoft Dynamics AX 2012, a product is identified by a unique shared


product number value, which is a natural key of the product entity. Not all types
of products can have a unique product number. The product variants do not have
their own shared product number because they are always identified by the
relation to their product master.

The DisplayProductNumber attribute helps identify product variants quickly and


uniquely in the application user interface.

Internally, all products have their own system-unique surrogate key that should
always be used to model the relationship to the product.

5-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

The InventTable still has an ItemId value that by default will be equal to the
corresponding product shared number value. However, in certain cases, you can
have an itemId value that differs from its product number value. With this option
you can have different identification strategies for the same product instance in
different legal entities.

FIGURE 5.6 PRODUCT AND ITEM IDENTIFICATION DATA MODEL

Inventory Dimensions
There is a clear difference between product attributes and product dimensions.
You can use product dimensions to track their values in all major processes such
as for cost, inventory, and analysis purposes.

Product attributes are only associated with products and product masters, and
product dimensions can only be used together with product masters (except for
masters that are configured by using the option constraint-based configuration).
This is because they consist of the uniqueness of a product master’s variations.

5-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

You can determine which product dimensions are mandatory for a given product
master by selecting the appropriate product dimension group when you create the
product master.

The product dimension group is set up from Product information management


> Setup > Dimension groups > Product dimension groups.

Microsoft Dynamics AX 2012 offers three product dimensions that include size,
color, and configuration.

Inventory Dimension Groups


In Microsoft Dynamics AX 2012 inventory dimensions are divided into the
following three categories:

• Product dimensions. These correspond to the size, color, and


configuration.
• Storage dimensions. These are site, warehouse, location, and pallet.
• Tracking dimensions. These are batch number and serial number.

The product dimension group can be assigned only when the product is being
created. The storage and tracking dimensions groups can be assigned to the
product on two levels—system level, where they are used in all legal entities
where the product is released, and the legal-entity level, where they are used only
for the product that is in that specific legal entity.

5-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

The following diagram shows the physical data model.

FIGURE 5.7 DIMENSION GROUPS DATA MODEL

The InventDimSearch class used in Microsoft Dynamics AX 2009 is no longer


available. In Microsoft Dynamics AX 2012, this class is replaced with several
new classes that are used to retrieve information about the inventory dimension
setup.

To determine if a dimension for a specific field is active you can use the
following code sample.

InventTable inventTable;
InventDimGroupSetup inventDimGroupSetup;
InventDimGroupFieldSetup inventDimGroupFieldSetup;
inventDimGroupSetup =
InventDimGroupSetup::newInventTable(inventTable);
inventDimGroupFieldSetup =
inventDimGroupSetup.getFieldSetup(fieldNum(InventDim,WMSPal
letId));
if (inventDimGroupFieldSetup.isActive())
{
info(strFmt("The palletId dimension is active for
dimension group
%1",inventDimGroupSetup.getStorageDimensionGroup()));
}

5-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Configuration Technologies
You can use the product setup to model configurable products. When you work
with product masters it is important to define how the variations of a master are
created. Frequently, many mandatory attributes must be specified to create a new
variation.

How a variant is constructed is controlled by the configuration technology that is


set up on the product master.

Configuration Definition
technology
Predefined variant With this type the product can be modeled based
on the product dimensions, color, configuration,
and size. This is the only option that can be set up
directly with product variants. Any combination
of the product dimensions is allowed.
Dimension-based A configuration technology that is used to create
configuration product variants by selecting values for product
dimensions. Any combination of the product
dimensions is permitted. The advantage of the
dimension configuration is that only one product
is required for a bill of material.
Constraint-based With this type the product can be used in the
configuration Product Configurator. To select this type, the
product dimension group must have a
configuration selected, and no other product
dimensions can be enabled. The constrain-based
configuration used the attributes described earlier.

NOTE: Rule-based configuration is used for items that implement the Product
builder functionality. This option is only available for customers who are
upgrading from an earlier version. This option will be removed in future
releases. Therefore it is recommended that you move to the Constraint-based
configuration option.

Product Variant Creation Process


To create a new product variant, follow this six-step process.

1. Create and define the product master.


2. Create the product dimensions (sizes, colors, or configurations).
3. Create the product variants (valid combinations of product
dimensions).
4. Release the product variants to legal entities.
5. Define legal entity specific data.
6. Use the product.

5-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Variant Configuration Technology Pattern


This pattern applies to the EcoResVariantConfigurationTechnology table.

In Microsoft Dynamics AX 2012, the product master contains a mandatory


policy that identifies the structure of its variant creation. This shared policy is
called "variant configuration technology." This setup identifies the only possible
feature that can be used to create related product variants. The Microsoft
Dynamics AX 2009 code base is adjusted and modified to follow the product
master setup so that any modification in this area should also be adjusted.

Product Dimension Values Pattern


This pattern applies to the following:

• EcoResProductMasterDimValue and
EcoResProductVariantDimValue hierarchies
• InventDim

Product dimensions are shared and are attribute-based. Three predefined


attributes exist, representing color, size, and configuration dimensions. These
attributes are related to the product dimensions and are distinctively different
than the EcoRes* attributes framework in Microsoft Dynamics AX 2012.

The product dimension values are stored in a shared, immutable table


(EcoResColor, EcoResSize, and EcoResConfiguration). The database schema
around product dimensions allows adding new attributes, which can be used to
represent new product dimensions. For example, you could have T-shirt sizes (S,
M, L) and shoe sizes (8, 10, 12).

The product master holds relations to all possible product dimensions values
within one product attribute. The product variant holds one—and only one—
relation to the product dimensions value within one product attribute. The
InventDim structure holds the relationships to the shared product dimension
values.

5-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The system allows lookup only of legal-entity–specific product dimensions on


the order line and always validates them against release product variants for the
current legal entity. On the shared level (product management forms, tables, and
so on), the system allows lookup of all product dimensions and validates them
again all product variants.

FIGURE 5.8 PRODUCT DIMENSION VALUES DATA MODEL

Released Product and Released Product Variant Pattern


This pattern applies to the following tables.

• InventTable
• InventDimCombination

Products and product variants must be released to a specific legal entity before
they can be used with that legal entity. The InventTable and its associated tables
use the concept of the released product and can also be treated as the instance of
the particular product in the current company. The mandatory product foreign
key is added to the InventTable. The InventTable represents the instance of either
a product master or a distinct product.

5-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

The InventDimCombination table and its associated tables use the concept of the
released product variant and can also be treated as the instance of a product
variant in the current company. The mandatory DistinctProductVariant foreign
key is added to the InventDimCombination table. The InventDimCombination
always represents the instance of a product variant.

Managing Inventory Policies


Item model groups are an important part of configuring product for stock,
inventory management and accounting. Item model groups contain settings that
determine how items are controlled and handled upon item receipt and issue.

Item model groups determine the following stock and inventory policy:

• Whether the product is stocked or not stocked.


• The cost flow assumption and cost measurement method for valuing
inventory of stocked products.
• If physical and financial negative inventory is permitted.
• If inventory transactions should be posted to the General Ledger.
• The workflow that is used when you send or receive items.
• The reservation rules.

5-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

An item model group setup is important when you determine how the item will
integrate with other areas of the Microsoft Dynamics AX 2012 system. You can
view the item model groups by opening Inventory and warehouse
management > Setup > Inventory > Item model groups.

FIGURE 5.9 ITEM MODEL GROUPS FORM

If an item model group is set up for a not stocked product, many of the
parameters are irrelevant. The following table displays the parameters that are
relevant to a product that are maintained in stock versus products that are not
maintained in stock.

Check box Stocked Not Stocked


Physical negative inventory Relevant Irrelevant
Financial negative inventory Relevant Relevant
Quarantine management Relevant Irrelevant
Consolidated picking Relevant Irrelevant
method
Post physical inventory Relevant Irrelevant
Post financial inventory Relevant Irrelevant
Post to Deferred Revenue Relevant Relevant
Account on Sales Delivery

5-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Check box Stocked Not Stocked


Accrue liability on product Relevant Relevant.
receipt NOTE: Check box is
selected. when Post
physical inventory is
Selected.
Registration requirements Relevant Irrelevant
Receiving requirements Relevant Relevant
Picking requirements Relevant Irrelevant
Deduction requirements Relevant Relevant
Date-controlled Relevant Irrelevant
Backward from ship date Relevant Irrelevant

When a product is defined as not stocked, there are several differences in how
transactions are handled, and certain types of transactions are restricted. For
example, when a not stocked product is added to a purchase order, the system
will not track the on hand quantity or create an inventory transaction
(inventTrans table record). You can process this purchase order in the same
manner as the purchase order with stocked product.

The following figure shows the data model for item groups and item model
groups.

FIGURE 5.10 ITEM GROUP AND ITEM MODEL GROUP DATA MODEL

5-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 5.1 - Product Information Management Workshop


This lab will demonstrate how to perform the following tasks:

• Add a new field to the product.


• Synchronize the new field with released products.
• Update the validation to make the field required.

Estimated time to complete: 20 minutes

Scenario

Isaac, the Business Systems Applications developer, received a request to add a


new field to the products that will track the manufacturer's suggested retail price
(MSRP). The requirements specify that the field must be added to the All
products and product masters details form. The new field must also be copied
to the released products and users should be able to override this field for each
legal entity. However, the field is required and validation must be added to make
sure that a value is entered.

Challenge Yourself!
By using the provided information, add a new field to the product that is copied
to the released product. Make sure that the field can be edited and that it is
required by adding logic into the Validate button on the Released products
form.

Need a Little Help?

1. Create a new project.


2. Create a new extended data type for the MSRP.
3. Add a new field to the EcoResProduct table.
4. Add the new field into a new field group.
5. Add the new field group to the All products and product masters
detail form.
6. Add a new field to the InventTable table.
7. Add the new field into a new field group.
8. Add logic to the initFromEcoResProuct method to copy the value
entered in the EcoResProduct table to the InventTable.
9. Add the new field group to the Released products form.
10. Test that the new field exists on both forms and that it is copied to
the released product.
11. Add logic to the validateProducts method so that the Validate button
on the Released products form requires the new field.

5-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Step by Step: Add the MSRP Field


Follow these steps to create a new project.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as
ProductInformationManagementWorkshop.
6. Double-click the project to open it, and then close the Projects
window.

Follow these steps to add the MSRP

1. In the AOT window expand the Data Dictionary node.


2. Right-click the Extended Data Types node and select New > Real.
3. In the Properties window, set the following values on the new real.
a. Name = MSRP
b. Label = MSRP
c. Help text = Manufacturer's suggested retail price for the product.
d. Extends = Price

4. Save the extended data type.


5. Drag the newly created MSRP extended data type into the project
that you created in step 3.

Follow these steps to add the MSRP field to the EcoResProduct table and the
EcoResProductDetails form.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the EcoResProduct table.
2. Drag the table into the project that you created in step 3.
3. Expand the EcoResProduct table.
4. Select the MSRP extended data type and drag it to the Fields node of
the EcoResProduct table.
5. Save the table.
6. Right-click the Field groups node and then click New Group.
7. Set the following values in the Properties window.
a. Name = MSRP
b. Label = MSRP

8. Select the MSRP field from the Fields node on the EcoResProduct
table, and then drag it into the MSRP Field group.

5-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

9. Save the table. If the Synchronize table window opens, click


Continue.
10. In the AOT window, expand Forms and then locate the
EcoResProductDetails form.
11. Drag the EcoResProductDetails form into the project that you
created in step 3.
12. Save the project.
13. Right-click the EcoResProductDetails form and then click Restore.
14. In the Data Sources node of the form browse to EcoResProduct >
Fields and then select the MSRP field group (folder) from the list.
15. Drag the MSRP field group into the bottom of the GeneralIFT
tabpage under the Design node of the form. (To locate the
GeneralIFT tabpage, browse to Designs >Design > Tab:Tab >
TabPage:Details > Group:GroupDetails > Tab:General >
TabPage:GeneralIFT in the EcoResProductDetails form.)
16. Right-click on the EcoResProductDetails form and then click
Open.
17. Verify that the new MSRP field is available.

FIGURE 5.11 PRODUCT DETAILS FORM WITH THE MSRP FIELD

18. Close the Product details form, and go back to the Development
workspace.

Follow these steps to add the MSRP field to the InventTable and the
EcoResProductDetailsExtended form.

1. In the AOT, locate the InventTable under the Tables node of the
Data Dictionary.
2. Drag the InventTable into the project that you created earlier.

5-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

3. Expand the InventTable table.


4. Select the MSRP extended data type and drag it to the Fields node of
the InventTable table.
5. Save the table.
6. Right-click the Field Groups node and then click New Group.
7. Set the following values in the Properties window.
a. Name = MSRP
b. Label = MSRP

8. Select the MSRP field from the Fields node of the InventTable and
then drag it into the MSRP Field Group node.
9. In the AOT window, expand Forms and then locate the
EcoResProductDetailsExtended form.
10. Drag the EcoResProductDetailsExtended form into the project that
you created earlier.
11. Save the project.
12. Right-click the EcoResProductDetailsExtended form and then
click Restore.
13. In the Data Sources node of the form browse to InventTable >
Fields and then select the MSRP field group (folder) from the list.
14. Drag the MSRP field group into the bottom of the TabPageSales
tabpage under the Design node of the form. (To locate the
TabPageSales tabpage, browse to Designs >Design > Tab:Tab >
TabPage:Details > Tab:TabHeader > TabPage:TabPageSales in
the EcoResProductDetailsExtended form.)

5-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

15. Right-click on the EcoResProductDetailsExtended form and then


click Open.
16. Verify that the new MSRP field is available.

FIGURE 5.12 RELEASED PRODUCT DETAILS FORM WITH THE


MSRP FIELD

17. Close the Released product details form and go back to the
Development workspace.

Step by Step: Copy the MSRP Field from the


EcoResProduct Table to the InventTable
Follow these steps to copy the value in the MSRP field from the EcoResProduct
table to the InventTable when a product is released.

1. In the Project window, locate the InventTable.


2. Expand the Methods node of the InventTable table and locate the
initFromEcoResProduct method.
3. Right-click the initFromEcoResProduct method and then click
View Code.
4. Assign the MSRP product value to the MSRP field on the
inventTable by adding the following code before the if statement.
"this.MSRP = _ecoResProduct.MSRP;"
5. Save and compile the InventTable table.

5-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Step by Step: Test the MSRP Field


To test the solution and verify that the MSRP field is copied from the product to
the released product, follow these steps.

1. Open Product information management > Common > Products >


All products and product masters.
2. Create a new product by clicking Product in the New group of the
Action Pane.
3. Enter a unique number for the product, and then click OK.
4. Click Edit on the Maintain group of the Action Pane.
5. Enter an amount in the MSRP field.
6. Click Release products.
7. Click the Companies tab.
8. Select CEU, and then click OK.
9. Close the form.
10. Open Product information management > Common > Products >
Released products.
11. Select the product that you released in step 8.
12. Click Edit in the Maintain group of the Action Pane.
13. Verify that the MSRP field is populated with the amount that you
entered for the product in step 5.
14. Close the form.

Step by Step: Add Validation to the MSRP Field


To add logic to check for the MSRP field to be populated when you click the
Validate button on the Released products form, follow these steps.

1. Open the Development Workspace.


2. In the AOT window, expand Classes and then locate the
EcoResProductValidationService class.
3. Drag the class into the project that you created earlier.
4. Expand the class and right-click the validateProducts method and
then click View Code.
5. Declare a new boolean variable called MSRPSet (boolean MSRPSet
= false;)
6. Add the following code to check for the MSRP field value to be
greater than zero after line 62 in the method.

MSRPSet = (InventTable::find(itemId).MSRP > 0) ? true :


false;

After line 64 add the following code.

if (!MSRPSet)

5-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

fieldList.addEnd("MSRP");

7. Save and compile the class.


8. Save the project.
9. To test the new logic, open the Released products form (Product
information management > Common > Products > Release
products.)
10. Select a product where the MSRP is set to 0.00.
11. Click the Validate button.
12. Verify that a you have received a warning message that states the
MSRP field must be specified.
13. Close all the windows.

TIP: You can compare your solution to the


AX2012_ENUS_DEVIV_05_01_LAB_SOL.xpo file provided with the training
image by importing the XPO file and then comparing the objects.

5-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Summary
The Product information management module provides functionality to set up
and maintain the details of products across legal entities and to set up legal entity
specific data for released products.

The module also includes functionality that will categorize products, create and
store custom product attribute details for each product, and support the entry of
translations for many fields on the product details.

Dimension groups can be used to determine which inventory dimensions should


be used for a product. They include the following:

• Product dimensions that includes size, color, and configuration.


• Storage dimensions that includes site, warehouse, locations, and
pallets.
• Tracking dimensions that include batch and serial numbers.

NOTE: More information about the item-product data model, upgrade for
earlier releases, and coding patterns can be found in the Implementing Item-
Product Data Management Framework for Microsoft Dynamics AX 2012 white
paper at https://go.microsoft.com/fwlink/?LinkId=246121.

5-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. TRUE or FALSE? All products are stored as system master data, which
allows organizations to create and maintain shared product definition data.
( ) True
( ) False

2. Which of the following fields must be populated to validate a product that


will be used on a transaction such as a sales order? (Select all that apply)
( ) Item group
( ) Item model group
( ) Product description
( ) Storage dimension group

3. Match the descriptions with the correct item.

_____ 1. Includes the product definition, which can a. Product


have variants in product dimensions (color, size, and Translations
configuration). b. Product Master
_____ 2. Includes a product that has several c. Product Variant
associated product dimension values (color, size, and
d. Distinct
configuration).
Product
_____ 3. Includes a product that does not vary in
product dimensions and therefore cannot have a
product dimension group associated to it.
_____ 4. Used for entering descriptions and product
names for multiple languages.

5-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 5: Use and Design of the Product Information Management
Module

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

5-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Solutions
Test Your Knowledge
1. TRUE or FALSE? All products are stored as system master data, which
allows organizations to create and maintain shared product definition data.
(•) True
( ) False

2. Which of the following fields must be populated to validate a product that


will be used on a transaction such as a sales order? (Select all that apply)
(√) Item group
(√) Item model group
( ) Product description
(√) Storage dimension group

3. Match the descriptions with the correct item.

b 1. Includes the product definition, which can a. Product


have variants in product dimensions (color, size, and Translations
configuration). b. Product Master
c 2. Includes a product that has several associated c. Product Variant
product dimension values (color, size, and
d. Distinct
configuration).
Product
d 3. Includes a product that does not vary in
product dimensions and therefore cannot have a
product dimension group associated to it.
a 4. Used for entering descriptions and product
names for multiple languages.

5-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

CHAPTER 6: USE AND DESIGN OF THE


INVENTORY AND WAREHOUSE MANAGEMENT
MODULE
Objectives
The objectives are:

• Describe how reservations and marking are used in the system.


• Review the inventory transactions and on hand inquiries.
• Describe the data model for inventory transactions and on hand
inventory.
• Review the structure of the InventOnHand Class.
• Explain how inventory journals are used.
• Discuss the inventory journals data model and the structure of the
InventJournalCheckPost classes.
• Describe how quarantine management and quality management are
used in the system.
• Explain inventory blocking.
• Describe other functionality that is available in the Inventory and
warehouse management module.

Introduction
The following sections explain the functionality offered by the Inventory and
warehouse management module by describing a series of tasks that are
performed by using the module.

The following main tasks are supported by the Inventory and warehouse
management module.

• Reservations and marking of inventory


• Maintenance of item transaction history and on hand inventory
• Inventory journal transactions such as cycle counts and adjustments
• Quarantine and quality management
• Other

6-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Reservations and Marking


When you enter a sales order line, you can make a commitment against the
current stock or an expected future arrival. The reserved quantity will be
deducted from the available quantity. This guarantees that the sales order line can
be delivered as promised. This concept is known as reservation.

When an item is delivered to a customer, the cost value of the item is used to
calculate the sale’s contribution margin. You can allocate a single sale of an item
against a specific stock lot to make sure that this calculation is completed
correctly. This concept is known as marking. Marking is used on items where the
average cost could be misleading because of large fluctuations in the costs of
individual stock lots.

Marking is a more detailed specification within the combinations of the


dimensions set up as financial dimensions. You cannot mark across financial
dimensions.

Reservations Overview
There are two basic types of reservations in Microsoft Dynamics AX 2012—
reserved physical and reserve ordered. A physical reservation is a hard allocation
or reservation. When a transaction is physically reserved, the item is available in
the warehouse and it is specifically set aside for the transaction(s) that it is
reserved against.

The reserve ordered type reservation is a soft allocation. This means the items are
currently on order and those specific ordered items are reserved for a specific
transaction. When the items are available in inventory, the reservation is changed
from reserve ordered to reserved physical. For example, you have created a sales
order for 100 widgets. The widgets are not available in inventory. However there
are several open purchase orders for the item so that you can make an ordered
reservation for the widgets against the sales order. After the widgets are received,
the reservation can be updated to a physical reservation.

There are three methods for making reservations in Microsoft Dynamics AX


2012.

• Manual: This type of reservations requires a user to manually select


the items to be reserved.
• Automatic: This type of reservation is created by the system when
you are creating transactions.
• Explosion: This type of reservation is designed specifically for Bill
of Materials (BOM) products. The reservation is "exploded" or
"expanded" to the line of the BOM not just the header.

6-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Reservations Data Model


The data model for reserved inventory is the same as other types of inventory
transactions. When inventory is reserved, the inventory transaction (InventTrans
table record) is updated with an Issue status to indicate that the quantities are
physically reserved or reserve ordered. Additionally, the InventDimFixed field
is updated with the inventDimID for the dimension combination that the
inventory is reserved against.

The InventSum table is used to make sure that the reserved quantities are
available. This requires that negative physical inventory is not allowed and it is
controlled by the item model group that is specified on each released product.
The control of the availability only considers the dimensions that are marked as
part of the physical inventory.

NOTE: For more information about the inventory transaction data model, refer
to the "Inquiries and Transactions" topic in this course.

Inquiries and Transactions


You can use the Inventory and warehouse module to make inquiries on the
actual status and on historic transactions.

On hand

The quantity on hand (available quantity) is a key figure when you make
decisions related to a specific item. This information can be supplemented by
expected stock movements because of future purchases, production, or sales. One
of the main purposes of the Inventory and warehouse management module is
to supply this important information; many of the other functions described are
intended to maintain this information.

Transactions

Historic transactions are an important source of information because they show


all item movements. By knowing the current quantity of an item, and its historic
transactions, you can calculate the quantity in stock for any historic date. You
can also print an inventory list for a given date, even if the quantities have
changed because of transactions after this date.

6-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Inventory Transactions
Many different actions in the system can trigger how you can create inventory
transactions. The four primary transactions include the following.

• Purchase: When purchase orders are created, the expected receipt is


recorded in the inventory transactions. The status is changed when
the product receipt and invoice are updated.
• Production: When a production order is created and estimated, the
expected receipt and consumption are recorded in the inventory
transactions. The status is changed when the raw materials are
consumed and when the goods are reported as finished.
• Project: The Project management and accounting module has
several functions to register the consumption of items. A project can
be related with a purchase order that contains items bought for the
specific project. The project can also have related sales orders to
manage the items sold to the customer as a part of the project. The
consumption of items can also be registered by using an inventory
journal or by creating an item requirement.
• Sales: When a sales order is created, the expected withdrawal is
recorded in the inventory transaction. If the quantity is reserved, this
is reflected in the status of the inventory transaction. Item status is
changed as picking lists, packing slips, and invoices are updated.

Inventory Transactions Data Model


The InventTrans table is one of the largest tables in Microsoft Dynamics AX, and
it keeps growing because of too much redundant data. Microsoft Dynamics AX
2012 begins changing this trend by refactoring parts of the table.

Refactoring helps reduce the amount of data that is stored (disk space) and help
parts of the table to avoid redundant data and the inherent risk of inconsistent
data.

The earlier versions of Microsoft Dynamics AX used the InventTransId field


name to identify sets of inventory transactions in the InventTrans table to then
identify the origin of inventory transactions in the originating tables, such as the
SalesLine, PurchLine, ProdTable, or InventJournalTrans table. However, the
InventTransId is not the ID for inventory transactions. This field identified the set
of inventory transactions related to the inventory transaction originating record.

Microsoft Dynamics AX 2012 introduces a new table named InventTransOrigin


that uses the RecId as the primary key, and the InventTransId is the alternative or
natural key. The new table stores data that is common to all the transactions
related to the same inventory transaction originating record.

6-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

The following figure shows the data model for inventory transactions.

FIGURE 6.1 INVENTORY TRANSACTIONS DATA MODEL

InventTrans Relationships
The split of the InventTrans table affects code that uses the relationships between
the inventory transaction originating tables and the inventory transaction table.
The InventTransId field is removed from the InventTrans table and is replaced
by the InventTransOrigin field to reference the InventTransOrigin table. Some
inventory transaction originating tables keep the InventTransId field; however,
the field cannot be used to reference the InventTrans table. All inventory
transaction originating records must first be referenced by a record in the
InventTransOrigin table that references the InventTrans table. The following
code example shows how to do this.

while select inventTransOriginSalesLine


where inventTransOriginSalesLine.SalesLineDataAreaId
== salesLine.dataAreaId
&& inventTransOriginSalesLine.SalesLineInventTransId
== salesLine.InventTransId
join inventTrans
where inventTrans.InventTransOrigin ==
inventTransOriginSalesLine.InventTransOrigin
{
info(inventTrans.toString());
}

6-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

This change also affects other objects that used the InventTransId field to find,
collect, or summarize data from the InventTrans table.

Existing tables such as SalesLine still have an InventTransId field. However,


we strongly recommend that you use the InventTrans <OriginatingTable>
(InventTransOriginSalesLine) table to reference the InventTransOrigin table
instead of using the InventTransId field of the <OrginatingTable> (SalesLine)
table. In a future release of Microsoft Dynamics AX, the InventTransId fields
will be removed from the inventory transaction originating tables. If you rely on
those InventTransId fields, you will have to update your code when you
upgrade.

InventMovement Class
The InventMovement class is used to wrap a record that is responsible for
generating inventory transactions. Sales line, production table, and inventory
journal line are examples of tables that hold this type of records. The concept is
to make a common presentation of the data attributes and ignore the source.

The InventMovement class is extended to cover additional functionality for each


source. The following figure shows the class hierarchy for the InventMovement
class.

FIGURE 6.2 INVENTMOVEMENT TYPE HIERARCHY BROWSER

The InventUpdate object requires an InventMovement object to specify which


data to update. You can use the static method InventMovement::construct() to
initialize the object for the actual record.

6-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

InventUpdate Class
You can use the InventUpdate class to make a specific change to the state of the
data. Reservation, Pick, and Delivery are examples of state changes covered by
this class.

InventUpdate is extended to cover each update. The following figure shows the
class hierarchy for the InventUpdate class.

FIGURE 6.3 INVENTUPDATE TYPE HIERARCHY BROWSER

The InventUpdate object is initialized with a specified InventMovement object.


The specification of dimension values is specified as additional parameters, when
the InventUpdate object is instantiated. When the object is initialized the object
method updateNow() performs the update.

Each InventUpd_ class has a series of static methods with a prefix new. They are
used to initialize the object that has a specific set of parameters.

The following pattern is typically used when you work with InventUpdate.

inventUpd_Reservation =
InventUpd_Reservation::newMovement(movement, reservation,
mayBeReduced);

inventUpd_Reservation.updateNow();

6-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Inventory Statuses
The inventSum table contains the sum of all inventTrans for each combination of
ItemId and InventDimId. InventTrans has two fields that specify the status of the
transaction—StatusReceipt and StatusIssue. InventSum has several fields that
specify the quantity of items of a different status.

FIGURE 6.4 INVENTSUM AND INVENTTRANS STATUS AND QUANTITY


FIELD RELATIONSHIPS

Designs that use InventSum are preferred for performance reasons, because it
prevents the summing of transactions during both the calculation of available
quantities and the control of negative inventory.

InventSum contains the sum of all inventory transactions. To calculate the


inventory status on a date in the past, you first have to adjust the figures found in
InventSum with the transactions updated after the date in question.

The information in InventSum is updated every time that a transaction is


committed. When you are in a transaction, the table will not reflect the changes
that you made in the current transaction. If the InventOnHand class is used to
fetch the data from InventSum, the changes from the current transaction will be
included.

Each record in InventTrans contains several dates.

• DateExpected: Expected date of the physical movement.


• DateInvent: Date the transaction is registered or picked on.
• DatePhysical: Date of the physical movement (product receipt,
packing slip, or report as finished).

6-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

• DateFinancial: Date of the financial movement (vendor invoice,


sales order invoice, or ending of a production order).
• DateStatus: Date the inventory status (status issue or status receipt)
is last updated.
• DateClosed: Date the transactions are financially closed on.

InventOnHand Class
The InventSum table contains consolidated figures for each item and dimension
combination. The content of this table is redundant to the data in InventTrans.
The reason for this design is to increase performance when calculating quantity
on hand.

InventOnHand class is used to wrap the InventSum table and should be used to
retrieve the information.

The class has several different static methods that are used to initialize the object.
You can use the static method InventOnHand::newItemDim to retrieve the
consolidated quantities for the specified dimension values. The following code
sample shows how to call this method.

ItemId itemId;
InventBatchId inventBatchId;
InventDim inventDimCriteria;
InventDimParm inventDimParm;
InventOnHand inventOnHand;

inventDimCriteria.clear();
inventDimCriteria.inventBatchId = inventBatchId;

inventDimParm.clear();
inventDimParm.InventBatchIdFlag = NoYes::Yes;

InventOnHand = InventOnHand::newItemDim(itemId,
inventDimCriteria,
inventDimParm);

info(strFmt(“The quantity available is %1”,


inventOnHand.availPhysical()));

InventDimOnHand Class
You can use the InventOnHand class to calculate consolidated figures for one
specification of an item ID and a dimension combination.

You can use the InventDimOnHand class to have individual figures for a more
detailed specification, than the one being used to limit the query.

The following sample shows how to obtain the physical quantity available for
each item included on a specific inventLocationId and wmsLocationId.

6-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

InventDimOnHand inventDimOnHand;
InventDimOnHandIterator inventDimOnHandIterator;
InventDimOnHandMember inventDimOnHandMember;
InventDim inventDimCriteria;
InventDimParm inventDimParmCriteria;
InventDimParm inventDimParmOnHand;

inventDimCriteria.clear();
inventDimCriteria.InventLocationId = inventLocationId;
inventDimCriteria.wmsLocationId = wmsLocationId;

inventDimParmCriteria.initFromInventDim(inventDimCriteria);

inventDimParmOnHand.clear();
inventDimParmOnHand.ItemIdFlag = NoYes::Yes;

inventDimOnHand = InventDimOnHand::newAvailPhysical(
'',
inventDimCriteria,
inventDimParmCriteria,
InventDimOnHandLevel::SpecPositive,
inventDimParmOnHand);

inventDimOnHandIterator = inventDimOnHand.onHandIterator();

while (inventDimOnHandIterator.more())
{
inventDimOnHandMember = inventDimOnHandIterator.value();

itemId = inventDimOnHandMember.parmItemId();
qty = inventDimOnHandMember.parmInventQty();

...
...

inventDimOnHandIterator.next();
}

Inventory Costing and Valuation


Another important task for the Inventory and warehouse management module
is to establish an accounting relationship between sales revenue and the cost of
goods sold. Microsoft Dynamics AX 2012 supports the following accepted
accounting models.

• First in, First out (FIFO)


• Last in, First out (LIFO)
• Average cost (Weighted average)
• Standard cost

6-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

The costing method is determined by settings on the item model group for each
product. Any number of costing methods can be used in a single installation.
When a method other than standard costing is used, the system records
transactions at the weighted average in real time. Then, a process that is known
as Inventory close must be run periodically to make adjustments from the
weighted average to the actual costing method. Additionally, the process makes
settlements between the receipts and invoices. After this process is complete the
inventory is stopped up to the date that inventory is closed for. This means that
no additional transactions can be posted with a date earlier than the specified
date.

When the inventory close process is run, the system updates the transactions
(inventTrans table records) with a new status in the ValueOpen field, records the
closed date, and records any adjustments for each inventory transaction.

InventSettlement
When a withdrawal from inventory is updated financially, it will be assigned a
cost value that is based on the current status of the inventory. Later, financial
receipt updates could affect the originally calculated cost value. There is no
automatic recalculation of the cost of goods sold for the update of the receipt.

6-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

However, a periodic run of the inventory close process will reevaluate the
assigned cost value. The original cost value is specified in the
InventTrans.CostAmountPosted field. The adjustment will not change this
original value. However, the change will be specified in the
InventTrans.CostAmountAdjustment field. If the transaction is affected by
more than one adjustment, this field will contain the consolidated adjustment.
Each adjustment is logged in the InventSettlement table. The following figure
shows the relationship between inventory transactions and settlements.

FIGURE 6.5 INVENTSETTLEMENT OBJECT MODEL

The InventTrans.costValue() method returns the current cost value that is the sum
of the CostAmountPosted and CostAmountAdjustment fields.

The InventSum.PostedValue field contains the consolidated cost value and


includes all adjustments.

6-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Inventory and Warehouse Management Integrations


The Inventory and warehouse management module is used to keep track of
physical items. The following figure shows the interface with the other modules
in Microsoft Dynamics AX 2012.

FIGURE 6.6 INVENTORY AND WAREHOUSE MANAGEMENT


INTERACTIONS WITH OTHER MODULES

Items are bought through the Procurement and sourcing module or produced in
the Production control module. Items are consumed by sales orders, projects or
production orders. The Ledger module keeps track of inventory value and
consumption costing.

Inventory Journals
The primary way that inventory is updated in Microsoft Dynamics AX is through
sales orders, purchase orders, and production orders. Inventory journals are an
alternative that you can use to make manual updates to the inventory. Several
types of journals can be used to make updates.

Each inventory journal consists of a header and lines. The header defines the
journal information that is configured on the journal name. These inventory
journal names resemble the journal names and types that are defined in the
General ledger module.

The journal lines are used to define the items, dimensions, and quantities. Each
type of journal has small differences. However, the main principle is that the
journal has inventory transactions in the inventTrans table that are used to add or
remove inventory.

6-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Journal Types
The four primary journal types are described in the following sections.

Movement

A movement is an update of a receipt or withdrawal of a specified quantity


without a related purchase, production, or sales order. This type of journal offers
additional control so that users can specify a main account that the inventory cost
is offset to.

Inventory Adjustment

An adjustment is made when a deviation is found between the physical inventory


and the quantity registered in Microsoft Dynamics AX 2012. A loss could also be
relevant if some items in stock are damaged or destroyed.

Counting

Counting is a special version of an adjustment, because the quantity entered is the


physical quantity counted. In a typical inventory adjustment journal, the change
in quantity is entered.

Transfer

A transfer is used when a lot is moved from one warehouse to another. The same
function is also used to change other inventory dimensions, such as batch ID,
serial ID, pallet, or warehouse location.

Additional journal types are available for item arrivals, production input, and tag
counting. For more information about other journal types, refer to the Help.

6-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Inventory Journal Data Model


The following figure displays the data model that is used for inventory journals.

FIGURE 6.7 INVENTORY JOURNALS DATA MODEL

6-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

InventJournalCheckPost Class
The InventJournalCheckPost class prepares for the validation and posting of an
inventory journal. It uses the baseEnum InventJournalType to construct an
instance of the correct type. The JournalCheckPost class actually does the
validation and posting.

The JournalCheckPost.postJournal() method selects the lines of the correct type


of journal. For each journal line the postTrans() method is called.

The class can be activated directly from X++ by using the following lines of
code.

JournalCheckPost =
InventJournalCheckPost::newPostJournal(inventJournalTable);

JournalCheckPost.run();

6-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Lab 6.1 - Import Beginning Balances


This lab demonstrates how to programmatically create a new movement journal
by importing a comma separated value (CSV) file.

Estimated time to complete: 25 minutes

Scenario

Simon, the Business System Developer, must upload the beginning inventory on
hand balances for the products that Contoso sells. The information is currently in
a spreadsheet and must be imported. Simon must create a new class that includes
a dialog box that has a field that allows the user to browse to the desired file, and
a drop-down box to select the journal name to be used for the import.

The import tool should be fixed to only allow the import of movement journals.
The journal should not be posted automatically to allow the user to review the
journal before he or she manually posts the journal.

Challenge Yourself!
Use the provided information to create a new class that has a dialog box that has
two parameters for selecting a file and a journal name. Add logic to the OK
button in the dialog box to open the selected file and create a new movement
journal header by using the journal name that is specified in the dialog box. Each
line of the spreadsheet must be imported into the journal lines. When the file is
finished processing, the users should receive an Infolog informing them of the
journal number.

Need a Little Help?

1. Create a new project to store the objects that you create or modify as
a part of this workshop.
2. Create a new class.
3. Add methods to the class for a dialog box. For an example of how to
create a dialog box in a class, refer to the Tutorial_RunBaseBatch
class.
4. Add a progress indicator to the class. For an example of how to
implement a progress indicator, refer to the Tutorial_Progress class.
5. Add validation to the class to verify that the two fields in the dialog
box are populated with a value.
6. Add methods to the class to open an excel file and read in the
contents of the file. Use the SysExcelApplications and
SysExcelWorkbooks classes to open and process the file.
7. Add a method to correctly close the Excel file when you are finished.

6-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

8. Add methods to the class to create a new journal header and journal
lines. For a sample of code that creates movement journals, refer to
the TutorialJournalCreateExample.
9. Create a menu item to open the new dialog box, and put the menu
item in the Periodic folder of the Inventory and warehouse
management module.
10. Create a new journal name to be used for the import in the
tutorial_JournalName form.
11. Test the import by importing the
AX2012_ENUS_DEVIV_06_01_LAB_SAMPLEFILE.xls file from
the Hyper-V training image.

Step by Step

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_06_01_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

Follow these steps to create a new project.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as ImportBeginningBalancesLab.
6. Double-click the project to open it, and then close the Projects
window.

To create a new class that is copied from the Run Base Batch Tutorial, follow
these steps.

1. In the AOT window, browse to Classes > Tutorial_RunbaseBatch.


2. Right-click the class and click Duplicate.
3. Right-click the CopyOfTutorial_RunbaseBatch class that is
created and click Rename.
4. Enter a name for the class such as ImportBeginningBalances.
5. Save the class.
6. Drag the new class into the project created earlier.
7. Save the project.

6-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

To update the code in the class for the dialog to importing beginning balances,
follow these steps.

1. Locate the ImportBeginningBalances class and then right-click and


choose View Code.
2. In the classDeclaration method, add variables for the packed
variables, Microsoft Office Excel objects, and the dialog fields. Use
the following code sample to guide you.

class ImportBeginningBalances extends RunBaseBatch


{
// Packed variables
FilenameOpen fileNameOpen;
TutorialJournalNameId inventJournalNameId;

// Excel objects
SysExcelApplication oSysExcelApplication;
SysExcelWorkbooks oSysExcelWorkbooks;
SysExcelWorksheets oSysExcelWorksheets;
SysExcelWorksheet oSysExcelWorksheet;
SysExcelCells oSysExcelCells;

// Dialog fields
DialogField dlgFileNameOpen;
DialogField dlgInventJournalNameId;

#define.CurrentVersion(1)
#define.Version1(1)
#localmacro.CurrentList
fileNameOpen,
inventJournalNameId
#endmacro
}

3. Modify the construct method to create a new instance of the


ImportBeginningBalances class. Use the following code sample to
guide you.

server static ImportBeginningBalances construct()


{
return new ImportBeginningBalances();
}

4. Update the description of the class. Use the following code sample to
guide you.

6-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

static ClassDescription description()


{
return "Import Beginning Balances";
}

5. Change the main method to call the construct of the


ImportBeginningBalances class. Use the following code sample to
guide you.

static void main(Args args)


{
ImportBeginningBalances ImportBeginningBalances;
;
ImportBeginningBalances = ImportBeginningBalances::construct();

if (ImportBeginningBalances.prompt())
ImportBeginningBalances.run();
}

6. Next, modify the dialog method to include the fileNameOpen and


inventJournalNameId fields. Use the following code sample to guide
you.

public Object dialog()


{
DialogRunbase dialog = super();
#resAppl
dlgFilenameOpen = dialog.addFieldValue(
extendedTypeStr(FilenameOpen),
FilenameOpen);
dlgInventJournalNameId =
dialog.addFieldValue(
extendedTypeStr(TutorialJournalNameId),
InventJournalNameId);

return dialog;
}

7. Next modify the getFromDialog method to set the value of the


fileNameOpen and inventJournalName variables. Use the following
code to guide you.

public boolean getFromDialog()


{
fileNameOpen = dlgFileNameOpen.value();
inventJournalNameId = dlgInventJournalNameId.value();

6-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

return super();
}

To add validation, a progress indicator, and logic to import the file, follow these
steps.

1. To add validation to the class, modify the validate method. Use the
following code sample to guide you.

public boolean validate(Object _calledFrom = null)


{
boolean ret = true;
//Add validation to the class to verify that the two fields on the dialog box are
populated with a value.
if (!fileNameOpen)
{
ret = checkFailed("Invalid file name.");
}
if (!inventJournalNameId)
{
ret = checkFailed("Invalid invent journal name Id.");
}
return ret;
}

2. Add the following code that is used to initialize the objects for
importing a spreadsheet in the init method.

public boolean init()


{
;
// If spreadsheet document doesn't exist, then quit
if (! winAPI::fileExists(fileNameOpen))
{
throw error(strfmt("File '%1' doesn't exist or is currently open.",
fileNameOpen));
}

// Start excel & turn off alerts


oSysExcelApplication = SysExcelApplication::construct();
oSysExcelApplication.displayAlerts(false);
oSysExcelWorkbooks = oSysExcelApplication.workbooks();

// Try to open the file


try
{
oSysExcelWorkbooks.open(fileNameOpen);
}

6-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

catch
{
throw error(strfmt("@SYS76826", fileNameOpen));
}

oSysExcelWorksheets = oSysExcelApplication.worksheets();

return true;
}

3. Create a new method called startProgress that will initiate the


progress bar. Use the following code sample to guide you.

void startProgress()
{
#avifiles
SysOperationProgress oProgress;
oProgress = new SysOperationProgress();
oProgress.setAnimation(#aviupdate);
oProgress.setCaption(ImportBeginningBalances::description());
oProgress.update(true);
}

4. Create a new method called readAll that opens the file and reads the
records. Use the following code sample to guide you.

private void readAll( )


{
// Macro for file type (extension)
#define.SP_FILE_TYPE ("xls")

// Macros for input and output sheet


#define.SP_OUTPUT_WORKSHEET ("Data")

// Macros for read


#define.SP_START_ROW (2)
#define.SP_END_ROW (10)
#define.SP_READ_TRANSDATE_COLUMN (1)
#define.SP_READ_ITEMID_COLUMN (2)
#define.SP_READ_COST_COLUMN (3)

int startRow = #SP_START_ROW;

InventDim tInventDim;
TutorialJournalTable journalTable;
TutorialJournalTrans journalTrans;

TutorialJournalTableData journalTableData =
JournalTableData::newTable(journalTable);
TutorialJournalTransData journalTransData =

6-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

journalTableData.journalStatic().newJournalTransData(journalTrans,journalTa
bleData);

// Try to open Outputs worksheet


oSysExcelWorksheet =
oSysExcelWorksheets.itemFromName(#SP_OUTPUT_WORKSHEET);
if (oSysExcelWorksheet == null)
{
throw error(strfmt("No 'Outputs' worksheet in file '%1'.", fileNameOpen));
}

// Try reading values from outputs worksheet


try
{

// Init journalTable

journalTable.JournalId = journalTableData.nextJournalId();
journalTable.JournalType = InventJournalType::Movement;
journalTable.JournalNameId = inventJournalNameId;

journalTableData.initFromJournalName(journalTableData.journalStatic().findJ
ournalName(journalTable.JournalNameId));

oSysExcelCells = oSysExcelWorksheet.cells();
while (startRow <= #SP_END_ROW)
{

journalTrans.clear();
journalTransData.initFromJournalTable();

journalTrans.TransDate = oSysExcelCells.item(StartRow,
#SP_READ_TRANSDATE_COLUMN).value().date();
journalTrans.ExItemId = this.cell2String(StartRow,
#SP_READ_ITEMID_COLUMN);
journalTrans.ExCostAmount = oSysExcelCells.item(StartRow,
#SP_READ_COST_COLUMN).value().double();

journalTransData.create();

StartRow ++;
}
journalTable.insert();
}
catch
{
throw error("Reading values from Excel file failed.");
}
}

6-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Create a new method called cell2String that converts the value


passed in to a string. Use the following code sample to guide you.

private str cell2String(int _row, int _column)


{
str ret;

if (! oSysExcelCells)
{
ret = '';
}
else
{
switch (oSysExcelCells.item(_row, _column).value().variantType())
{
case COMVariantType::VT_BSTR:
// String type
ret = strltrim(strrtrim(oSysExcelCells.item(_row,
_column).value().bstr()));
break;
case COMVariantType::VT_R8:
// Real type
ret = strltrim(strrtrim(num2str(oSysExcelCells.item(_row,
_column).value().double(),0,0,0,0)));
break;
default :
ret = '';
break;
}
}
return ret;
}

6. Create a new method called exitExcel that correctly closes Microsoft


Office Excel. Use the following code sample to guide you.

private void exitExcel()


{
if (oSysExcelApplication)
{
// Although displayAlerts is called in init it appears necessary to
// call it again. Otherwise if the application is not saved a dialog
// will pop up asking if the file should be saved.
oSysExcelApplication.displayAlerts(false);
oSysExcelApplication.quit();
}
}

6-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

7. Modify the run method to execute the logic you created in the
startProgress, init, readAll, and exitExcel methods. Use the following
code sample to guide you.

/// <summary>
/// Contains the code that does the actual job of the class.
/// </summary>
public void run()
{
#OCCRetryCount
if (! this.validate())
throw error("");

try
{
ttsbegin;

this.startProgress();
this.init();
this.readAll();
this.exitExcel();

ttscommit;
}
catch (Exception::Deadlock)
{
retry;
}
catch (Exception::UpdateConflict)
{
if (appl.ttsLevel() == 0)
{
if (xSession::currentRetryCount() >= #RetryNum)
{
this.exitExcel();
throw Exception::UpdateConflictNotRecovered;
}
else
{
retry;
}
}
else
{
this.exitExcel();
throw Exception::UpdateConflict;
}
}
catch (Exception::Error)
{

6-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

error("Import failed!");
this.exitExcel();
}

8. Save and compile the class, and then close the Code Editor window.

Test
To create a new menu item and put it on the main menu in the Inventory and
warehouse management module under the Periodic folder, follow these steps.

1. In the AOT window, expand Menu Items.


2. Right-click Action, and then click New Menu Item.
3. In the Properties window, set the following values.
a. Name = ImportBeginningBalances
b. Label = Import beginning balances
c. HelpText = Tutorial to import beginning balances into a
movement journal.
d. ObjectType = Class
e. Object = ImportBeginningBalances

4. Save the menu item.


5. Drag the new menu item into the project that you created earlier.
6. In the AOT window, browse to Menus >
InventoryAndWarehouseManagement.
7. Drag the menu into the project that you created earlier.
8. In the Project window, browse to the Periodic folder of the
InventoryAndWarehouseManagement menu.
9. Drag the ImportBeginningBalances menu item into the Periodic
folder and place it below the Inventory blocking menu item.
10. Save the menu and the project.

To create a new journal name to be used for the import, follow these steps.

1. In the AOT window, browse to Forms > tutorial_JournalName.


2. Right-click the form and then click Open.
3. Create a new record and enter the following information.
a. Name = IMov
b. Description = Inventory Movement
c. Journal type = Movement
d. Voucher series = Inve_72

4. Close the Journal names form.

6-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

To test the new menu item and import process, follow these steps.

1. Close the Microsoft Dynamics AX 2012 client.


2. Open a new Microsoft Dynamics AX 2012 client.
3. Open Inventory and warehouse management > Periodic > Import
beginning balances.
4. Verify that your dialog box looks similar to the following figure.

FIGURE 6.8 IMPORT BEGINNING BALANCES DIALOG BOX

5. Click the yellow folder icon and browse to the


AX2012_ENUS_DEVIV_06_01_LAB_SAMPLEFILE.xlsx file.
6. Click Open in the Windows Explorer window to open the file.
7. In the Name drop-down box, select IMov.
8. Click OK.
9. Notice the progress indicator while file imports. When the process is
finished the progress bar will disappear to indicate the process is
finished.

To view the journal that was imported, follow these steps.

1. Open the Development Workspace.


2. In the AOT window, browse to Forms > tutorial_JournalTable.
3. Right-click the form and select Open.

6-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

4. Notice the journal header that is imported, and then click Lines.
5. Notice the journal lines that are imported. Your data should look
similar to the following figure.

FIGURE 6.9 JOURNAL AND JOURNAL LINES FORMS

TIP: You can repeat the test as many times as you would like. The journal
number and voucher numbers will automatically increment during each import.

TIP: You can import the AX2012_ENUS_DEVIV_06_01_LAB_SOL.xpo file to


verify and compare your solution.

NOTE: This lab uses the Microsoft Dynamics AX 2012 Tutorial tables, classes,
and forms. In a more realistic implementation, you should create your own
tables, forms, and classes.

6-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Quarantine and Quality Management


Microsoft Dynamics AX 2012 includes functionality to help you manage the
quality of the products that you purchase or sell. This includes quarantine
management, quality management with tests, and inventory blocking.

Quarantine Orders
The quarantine function is used to block a specific lot. When the quarantine is
started, the quantity is removed from available inventory. Later, when the
quarantine is ended, the quantity is returned to available inventory. One use of
this function is to block a received lot until it has passed quality assurance.

The InventMov_Quarantine class is used when you work with inventory


quarantine orders to control items that are in the InventQuarantineOrder table
quarantine. Quarantine orders differ from other types of orders such as purchase
orders or sales orders because they do not have a header and line data structure.

Quality Orders
You can use quality orders to identify the tests and to record test results and test
quantity for a specific item.

The tests are copied from the test group that is assigned to the quality order. Tests
can be added, deleted, or changed. A quality order can be manually created or
automatically generated based on rules that are defined in the Quality
associations form found in Inventory and warehouse management > Setup >
Quality control. A quality order is associated with an item in a sales order, a
purchase order, a quarantine order, a production order, a production order routing
operation, or an on-hand inventory balance. Items that are specified for
inspection in a quality order are automatically blocked from issue or
consumption.

Each quality order is stored in the InventQualityOrder table. The lines of the
quality order represent each test to be performed and stored in the
InventQualityOrderLine table. Each test or quality order line can have test results
recorded for it that are stored in the InventQualityOrdersLineResults table. The
InventQualityManagementCreate class provides the facilities for quality
management order generation.

Inventory Blocking
Inventory blocking is part of the quality inspection process. During the quality
inspection, items are automatically blocked from consumption or issue. Also, you
can manually block items that you want to prevent from being issued or
consumed.

6-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Inventory blocking methods

Inventory items can be blocked three ways—manually, by creating a quality


order, or by using a process that generates a quality order.

Block items manually

The quantity of an item can be blocked by creating a transaction in the Inventory


blocking form found in Inventory and warehouse management > Periodic.
Only items that are available as on-hand inventory can be blocked.

For manually blocked quantities, you must consider if expected receipts should
be included in planning activities as an expected on-hand quantity. Expected
receipts are blocked items that are expected to be available as on-hand inventory
after inspection. By default, the Expected receipts check box is selected for
items that are blocked through a quality order.

You can cancel blocking of a manually blocked quantity by deleting the


transaction in the Inventory blocking form.

Block items by creating a quality order

Items can be specified for inspection by creating a quality order in the Quality
orders form found in Inventory and warehouse management > Periodic >
Quality management. When you create a quality order, the quantity of an item
that you specify is blocked.

NOTE: The sampling plan (created in Inventory and warehouse management >
Setup > Quality control > Item sampling) that is associated with a quality order
controls the quantity of an item that should be inspected. The quantity of blocked
items, on the other hand, is not controlled by the sampling plan. Regardless of
the quantity that is sent for inspection, as specified by the sampling plan, the
quantity of the item that is entered on the quality order is the quantity that is
blocked.

Block items by a process that generates a quality order

A quantity of an item that is specified for inspection through a quality process is


automatically blocked. So when a quality order is generated automatically, the
item sampling plan that is associated with the quality order controls the quantity
of items that is blocked and not only the quantity of items that will be inspected.

NOTE: If the Full blocking check box in the Item sampling form is selected, the
full quantity of, for example, a purchase order line is blocked during inspection
regardless of the item sampling quantity.

6-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

The InventMov_Blocking class is a specialized InventMovement class version


responsible for handling inventory blockings. The InventBlockingTableType
class wraps various properties of the different inventory blocking types and
callers. The InventBlockingQualityOrderSync class provides methods to
synchronize inventory blocking and related quality orders.

Other Functionality
The Inventory and warehouse management module has many additional
features. The following topics review the forecasting and transfer order
functionality.

Forecasts
Forecasts are used to enter sales and purchases expected in the future. By
forecasting you can plan for the future beyond the period covered by received
sales orders and created purchase orders. For example, forecasts are necessary
when a manufacturing company’s production lead time is longer than the order-
to-delivery time that it offers customers.

A forecast model is used to name and identify a specific forecast.

You can define a forecast model in two levels. A forecast model can include one
or more submodels. This allows you to aggregate the individual forecasts. When
you run forecast scheduling for a top-level forecast model, the program calculates
gross requirements for all models that are designated as submodels.

• All forecast models must be defined before you can designate one or
more models as submodels of a forecast model.
• A forecast model that is used as a submodel cannot contain other
submodels.
• A forecast submodel uses its own parameters, not those of the top-
level forecast model.

There are several types of forecasts available in Microsoft Dynamics AX 2012


including demand, supply, item, and expense forecasts.

Transfer Orders
A transfer between two warehouses can be updated by using a transfer journal as
mentioned earlier. However, when a journal is updated, the issue and receipt are
updated at the same time. If there is a time lag between the issue and the receipt
because of transport time, this can be reflected by creating a transfer order.

Transfer orders differ from transfer journals because shipping and receiving
actions must be completed. They also allow for multiple shipments and receipts
against the same order.

6-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Before shipping a transfer order, you can also do the following.

• Select the transfer order lines that you want to ship.


• Reserve items for transfer. In the Transfer orders form, click
Inventory > Reservation and then select the items that you want to
reserve for transfer.
• Pick items for transfer. In the Transfer orders form, click Inventory
> Pick and then select the items that you want to pick for transfer. In
the Pick list, select items for transfer by their serial number. You can
also print a picking list and register picking list.
• Specify the quantity that you want to ship for each transfer order line
by entering a quantity in the Ship now field. To ship this quantity,
open the Shipment form and select Ship now in the Update list.
• Print the transfer order by clicking Print and selecting Transfer
overview.

6-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Lab 6.2 - Inventory Blocking


This lab demonstrates how to modify the inventory blocking functionality to
support the clearing of blocked inventory instead of deleting the inventory
blocking record.

Estimated time to complete: 25 minutes

Scenario

Contoso has to keep a history of all inventory blocking records for auditing. In
Microsoft Dynamics AX 2012, an inventory blocking record must be deleted to
clear or release the hold on the inventory.

Simon, the Business Systems Developer, must add new fields to track the date,
time, and the user who clears the inventory blocking. Additionally, the Delete
button on the Inventory blocking form must be modified to copy the data into a
new Inventory blocking history table.

He must then create a new form and menu item to access the inventory blocking
history. The new Inventory blocking history form will be located in Inventory
and warehouse management > Inquiries > Quality management.

Challenge Yourself!
Use the provided information to create a new table to track the history of cleared
inventory blocking records. Add new fields to this table to store the user ID and
the cleared date and time. Modify the functionality of the Delete button on the
Inventory blocking form to copy the blocking record to the new inventory
blocking history table.

Need a Little Help?

1. Create a new table for inventory blocking history. Make sure that
you include new fields with extended data types for the user ID,
cleared flag, and the cleared date and time.
2. Create a new form for the inventory blocking history.
3. Create a new menu item for the new inventory blocking history, and
add the menu item to the main menu under Inventory and
warehouse management > Inquiries > Quality management.
4. Create a new method in the InventBlockingTableType class to copy
the inventory blocking record to the inventory blocking history table.
5. Modify the delete method in the InventBlockingTableType class to
call the new method that you created in step 4.
6. Test the new functionality to verify that the records are copied to the
new inventory blocking history table.

6-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Step by Step: Create the Table


Follow these steps to create a new project.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as InventoryBlockingLab.
6. Double-click the project to open it, and then close the Projects
window.

To create new extended data types for the new inventory blocking history table,
follow these steps.

1. In the AOT window, browse to Data Dictionary > Extended Data


Types.
2. Right-click Extended Data Types, and then click New > Enum.
3. In the Properties window for the new enum, set the following
values.
a. Name = InventBlockingClearedFlag
b. Label = Cleared
c. HelpText = Inventory blocking is cleared when selected.
d. Extends = NoYesId
e. EnumType = NoYes

4. Save the extended data type, and then drag it into the project that you
created earlier.
5. Right-click Extended Data Types, and then click New >
UtcDateTime.
6. In the Properties window for the new extended data type, set the
following values.
a. Name = ClearedDateTime
b. Label = Cleared date time
c. HelpText = Date and time the inventory blocking was cleared.

7. Save the extended data type, and then drag it into the project that you
created earlier.
8. Save the project.

6-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

To create a new inventory blocking history table, follow these steps.

1. In the AOT window, browse to Data Dictionary > Tables >


InventBlocking.
2. Right-click the InventBlocking table and then click Duplicate.
3. In the Properties window, set the following values.
a. Name = InventBlockingHistory
b. Label = Inventory blocking history
c. CreatedDateTime = No
d. CreatedBy = No

4. Save the table, and then drag it into the project that you created
earlier.
5. Save the project.
6. Expand the Fields node of the InventBlockingHistory table.
7. Drag the InventBlockingClearedFlag and ClearedDateTime extended
data types into the Fields node.
8. Set the AllowEdit property on each of the fields to No.
9. Right-click the Fields node and then click New > String.
10. In the Properties window, set the following values.
a. Name = ClearedBy
b. Label = Cleared by
c. HelpText = User that cleared the inventory blocking.
d. AllowEdit = No
e. ExtendedDataType = UserId

11. Right-click the Fields node and then click New > String.
12. In the Properties window, set the following values.
a. Name = origCreatedBy
b. Label = Created by
c. HelpText = User that created the inventory blocking.
d. AllowEdit = No
e. ExtendedDataType = UserId

13. Right-click the Fields node and then click New > UtcDateTime.
14. In the Properties window, set the following values.
a. Name = origCreatedDateTime
b. AllowEdit = No
c. ExtendedDataType = CreatedDateTime

15. Right-click the Field Groups node and then click New Group.

6-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

16. In the Properties window, set the following values.


a. Name = InventBlockingClear
b. Label = Cleared

17. Drag the InventBlockingClearedFlag, ClearedBy, and


ClearedDateTime fields into the new group.
18. Expand the History field group, and then delete each of the fields
from the field group.
19. Drag the origCreatedBy and origCreatedDateTime fields into the
History field group node.
20. Save the table and the project.

Step by Step: Create the Form


To create a new form for the inventory blocking history, follow these steps.

1. In the AOT window, browse to Forms > InventBlocking.


2. Right-click the InventBlocking form and then click Duplicate.
3. Right-click the CopyOfInventBlocking form and then click
Rename.
4. Set the name to InventBlockingHistory.
5. Save the form, and then drag it into the project that you created
earlier.
6. In the form, expand Methods. Remove the inventDimSetupObject
and updateDesign methods.
7. Modify the classDeclaration of the form to only inlcude the vertical
splitter. Use the following code sample to guide you.

public class FormRun extends ObjectRun


{
SysFormSplitter_X verticalSplitter;
}

8. Modify the init method of the form to only call the super and
initialize the vertical splitter. Use the following code sample to guide
you.

public void init()


{
super();
//Initialize splitter
verticalSplitter = new SysFormSplitter_X(vSplitter, gridContainer, element);
}

9. In the form, browse to Data Source > InventBlocking > Methods,


and then remove the write, init, validateWrite, and active methods.

6-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

10. Right-click the InventBlockingForm query under the Data Sources


node and select Delete.
11. Select Permanately delete, and then click OK, to confirm the
deletion.
12. Select the InventBlocking data source, and set the following
properties.
a. Table = InventBlockingHistory.
b. AllowEdit = No
c. AllowCreate = No
d. AllowDelete = No

13. Select the Design node of the form and set the Caption property to
Invent blocking history.
14. In the form, browse to Designs > Design > ActionPane:ActionPane
> ActionPaneTab:ActionPaneTab, and then remove the
ButtonGroup:RecordBasics.
15. In the form, browse to Designs > Design > Group:Body >
Group:DetailsContainer > Tab:DetailsTab > TabPage:General,
and then set the Columns property to 3.
16. Right-click the top node of the InventBlockingHistory form and
select Restore.
17. Drag the InventBlockingClear field group from the Fields node of
the InventBlocking data source on the form into the
TabPage:General section and put it below the Group:History
group.
18. Save the form.
19. In the Project window, select the InventBlockingHistory table, and
set the FormRef property to InventBlockingHistory.

To create a new menu item and to add the menu item to the menu, follow these
steps.

1. In the AOT window, expand Menu Items.


2. Right-click Display, and then click New Menu Item.
3. In the Properties window, set the following values.
a. Name = InventBlockingHistory
b. Label = Inventory blocking history
c. HelpText = View inventory blocking history.
d. ObjectType = Form
e. Object = InventBlockingHistory

4. Save the menu item.


5. Drag the new menu item into the project that you created earlier.

6-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. In the AOT window, browse to Menus >


InventoryAndWarehouseManagement.
7. Drag the menu into the project that you created earlier.
8. In the Project window, browse to the Inquiries > Quality
management folder of the InventoryAndWarehouseManagement
menu.
9. Drag the InventBlockingHistory menu item into the Quality
management folder and place it below the Related operation time
sheets menu item.
10. Save the menu and the project.

Step by Step: Create the Logic


To create the logic for copying the inventory blocking data, to the inventory
blocking history table, follow these steps.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_06_02_LAB _CODE.txt file. You can copy and paste
these code samples into the correct methods.

In the Project window, locate the InventBlockingHistory table.

1. Delete all of the methods from the Methods node of the table. (These
methods were copied from the InventBlocking table, and are not needed on the
new InventBlockingHistory table.)

2. Create a new method on the table called initFromInventBlocking. This


method should set all of the fields in the history table from the original table. Use
the following code sample to guide you.

/// <summary>
/// Initializes the current <c>InventBlockingHistory</c> record from an
InventBlocking record.
/// </summary>
public void initFromInventBlocking(InventBlocking _InventBlocking)
{
this.ItemId = _InventBlocking.ItemId;
this.Qty = _InventBlocking.Qty;
this.InventTransIdIssue = _InventBlocking.InventTransIdIssue;
this.InventTransIdReceipt = _InventBlocking.InventTransIdReceipt;
this.InventDimId = _InventBlocking.InventDimId;
this.ExpectedReceiptDate = _InventBlocking.ExpectedReceiptDate;
this.ExpectReceipt = _InventBlocking.ExpectReceipt;
this.Description = _InventBlocking.Description;
this.BlockingType = _InventBlocking.BlockingType;
this.origCreatedBy = _InventBlocking.createdBy;
this.origCreatedDateTime = _InventBlocking.createdDateTime;
}

6-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

3. Create a new find method on the table that is used to find inventory blocking
history table records. Use the following code sample to guide you.

/// <summary>
/// Finds the specified record in the <c>InventBlockingHistory</c> table.
/// </summary>
/// <param name="_inventBlockingHistory">
/// The ID of the record to find.
/// </param>
/// <param name="_forUpdate">
/// A Boolean value that indicates whether to read the record for update;
optional.
/// </param>
/// <returns>
/// A record in the <c>InventBlocking</c> table if it exists; otherwise, an empty
record.
/// </returns>
public static InventBlockingHistory find(
RecId _inventBlockingHistory,
boolean _forUpdate = false)
{
InventBlockingHistory inventBlockingHistory;

inventBlockingHistory.selectForUpdate(_forUpdate);

select firstonly inventBlockingHistory


where inventBlockingHistory.RecId == _inventBlockingHistory;

return inventBlockingHistory;
}

4. Create a new method on the table that overrides the initValue method. This
method should set the values for the new fields that were added to the table. Use
the following code sample to guide you.

/// <summary>
/// Initializes default inventory blocking history values.
/// </summary>
public void initValue()
{
this.InventBlockingClearedFlag = NoYes::Yes;
this.ClearedBy = curUserId();
this.ClearedDateTime = DateTimeUtil::utcNow();
}

5. In the AOT window, browse to Classes > InventBlockingTableType.

6. Drag the class into the project that you created earlier.

6-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

7. Create a new method in the class called writeInventBlockingHistory, and then


add logic to the method to call the table methods for initializing and copying the
data.

/// <summary>
/// Lab 6.2 Write History Table
/// </summary>
private void writeInventBlockingHistory()
{
inventBlockingHistory inventBlockingHistory;

inventBlockingHistory.initFromInventBlocking(inventBlocking);
inventBlockingHistory.initValue();
inventBlockingHistory.insert();
}

8. Modify the delete method of the InventBlockingTableType class to call the


new writeInventBlockingHistory method. Use the following code sample to
guide you.

/// <summary>
/// Deletes the inventory blocking record and corresponding inventory
transactions.
/// </summary>
public void delete()
{
// Delete issue transaction
this.deleteBlockingTransaction();

// Delete receipt transaction if exists


if (inventBlocking.InventTransIdReceipt)
{
this.deleteBlockingTransaction(InventMovSubType::TransferReceipt);
}

//Lab 6.2 Write History Table


this.writeInventBlockingHistory();

inventBlocking.doDelete();
}

9. Save the class and the project.

Step by Step: Test the Solution


To test the new inventory blocking history functionality, follow these steps.

1. Close the Microsoft Dynamics AX 2012 client.


2. Open a new Microsoft Dynamics AX 2012 client.

6-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

3. Open Inventory and warehouse management > Periodic >


Inventory blocking.
4. Create a new record by clicking New.
5. Select an item number such as 1005.
6. Enter a description such as Test.
7. Select a configuration such as HD, a size such as 50, and a color
such as 02.
8. Save the record by pressing Ctrl+S.
9. Click Delete.
10. Close the Inventory blocking form.
11. Open Inventory and warehouse management > Inquiries >
Quality management > Inventory blocking history.
12. Notice the inventory blocking record that you just created. Your
results should look similar to the following figure.

FIGURE 6.10 INVENTORY BLOCKING HISTORY FORM

TIP: You can repeat the test as many times as you would like by using different
item numbers and dimensions. The only requirement is that the item and
dimension combination that you select must be on hand.

TIP: You can import the AX2012_ENUS_DEVIV_06_02_LAB_SOL.xpo file to


verify and compare your solution.

6-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Summary
The Inventory and warehouse management module in Microsoft Dynamics
AX 2012 integrates with many other modules and is the central module for
processing inventory transactions.

The module includes functionality for recording and updating the inventory
transactions and keeping track of the on hand quantities for every item and item-
dimension combination.

The inventory closing process provides functionality to revalue the inventory


from the weighted average to the selected inventory costing method that is
specified on each item.

Inventory journals can be used to make manual adjustments to the inventory


values by adding, removing, or counting the current on hand inventory values.
You can also make transfers by using an inventory journal or by creating a
transfer order.

Finally, quarantine and quality management features can be used to record test
results and prevent items from being processed because of quality issues.

6-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Test Your Knowledge


Test your knowledge with the following questions.

1. Describe the difference between the inventTrans table and the inventSum
table.

2. Match the inventory statuses with the correct inventory status field.

Categories (Inventory Statuses):

1. Status Issue
2. Status Receipt

_____ Item 1: Ordered

_____ Item 2: OnOrder

_____ Item 3: ReservOrdered

_____ Item 4: Received

_____ Item 5: Purchased

_____ Item 6: Deducted

_____ Item 7: Picked

_____ Item 8: Sold

3. TRUE or FALSE? The InventJournalCheckPost class handles the validation


and posting of a purchase order.
( ) TRUE
( ) FALSE

6-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

4. Which of the following stores the original cost value for an inventory
transaction in the InventTrans table?
( ) InventTrans.CostValue() method
( ) InventTrans.CostAmountAdjusted field
( ) InventTrans.CostAmountPhysical field
( ) InventTrans.CostAmountFinancial field

5. Which of the following are types of reservations available in Microsoft


Dynamics AX 2012? (Select all that apply)
( ) Reserved physical
( ) Reserve ordered
( ) Sales reservation
( ) Purchase reservation

6-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

6-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Solutions
Test Your Knowledge
1. Describe the difference between the inventTrans table and the inventSum
table.

MODEL ANSWER:

The inventTrans table stores the details of every inventory issue and receipt,
whereas the inventSum table stores the summation of all inventTrans records
grouped by the inventory dimension combinations which are identified by
the inventDimID.

2. Match the inventory statuses with the correct inventory status field.

Categories (Inventory Statuses):

1. Status Issue
2. Status Receipt

2 Item 1: Ordered

1 Item 2: OnOrder

1 Item 3: ReservOrdered

2 Item 4: Received

2 Item 5: Purchased

1 Item 6: Deducted

1 Item 7: Picked

1 Item 8: Sold

3. TRUE or FALSE? The InventJournalCheckPost class handles the validation


and posting of a purchase order.
( ) TRUE
(•) FALSE

4. Which of the following stores the original cost value for an inventory
transaction in the InventTrans table?
( ) InventTrans.CostValue() method
( ) InventTrans.CostAmountAdjusted field
( ) InventTrans.CostAmountPhysical field
(•) InventTrans.CostAmountFinancial field

6-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 6: Use and Design of the Inventory and Warehouse Management
Module

5. Which of the following are types of reservations available in Microsoft


Dynamics AX 2012? (Select all that apply)
(√) Reserved physical
(√) Reserve ordered
( ) Sales reservation
( ) Purchase reservation

6-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

CHAPTER 7: USE AND DESIGN OF THE ACCOUNTS


RECEIVABLE AND ACCOUNTS PAYABLE
MODULES
Objectives
The objectives are:

• Describe the activities and transactions that can be created for


customers.
• Review the customer data model.
• Describe the activities and transactions that can be created for
customers.
• Describe how free text invoices are used.
• Review the data model and framework that is used for processing
free text invoices.
• Review the various ways that vendor invoices can be generated.
• Describe the set up that is required for payments and review the data
model for payment set up.
• Describe how customer and vendor payments are made.
• Review the customer payment data model and discuss the framework
that is used for making and generating payments.
• Describe how collections and interest notes are used.
• Review the data model and framework for interest notes.
• Describe the functionality that is available for bill of exchanges.
• Describe the functionality that is available for promissory notes.

Introduction
The Accounts receivable and Accounts payable modules offer similar
functionality for customers and vendors. The modules are used to maintain the
customer and vendor information and the transactions that occur for each. This
chapter reviews the functionality that is available for customers and vendors and
the primary transactions that occur for each module.

7-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Customers
Accounts receivable is used to track customer invoices and incoming payments.
You can create customer invoices for a sale that is based on sales orders or
packing slips. You can also enter free text invoices that are not related to sales
orders. Additionally you can generate customer invoices from a project. You can
receive payments by using several different payment types. These include bills of
exchange, cash, checks, credit cards, and electronic payments. If your
organization includes multiple legal entities, you can use centralized payments to
record payments in a single legal entity on behalf of the other legal entities.

You can use the Settle open transactions form to settle invoices with payments
or credit notes. You can also enter payments and settle them in the Enter
customer payments form. To view customer information, use the All customers
list page and related forms. You can manage overdue balances, calculate interest,
and generate collection letters by using the Collections list page and related
forms.

Accounts Receivable Processes


The main tasks supported by the Accounts receivable module include the
following.

• Maintain customers
• Free text invoice
• Request payment
• Register payment
• Bill of exchange
• Account statement
• Collection letter
• Interest calculation
• Exchange adjustment
• Reconciliation

7-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

The following figure shows the Accounts receivable business process.

FIGURE 7.1 ACCOUNTS RECEIVABLE BUSINESS PROCESS

Maintain Customers
Creating new customers and maintaining existing customer information is an
ongoing task. Make sure that customer setup is correct to guarantee smooth
communication and to avoid calculation errors.

Some customers are transferred from the Prospects form in the Sales and
marketing module. However, other customers must be created manually in the
Accounts receivable module. The customer forms and list pages are available
from the Accounts receivable and the Sales and marketing modules.

Customer sales prices and discounts for items sold should be maintained. Prices
can be set up specifically for individual items and customers, for a group of
customers or for all customers as one group. The price structure also includes
line, multiline, and total discounts.

The actual value of invoices due in a foreign currency can change over time as
the result of exchange rate fluctuations. Because an invoice’s value is calculated
in the accounting currency when the transaction is posted, you could have to
make periodic exchange rate adjustments to revalue foreign currency receivables.

7-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Reconciliations guarantee that registrations about customer transaction status are


correct. The reconciliation process includes different kinds of reporting to
analyze open transactions and to make sure that they are reflected correctly in the
General ledger module. It is also important that the customer has the same
opinion of the current status of the financial relationship.

Accounts Receivable Integrations


The Accounts receivable module helps monitor relationships between the
company and its customers. The following figure shows interfaces with other
Microsoft Dynamics AX 2012 modules.

FIGURE 7.2 ACCOUNTS RECEIVABLE INTEGRATIONS

The Accounts receivable module handles customer-related transactions. The


primary focus of the module is to keep track of open invoices and to register
payments.

The Sales and marketing module handles administration of potential customers


or prospects. This includes submission of quotations. When a quotation is
accepted, it is then transferred to a sales order. At this point, the potential
customer is created as an actual customer.

7-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Trade agreements (terms and conditions) made with the customer are registered
and maintained in cooperation with the Inventory and warehouse management
module. The customer’s expected sales can be forecast and used in master
planning.

When a sales order or project is invoiced, the information is passed to the


Accounts receivable module that administers payment collection.

The General ledger module keeps track of all company financial transactions.
All customer financial movements are replicated in the General ledger module.

Payment transactions are recorded in the Cash and bank management module
that controls the company’s bank accounts.

Customer Data Model


The following figure shows the data model for customers and customer
transactions.

FIGURE 7.3 CUSTOMER DATA MODEL

Each transaction (invoice, payment, and so on) is represented by one record in


the CustTrans table.

7-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

CustTransOpen contains one or more records for all transactions in CustTrans


that are not completely settled against other transactions. The relation between
CustTransOpen and CustTrans is made by the RefRecId in CustTransOpen that is
a foreign key to the RecId of the related CustTrans. The reason for this design is
that one open transaction can be distributed across several due dates by using
payment schedules.

CustSettlement contains information about settlement between transactions in


CustTrans. The record refers to the two transactions (TransRecId and
OffsetRecId) and specifies the amount settled between the two transactions. The
information includes the date of the settlement. This makes it possible to
backdate or future date a transaction’s settlement status in CustTrans. This data
structure allows you to retrieve a customer balance at any point in time as it
transitions from the open to the closed state.

Both open and settled parts of a customer transaction can have related cash
discount information. This information is stored in a separate table,
CustTransCashDisc, because each transaction part can have multiple cash
discount specifications.

Vendors
Accounts payable is used to track vendor invoices and outgoing expenditures.
You can enter vendor invoices manually or receive them electronically through a
service, or your vendor can enter the invoices by using a vendor portal. After the
invoices are entered or received, you can review and approve the invoices by
using an invoice approval journal or the Vendor invoice form. You can use
invoice matching, vendor invoice policies, and workflow to automate the review
process so that invoices that meet certain criteria are automatically approved, and
the remaining invoices are flagged for review by an authorized user.

After vendor invoices are approved, you can pay vendors. If your organization
includes multiple legal entities, you can use centralized payments to pay all
invoices from a single legal entity. Multiple payment formats are supported.
These include checks, promissory notes, and Single Euro Payments Area (SEPA)
electronic payments. You can settle invoices with payments or credit notes by
using the Settle open transactions form. To view vendor information, use the
All vendors list page and related forms.

Accounts Payable Processes


The main tasks supported by the Accounts payable module include the following.

• Maintain vendors
• Register invoice
• Invoice approval
• Payment proposal
• Register payment
• Promissory notes

7-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

• Exchange adjustment
• Reconciliation

The following figure shows the Accounts payable business process.

FIGURE 7.4 ACCOUNTS PAYABLE BUSINESS PROCESS

Maintain Vendors
Creating new vendors and maintaining existing vendor information is an ongoing
task. Make sure that vendor setup is correct to guarantee smooth communication
and to avoid calculation errors.

Purchase prices and discounts for items purchased should be maintained. Prices
can be set up specifically for individual items and vendors, for a group of
vendors, or for all vendors as one group. The price structure also includes line,
multiline, and total discounts.

7-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Accounts Payable Integrations


The Accounts payable module helps monitor relationships between the company
and its suppliers. The following figure shows interfaces with other Microsoft
Dynamics AX 2012 modules.

FIGURE 7.5 ACCOUNTS PAYABLE INTEGRATIONS

The Accounts payable module handles vendor-related transactions. The primary


focus of the module is to keep track of invoice approval and payment processing.

Trade agreements (terms and conditions) made with vendors are registered and
maintained with the Inventory and warehouse management module. Expected
purchases can be forecast and used in master planning.

When a purchase order invoice is recorded, the information is passed to the


Accounts payable module that administers invoice approval and payment
processing.

The General ledger module keeps track of all company financial transactions.
All vendor financial movements are replicated in the General ledger module.

Payment transactions are recorded in the Cash and bank management module
that controls the company’s bank accounts.

The data model for vendors and vendor transactions resembles the customer data
model. Therefore, the data model for vendors is not reviewed. The primary
difference between the data models is that the vendor data model tables begin
with Vend... and the customer data model tables begin with Cust.

7-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Free Text Invoices


The Accounts receivable module has its own invoice function. Although sales
order invoices are integrated with the Inventory and warehouse management
module, free text invoices are not related to inventory items.

This lack of integration makes the use of free text invoices simpler and creates
fewer database records. Therefore, free text invoices are a good option when
integration to other functions is required.

Implementing free text invoices as the primary invoice engine will typically
require some additional programming, because the standard application only
handles basic scenarios.

Free text invoices in Microsoft Dynamics AX 2012 introduce a new recurring


free text invoice feature. With recurring free text invoices you can create
templates that are linked to one or more customers to be invoiced at set intervals.
Then you can run a simple job to create the invoice, and another job to post the
invoices. A new corrections feature and workflow for free text invoices is also
introduced. Additionally, the free text invoice includes source document support
and subledger journal distributions.

Free Text Invoice Data Model


A free text invoice is an invoice that is not attached to a sales order. A free text
invoice contains a header and one or more lines for items or services that are not
tracked in inventory. Use a free text invoice for sales that do not require a sales
order and packing slip. For example, you can use a free text invoice for a
consulting fee or services fee, or for a miscellaneous fee for an event
reimbursement.

7-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the free text invoice data-model.

FIGURE 7.6 FREE TEXT INVOICE DATA MODEL

The CustInvoiceTable contains invoice headers, whereas CustInvoiceLine


contains details about invoice lines. When an invoice is posted, its information is
copied to the invoice journal with the header in CustInvoiceJour and the lines in
CustInvoiceTrans.

CustInvoiceJour and CustInvoiceTrans also contain invoices posted in the Sales


and marketing module. The invoice report is shared with the Sales and
marketing module. This means that the journal and the invoice report already
contain quantity and price fields.

TIP: Project related invoices go into the ProjInvoiceJour and ProjInvoiceTrans


tables instead of the CustInvoiceJour and CustInvoiceTrans tables.

The CustRelatedInvoice table contains the relationship between the original,


parent, corrected and adjusting invoice.

Printing setup and copies can be specified individually for each customer. This
setup can be overridden in a specific Free Text Invoice. The setup is included in
the tables PrintMgmtDocInstance, PrintMgmtSettings and
PrintMgmtIdentificationText.

7-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Recurring Free Text Invoice Data Model


The following figure shows the recurring free text invoice data model.

FIGURE 7.7 RECURRING FREE TEXT INVOICE DATA MODEL

Each free text invoice template record is stored in the CustInvoiceTemplate table.
The lines of the templates are stored in the CustInvoiceLineTemplate table. Each
free text invoice template must be linked to one or more customers. The
CustRecurrenceInvoice table contains the information about the templates that
are assigned to a customer. One template can be assigned to multiple customers,
and each customer can have multiple templates assigned.

Periodically, you must run the Generate recurring invoices job to create the
recurring free text invoices for each customer. When the job runs the
CustInvoiceTemplate table records are copied into the CustInvoiceTable as a
standard free text invoice. The lines are copied from the
CustInvoiceLineTemplate table to the CustInvoiceLine table.

Every time that the Generate recurring invoices job is run, a new record is
inserted into the RecurrenceInvoice table. This record serves as a batch or
"journal" header type record for the free text invoices that are created. The
CustRecurrenceInvoiceGroup table contains information about each of the free
text invoices that are created from the batch.

When the recurring free text invoices are posted, the transactions are copied to
the CustInvoiceJour and CustInvoiceTrans tables in the same manner that a
regular free text invoice is processed.

7-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

CustPostInvoice Classes
CustPostInvoice

The CustPostInvoice class handles the posting of a single free text invoice
specified by one record in the CustInvoiceTable and one or more records in the
CustInvoiceLine.

The posting includes the generation of the following data.

• Ledger transactions by using the LedgerVoucher class.


• Customer transactions by using the CustVoucher class.
• Tax transactions by using the CustInvoiceCalcTax class.
• Invoice journal and lines (CustInvoiceJour and -Trans).
• Printing of the invoice report by using the FormLetter framework
classes.

CustPostInvoiceJob

The CustPostInvoiceJob class handles the selection of which records in the


CustInvoiceTable to post. It also handles the printing of the invoices if it is
specified. The class extends from the RunBase-framework.

Vendor Invoices
Invoices can originate from purchase orders. However, if an invoice is created in
another system, or for products and services that are not recorded in a purchase
order, then it can be recorded manually in Microsoft Dynamics AX, by using the
General journal or an Invoice journal in the Accounts payable module. When
you manually enter a vendor transaction and specify a vendor account and an
invoice number, the transaction will be recorded as an invoice.

The company receives invoices from its vendors. To make sure that received
invoices are correct and valid, incoming invoices are typically sent through an
approval workflow.

It is important to register invoices as quickly as possible. You do this with a


status that displays that the invoice is awaiting approval. This status is changed
when the invoice is approved.

Invoicing Methods
Purchase Order Invoicing

A vendor invoice for a purchase order is an invoice that is attached to a purchase


order. It contains a header and one or more lines for items or services. A vendor
invoice finishes the purchase order, product receipt, and vendor invoice cycle.
You can also enter vendor invoices that are not associated with purchase orders.

7-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Invoice Journal

The procedure for handling invoices varies from company to company,


depending on the company's size, structure and organization. The invoices are
typically one of the following:

• Registered
• Approved
• Paid

Consider the following about Microsoft Dynamics AX.

• It supports several methods of managing incoming invoices to cater


to different company procedures.
• It has a different invoice journal depending on the need of the
company.

The following types of invoices are available.

• Invoice Register
• Invoice Approval Journal
• Invoice Pool excluding Posting
• Invoice Journal

Invoice Journal Types


Invoice Register

The purpose of the invoice register journal is to pre-register invoices when they
arrive at the company and transfer them to an invoice pool for approval. In the
invoice register journal, an employee registers the following information.

• Vendor account
• Invoice number
• Amount
• Person who approves the invoice

The same employee validates and posts the journal to the accounts specified in
the posting profile. Usually the accounts are pending accounts where the amounts
require the manual approval and reclassification by the person specified in the
journal line.

7-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Invoice Approval Journal

After you post the lines of the invoice register, the postings display in the invoice
pool. To view the postings in the invoice pool click Accounts Payable, click
Inquiries, and then click Invoice pool.

The following applies to the invoice pools.

• The invoice pool displays the relevant information about the invoices
awaiting approval.
• The invoice pool holds invoices originating from a purchase order
that originate from an invoice register. Click the Purchase order
button to select and approve the purchase orders.

Vendor Invoice Pool Excluding Posting Details

Invoice pools excluding posting have the following characteristics:

• The invoice register excluding posting is another kind of journal


available in the Accounts payable module.
• By using the invoice journal represents another procedure for
handling incoming invoices, although it resembles the invoice
register with posting. The difference is that you cannot post the lines.
The lines go directly into the invoice pool.
• To post the lines, create a new invoice journal, and then click
Functions. Select Invoice pool and accept the individual invoices in
the pool after you approve them.
• If you activate the invoice pool by accessing the invoice pool
exclude posting item in the Accounts Payable menu, the invoices
shown on the window are registered, unapproved invoices. Although
the invoices are unposted, they are registered in the system.
• Use the invoice journal to transfer the invoices for approval and
posting.

Invoice Journal

A third option for processing incoming invoices is to enter them directly into the
invoice journal.

• By default, the user who is logged on and enters the journal lines
approves the invoices.
• The invoice journal is designed for users to enter the invoices they
receive from vendors without entering them into the approval
journal. As soon as the user enters the incoming invoices, the user
can post.

7-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Invoice Journal Data Model


Invoice journals use the LedgerJournalTable and LedgerJournalTrans tables in
the same manner that a general journal is created. The posting logic is also
handled through the LedgerJournalCheckPost framework. However, there are
small differences in the validation that occurs for an invoice journal versus a
general journal. For this reason the details of the data model and posting
framework are not reviewed here. For more information about the journal and
posting framework, refer to the Use and Design of the Ledger Module chapter in
this course.

Payments
The collection of customer payments and generation of vendor payments is one
of the most important tasks in the finance process. They control the flow of cash
into and out of your business.

If you do not receive payments from your customers, you might not have cash to
make payments to vendors and keep your business running. Similarly, if you do
not make payments to your vendors for the items that you purchase, your vendors
could stop sending you items that keep your business running.

Before any payments can be made or received, several system setups must be
completed. Most of the payment setup is shared between the Accounts
receivable and Accounts payable modules, and there are many similarities in
the processing of payments for each module.

Payment Set Up
Microsoft Dynamics AX offers extensive functionality for setting up different
vendor payment options. These global payment options are used in the Accounts
payable and Accounts receivable modules, and include the following.

• Payment schedules: Use payment schedules to pay invoices in


installments. You must define the following to set up a payment
schedule.
o Number of installments
o Amount of each installment
o Due date of each installment

• Payment days: Use payment days to define the payment day used
for calculating the due date. The due date always is rounded up to the
nearest specified date. Payment days can be specified for one of the
following.
o Day in the week
o Day in the month

7-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Terms of payment: Use a term of payment for the calculation of a


due date based on the date of the invoice.
• Cash discounts: Use cash discounts to accrue and reward discounts
if a company meets the vendor payment terms on time, or give them
to customers when they pay their invoices in a specified period.
• Payment fees: Use payment fees to specify if any additional charges
are added to the vendor invoice. For example, a vendor might add a
fee for issuing a promissory note or a company might be charged a
vendor bank remittance fee.
• Methods of payment: Methods of payment are used to define how
payments should be summarized and posted. Many companies offer
several methods to pay due invoices, such as the following.
o Credit
o Cash in advance
o Bill of exchange
o Check and electronic payments

7-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Payment Set Up Data Model


The following figure shows the data model for setting up customer payment
information.

FIGURE 7.8 PAYMENT SET UP DATA MODEL

VendPaymFormat contains payment formats that are selected by using the Setup
button on the File formats tab page (in the form used for setting up payment
methods).

VendPaymModeTable contains defined payment methods. These include related


file formats that are represented by an ID of the class implementing the format.
Each payment method can be related to other information.

7-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

VendPaymMethodVal contains validation rules for the payment method. It


determines which information should be specified to process the payment.

VendPaymModeSpec contains specifications of different record formats in the


file that is used for requesting payments (Export format).

VendPaymModeFee specifies fees related to the payment method. The different


kinds of fees that include the setup of ledger postings are set up in the table
VendPaymFee. VendPaymModeFeeInterval specifies fee amounts as a function
of the number of days between a remittance and a bill of exchange’s due date.

Similar tables that begin or end with Cust are used for customer payment set up.
The following tables are shared between Accounts receivable and Accounts
payable.

• PaymSched and PaymSchedLine: These tables are used to store the


payment schedules. Payment schedules can be linked to terms of
payments, customers, or vendors.
• PaymDay and PaymDayLine: These tables are used to store
payment days. Payment days can be linked to terms of payment,
customers, or vendors.
• PaymTerm: This table stores each of the terms of payment. Terms
of payment can be linked to customers or vendors.
• CashDisc: This table is used to store the definition of cash discount
terms. Cash discounts can be linked to customers or vendors.

Customer Payments
Request Payments

Some companies request customer payment by submitting electronic information


to a bank. This requires agreement with the customer, because payments are
drawn automatically without the customer’s individual approval.

Banks typically respond with corresponding electronic information, specifying


whether the individual payments are processed or canceled.

This automatic approach to customer payment is typically used by companies


with high sales volumes to regular customers, such as subscriptions.

Payment Journals

Payment registration is one of the Customer module’s main tasks. The payment
journal, a variant of the general journal used in the General ledger module, is
used to register customer payments. You can do this manually by entering
information into the payment journal.

7-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Some companies receive payment information electronically from banks. This


requires that customer invoices contain payment information that must be
attached to the customer’s bank payment. This payment information, when it is
received by the company from the bank, is imported to the same kind of journal
that is used for manual payment entry.

Key tasks related to payment registration are to match invoices with their specific
payment, and to recognize outstanding invoices to be able to calculate interest
charges and submit collection letters. By doing this, the electronic payments
received from the bank, should settle and pay the appropriate invoices. Some
payments have related fees that customers should pay to the bank. Registration of
these fees is an integrated part of payment registration.

Vendor Payments
Payment Proposal

Open vendor invoices are reviewed periodically to select specific invoices to pay.
You do this by entering the payments in a journal with the specifications for
those invoices that will be settled. The Accounts payable module includes a
function for automatic proposals of those invoices that have to be paid.

When the payment proposal is reviewed and approved, payments are then
typically generated. The payment generation process is different, depending on
the method of payment. For check payments, a physical check must be printed
and mailed, whereas other types of payments require the generation of a file that
is transferred electronically to a bank.

Payment Journals

Payment registration is usually performed by posting the payment proposals


entered in the journal.

Some banks deliver a response to electronic payments as a receipt. Delaying


journal posting until arrival of the bank receipt is optional.

7-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Payment Journal Data Model


The following figure shows the data model for the customer payment journal.

FIGURE 7.9 PAYMENT JOURNAL DATA MODEL

LedgerJournalName contains different journal names, based on how they are set
up in the General Ledger module. Each journal name is related to one specific
type of journal. One of the journal types is customer payments.

LedgerJournalTable contains records that are headers for individual journals. A


new record is created in this table every time that the user creates a new journal
in the form that displays the list of journals.

LedgerJournalTrans contains individual journal lines. Each payment can have


related fees.

The fees are stored in the CustVendPaymJournalFee table. Each payment fee can
generate a new record in LedgerJournalTrans that will contain the fee. To post
payment fees, this design uses the usual ledger journal posting. Fee transactions
cannot be viewed or edited in LedgerJournalTrans, because this is replicated
from the information in CustVendPaymJournalFee.

7-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

When a payment is entered in the journal, the desired transaction settlement can
be specified when it is posted. The settlement is stored in the SpecTrans table,
and will be reflected in the CustSettlement table when the journal is posted. Each
record in SpecTrans defines a settlement between a line in the payment journal
and an open transaction part in CustTransOpen. SpecTrans can contain
information other than settlements from the customer payment journal. The same
table is used for other settlement specifications in the Customer and Vendor
modules.

The CustVendPaymProposalLine table contains the payments that are proposed


by the payment proposal creation and edit processes. The payment proposals are
removed from this table at the end of the process, and inserted into the
LedgerJournalTrans table.

CustInPaym Class
The CustInPaym class forms a framework for the import of payments from
customers. The file is typically received from the company bank. The function
involves reading the file and creating a new journal that contains the payments.
The information in the received file will usually contain a reference to the
invoice covered by the payment, and the import should make a settlement against
the open invoices while generating the payment journal.

When a payment method is set up, it can be related to an import file format. This
function will display all classes extending from CustInPaym.

CustOutPaym and VendOutPaym Classes


The CustOutPaym and VendOutPaym classes form a framework for exporting
payment information to a file. This file is typically sent to the company bank for
processing.

CustOutPaym is used to generate a file of payments to be collected from the


customers. This typically requires a form of agreement with the customer and the
banks involved.

VendOutPaym is used to generate a file of payments to be sent to the vendors.

CustOutPaymRecord and VendOutPaymRecord

The files generated can contain different types of records to handle several ways
of processing the payment. The individual types of records in the file are
implemented by creating a class extending from
CustOutPaymRecord/VendOutPaymRecord. If multiple record types will be
implemented, they should be implemented as extensions from one root class
extending from CustOutPaymRecord/VendOutPaymRecord.

This root class is associated to the class extending from


CustOutPaym/VendOutPaym by overriding the method
custVendOutPaymRecordRootClassId.

7-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following classes form a tutorial that displays an implementation of an


arbitrary format.

• VendOutPaym_Format1
• VendOutPaymRecordFormat1
• VendOutPaymRecordFormat1Spec1
• VendOutPaymRecordFormat1Spec2

You can make a duplication of these classes, when you implement a new specific
format.

CustPaym and VendPaym

The details of a payment can be retrieved from many tables in the Vendor
module. The VendPaym class contains a payment’s consolidated information. All
information is available by calling corresponding methods. The methods can be
grouped into three categories.

• The first group of methods describes payment senders (the company


exporting payments). All these methods have the prefix “senders.”
• The second group of methods describes payment receivers. All these
methods have the prefix “receivers.”
• The last group of methods describes payments. All these methods
have the prefix “paym.”

CustVendCreatePaymJournal Class
The CustVendCreatePaymJournal class is used to generate journals with
payments or journals handling bills of exchange and promissory notes.

The class searches for open invoices that will be paid by using a cash discount
and due date criteria. The data fetched is controlled by a query on the
CustTransOpen/VendTransOpen table and the payments generated are saved in a
ledger journal (LedgerJournalTrans).

The generated journal can be exported to a file by using the Cust-/VendOutPaym


classes described earlier.

CustVendSettle Class
The CustVendSettle class handles the update of a settlement between an invoice
and a payment. The processing is complex because the settlement can include
some of the following tasks.

• Read open transaction editing information in SpecTrans table


• Calculation and posting of cash discount
• Reversal of posted tax on cash discount
• Calculation and posting of conditional tax

7-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

• Calculation and posting of exchange rate adjustment


• Handling of over/underpayment
• Update information in CustSettlement/VendSettlement
• Centralized Customer /Vendor payments

The processing is automatically activated when you post customer or vendor


transactions in the ledger journal.

If the journal transaction is created by X++ the open transaction editing can be
controlled by creating records in SpecTrans as illustrated earlier. Suppose that the
amount in the journal transaction must be settled against a specified tableId
(Cust-/VendTransOpen) and recId. The following method will create the
information in SpecTrans.

protected void createSpecTrans(


LedgerJournalTrans _ledgerJournalTrans,
TableId _tableId,
RecId _recId)
{

SpecTransManager specTransManager;
;
specTransManager =

SpecTransManager::construct(ledgerJournalTrans);

specTransManager.insert(_ledgerJournalTrans.DataAreaId,
_tableId,
_recId,

_ledgerJournalTrans.amount(),

_ledgerJournalTrans.CurrencyCode);

If the task is to settle several open transactions without creating a new


transaction, you can do this by using the following code sample.

SpecTransManager specTransManager
CustTable custTable;
CustTransOpen custTransOpen;

specTransManager = SpecTransManager::construct(custTable);

specTransManager.deleteAll();

custTransOpen = …;
specTransManager.insert(custTransOpen.DataAreaId,

custTransOpen.tableId,

7-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

custTransOpen.recId,

custTransOpen.AmountCUR,

custTransOpen.custTrans().currencyCode);

custTransOpen = …;
specTransManager.insert(custTransOpen.DataAreaId,

custTransOpen.tableId,
custTransOpen.recId,

custTransOpen.AmountCUR,

custTransOpen.custTrans().currencyCode);

CustTrans::settleTransact(custTable);

This resembles the manual transaction editing that can be controlled by the end-
user.

7-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Lab 7.1 - Export Vendor Payments


This lab demonstrates how to use the framework to implement a specific file
format related to the exchange of payment information between the company and
their bank.

This lab is designed for self-study. Completing this lab takes approximately 45
minutes.

Scenario

The solution should contain a function for exporting payments to a file. The file
should contain one record for each payment, and the records should have a fixed
length.

The file can consist of two kinds of records. One record is used for bank transfers
and another record layout is used for checks.

The length of each record is 198 bytes. Each record is separated by Carriage
Return Line Feed (CR LF). The total size of the file is 200 bytes for each
transaction.

The record layout for a bank transfer is as follows.

Field Description Start End Length


Type 001 1 3 3
Bank Reg. Bank Registration (routing) ID 4 7 4
Bank Acc. Bank account number 8 17 10
Payment Payment identification 18 37 20
ID
Date YYYYMMDD 38 45 8
Currency ISO 46 48 3
Amount 2 decimals, no separator, right 49 63 15
adjusted, zero fill
Filler Spaces 64 198 135

7-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The record layout for a check payment is as follows.

Field Description Start End Length


Type 002 1 3 3
Name Name of receiver 4 33 30
Address 1 Address line 1 34 63 30
Address 2 Address line 2 64 93 30
Address 3 Address line 3 94 123 30
Reference Payment reference 124 143 20
Date YYYYMMDD 144 151 8
Currency ISO 152 154 3
Amount 2 decimals, no separator, right 155 169 15
adjusted, zero fill
Filler Space 170 198 29

Technical Issues
VendOutPaym

The VendOutPaym class defines the framework used to implement individual


formats for exporting vendor payments.

All classes extending from VendOutPaym will be available when you set up
export formats related to payment methods.

The extension should implement the following methods.

• interfaceName
• open
• close
• custVendOutPaymRecordRootClassId
• dialog
• pack
• unpack
• validate
• ::description (Scope resolution operator determines the method is
static)

The interfaceName method should return a string (type PaymInterfaceName) that


describes the format. The method is used in the user interface to represent the
payment method. Use the following code sample to guide you.

7-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

The open method should initialize data member files that are defined in the super
class. Use the following code sample to guide you.

public PaymInterfaceName interfaceName()


{
return "AXA export";
}

public void open()


{
file = CustVendOutPaym::newFile(filename,
this.codepage());

if (!file || file.status() != IO_Status::OK)


{
throw error(strFmt("@SYS73665",filename));
}
file.outFieldDelimiter('');
file.outRecordDelimiter('\r\n');
}

Codepage

Codepage is a list of selected character codes in a certain order. Codepages are


usually defined to support specific languages or groups of languages that share
common writing systems. For example, codepage 1252 provides character codes
required in the Latin writing system.

The LocalCodePage macro lists code pages defined.

private int codepage()


{
#Localcodepage
;
return #cp_1252;
}

The close method is called when all payments are exported to the file. If the last
record should be followed by a record delimiter, then an additional empty call to
file.write() can be included in this method. The method can also send information
to the created file’s infolog.

The custVendOutPaymRecordRootClassId method returns the ID of the root


class implementing the different record types. This class is described in the
following text. Use the following code sample to guide you.

classId custVendOutPaymRecordRootClassId()
{
return classNum(VendOutPaymRecord_AXA);
}

7-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The dialog method is overridden to specify those fields to include in the dialog
box. If the only field is the name of the file, then the method should be such as
this.

protected Object dialog(DialogRunbase _dialog = null,


boolean _forceOnClient
= false)
{
DialogRunbase dialog;
;

dialog = super(_dialog, _forceOnClient);

this.dialogAddFileName(dialog);

this.dialogAddPrintDocument(PaymDocumentType::ControlReport
,
dialog,
true);
return dialog;
}

Notice that the method also adds functionality to print a control report.

The pack and unpack methods should be implemented by using the usual
contents. The CurrentVersion and CurrentList macros are defined in the super
class.

The validate method should, as a minimum, contain validation of the specified


file name.

The method, ::description is a static method that returns the same information as
the object method interfaceName. The following is a sample of this method.

client server public static ClassDescription description()


{
return new VendOutPaym_AXA().interfaceName();
}

VendOutPaymRecord

The VendOutPaymRecord class defines the framework for implementing


individual record types in an export file.

Each payment format extending from VendOutPaym should be associated with a


class extending from VendOutPaymRecord. Each record type is implemented as
an extension of the class that is specified as the root in the
custVendOutPaymRecordRootClassId method described earlier.

You can use “abstract” classes in the hierarchy with the purpose of sharing code
between some record formats. The rule is that you should only implement the
interfaceName method on classes that implement an actual record type.

7-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Each record type should implement the following methods.

• interfaceName
• checkValues
• output

The interfaceName method will return a string (type PaymInterfaceName) that


describes the type of record. The method is used in the user interface to represent
payment specification. An example of the method follows.

public PaymInterfaceName interfaceName()


{
return "Bank transfer";
}

The checkValues method implements record type validation. Among other


things, it verifies that mandatory information is present. If the validation fails,
then the method returns false and errors will be reported to the infolog. This is
achieved by using the usual “return checkFailed()” pattern.

The output method writes the record type to the file. You can do this by calling
file.write() or file.writeExp().

Both methods checkValues and output methods are called automatically for each
record to export. All information about the payment will be available through the
data member custVendPaym, based on the VendPaym class described in the
following text.

Implementation
Perform the following steps to export the vendor payments to a file of a fixed
length as it is specified in the “Scenario” section of this lab.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_07_01_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

1. Create a new class called VendOutPaym_AXA that extends the


VendOutPaym class. Implement the following methods as described
in the "Technical Issue" section of this lab. Use the code samples
provided in the sample file to guide you.
a. classDeclaration (declare variables as required for the class)
b. interfaceName
c. open
d. close
e. custVendOutPaymRecordRootClassId
f. dialog

7-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

g. pack
h. unpack
i. validate
j. description

2. Create a new class called VendOutPaymRecord_AXA that extends


the VendOutPaymRecord class. This class should override the
checkValues method and contain logic to validate that the payment
specification is entered, and that credit amounts are not allowed.
3. Create two new classes that extend the VendOutPaymRecord_AXA
class. The first class is for checks, and the second class is for bank
transfers. Each class should implement the following methods.
a. interfaceName
b. output (This method should build the fixed length string as
defined in the "Scenario" section of this lab.

4. To test the implementation, complete the following steps.


a. Create a new method of payment that uses the new export
format.
b. Create two payment specifications and relate them to the
corresponding classes.
c. Create a new payment journal.
d. Export the payments.

TIP: You can import the AX2012_ENUS_DEVIV_07_01_LAB_SOL.xpo file to


verify and compare your solution.

Test
To test the implementation, complete the following steps.

1. Create a new payment method by using the path Accounts payable


> Setup > Payment > Methods of payment.
a. Specify the account type (Bank)
b. Set the payment account (USA OPER).

2. Click the Setup button on the File formats FastTab. Locate the new
AXA export format in the list of available formats and move it to the
left (Selected). Close the form. Select the file format in the Export
format field on the File formats tab page and save the record.
3. Click the Payment specification button and create two records
related to the two record formats (Bank transfer and Check)
implemented. Remember to specify the Export format for each
record type. Close the forms.

7-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

4. Create a new payment journal by using the path Accounts payable >
Journals > Payments > Payment journal. Open the journal lines
by clicking Lines.
5. Create a payment for vendor, “8500” with a debit amount of 766.50
using the United States dollar (USD). Specify the payment method
and record format in the Method of payments and Payment
specification fields.
6. Manually create another payment for vendor “8500” with a debit
amount of 474.86 USD. Specify the payment method and record the
format in the Method of payments and Payment specification
fields. Select the other record format compared to the line earlier.
7. Click the Functions > Generate payment button and select the
implemented Export format in the dialog box. Click the Dialog
button and specify the name of the file to be generated. Specify the
bank account “USA OPER”.

NOTE: You will receive an error about credit amounts when you generate the
file. This error is expected, because you added validation to check for credit
amounts. To correct the error you can change the credit amount in the journal
line to a debit amount and then generate payments again.

TIP: If you want to repeat the test, set the status of the lines back to None by
selecting Payment status and clicking the None button.

Collections and Interest


The account statement provides credit to customers on invoices. Customers
usually receive periodic account statements.

If account statements are to specify those invoices that are outstanding, then
transaction open-editing must be up to date. Account statement printouts are
followed by a reconciliation to make sure that they are correct.

When customer invoices are overdue, reminders could be in order. Submitting


collection letters is a supported process that includes the status registration of
individual open invoices, and typically involves the progression through
predefined steps. Submission of a collection letter frequently includes a related
fee to be paid by the customer.

An alternative to submitting collection letters is the calculation of interest on


unpaid invoices. This is usually done periodically. The calculated interest can be
printed on an interest note that is submitted to the customer. The interest note can
also have a related fee to be paid by the customer.

7-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Interest Data Model


The following figure shows the data model covering setup and the calculation of
interest.

FIGURE 7.10 INTEREST DATA MODEL

The CustInterest table defines the different interest codes that have the related
specification of the interest calculation that includes the percentages and accounts
that are used for posting.

The interest code used for each customer is determined by the posting profile that
can be accessed by the path Accounts receivable > Setup > Posting profiles >
Setup.

The CustInterestFee table is used to specify a fee that will be included in the
interest calculation. The reason for this separate table is the need to specify a
specific fee for each currency. The table is also used to specify a minimum
interest that should be calculated. The CustInterestRange table contains
information about the interest that is applicable by the ranges of an overdue
balance or the time on the customer transactions and is specific to a customer
currency.

Each calculated interest note has a header in the CustInterestJour table. The
calculation is specified in CustInterestTrans that contains a record for each
original transaction that has contributed to the interest calculation.

7-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Even though the relation between CustTrans and CustInterestTrans is not


specified on an extended data type or as a relation on the CustInterestTrans table,
there is a conceptual relation between the two tables.

The printing and posting of the interest note updates information in the
CustInterestJour. When the interest is posted one or more new interest
transactions are created in the CustTrans table.

The CustInterestWriteOffUnPostedJournal journal is used when write-off


transactions are created in the Collections form.

The CustInterestVersion and CustInterestVersionDetail tables contain the


versions of interest codes that are charged and paid.

CustInterestCreate and CustInterestPost Classes


The CustInterestCreate class handles how to create an interest note. The class has
two important methods.

• checkOpenTrans
• checkSettlement

They evaluate whether an open or closed transaction should be included in the


interest calculation.

The CustInterestPost class handles the posting of an interest note. This includes
the creation of ledger and customer transactions.

Bills of Exchange
A bill of exchange, also known as a draft, is an instrument used to administer
agreements to make payments. The document is created by the selling company.
However, it resembles a check written from the buyer to the seller.

Administration of bills of exchange can be divided into the following steps.

• Draw
• Protest
• Redraw
• Remittance
• Settlement

Separate journals for each step handle registration. These different kinds of
journals are collected in the submenu Journals > Bills of exchange.

7-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Draw

This step creates the document. Invoice transactions are selected when you enter
information into the journal.

When the journal is posted, the customer transaction that originated the invoice,
is settled and replaced by a new, open transaction represented by the bill of
exchange.

Protest

A bill of exchange is created by the selling company. A buyer can protest the bill
of exchange if he or she does not accept it.

For a protest, the transaction representing the drawn bill of exchange is selected
when you enter the information into the journal. When the journal is posted, the
bill of exchange’s status is changed from Drawn to Protested.

The customer transaction that originated the drawn bill of exchange is settled and
replaced by a new, open transaction represented by the protested bill of
exchange.

Redraw

A protested bill of exchange can be re-drawn.

To do this, the transaction representing the protested bill of exchange is selected


when you enter the information into the journal. When the journal is posted, the
bill of exchange’s status is changed from Protested to Redrawn.

The customer transaction that originated the protested bill of exchange is settled
and replaced by a new, open transaction representing the redrawn bill of
exchange.

Remittance

One of the purposes of bills of exchange is for sellers to use them to obtain bank
credit.

The transaction representing the drawn or redrawn bill of exchange is selected


when you enter the information into the journal. When the journal is posted, the
bill of exchange’s status is changed from Drawn/Redrawn to Remitted.

The customer transaction that originated the drawn or redrawn bill of exchange is
settled and replaced by a new, open transaction representing the remitted bill of
exchange.

7-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Settlement

Final settlement of a bill of exchange ends the payment workflow. This step
represents the customer’s final payment of the invoice that is the basis for the bill
of exchange.

The transaction representing the remitted bill of exchange is selected when you
enter the information into the journal. When the journal is posted, the status of
the bill of exchange is changed from Remitted to Honored.

The customer transaction that originated the remitted bill of exchange is settled
and replaced by a new, open transaction representing the honored bill of
exchange.

Promissory Notes
A promissory note is an instrument used to administer agreements to make
payments. The document is created by the buying company and states that the
buyer has agreed to make a payment in the future.

Administration of promissory notes can be divided into the following steps.

1. Draw
2. Redraw
3. Remittance
4. Settlement

Each of the steps are handled and registered by using a journal dedicated to each
step. The different kinds of journals are collected in the submenu Journals >
Promissory notes.

Draw

This step creates the document. Invoice transactions are selected when you enter
information into the journal.

When the journal is posted, the customer transaction that originated the invoice is
settled and replaced by a new, open transaction represented by the promissory
note.

Redraw

A settled promissory note can be re-drawn.

The transaction representing the honored promissory note is selected when you
enter the information into the journal. When the journal is posted, the promissory
note status is changed from Honored to Redrawn.

7-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The vendor transaction that originated the honored promissory note is settled and
replaced by a new, open transaction representing the redrawn promissory note.

Remittance

A drawn or redrawn promissory note can be remitted.

The transaction representing the drawn or redrawn promissory note is selected


when you enter the information into the journal. When the journal is posted, the
promissory note status is changed from Drawn/Redrawn to Remitted.

The vendor transaction that originated the drawn or redrawn promissory note is
settled and replaced by a new, open transaction representing the remitted
promissory note.

Settlement

Final settlement of the promissory note ends the payment workflow. This step
represents the vendor’s final payment of the invoice that is the basis for the
promissory note.

The transaction representing the remitted promissory note is selected when you
enter the information into the journal. When the journal is posted, the promissory
note status is changed from Remitted to Honored.

The vendor transaction that originated the remitted promissory note is settled and
replaced by a new, open transaction representing the honored promissory note.

7-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Lab 7.2 - Transfer Balances


This lab demonstrates how to update open transactions editing information
directly from X++.

Estimated time to complete: 45 minutes

Scenario

The business relations, used as vendors, and the customers, are recorded in the
accounts payable table. If the company is buying from and selling to the same
business relation, this will be created in both tables.

An invoice is usually settled by a payment, but when buying from and selling to
the same business relation, the invoices from the purchase and sales order could
be set off one another.

A new function should find customers and vendors related to one another (the
same business relation). If both the customer and vendor have open invoices,
they should be set off one another. Only invoices in the same currency can be
settled against one another.

Implementation
To find and settle customer and vendor open invoices of the same currency,
follow these steps.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_07_02_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

1. Import the project AX2012_ENUS_DEVIV_07_02_LAB.xpo. The


project contains a framework for the class
AXACustVendTransferBalance.
2. Do not be concerned about the dialog and so on. This is already
implemented so that you can focus on the Accounts receivable and
Accounts payable modules.
3. Implement the method run, to find and create the settlements. For
each customer who has a related vendor, follow these steps.
a. Find an open customer transaction and calculate the remaining
amount.
b. Find an open vendor transaction with the same currency and
calculate the remaining amount.
c. Calculate the settlement between the two transactions as the
minimum amount of the two.
d. Create two lines in a ledger journal and update the related
settlement specifications.

7-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

TIP: You can import the AX2012_ENUS_DEVIV_07_02_LAB_SOL.xpo file to


verify and compare your solution.

Test
To test the implementation, follow these steps.

1. Create a reference between customer 3001 and vendor 3004, by


using the path Accounts receivable > Customers > All customers
in the Vendor account field on the Miscellaneous details FastTab
in the Customer details form.
2. Create a number sequence by using the path Organization
administration > Common > Number sequences > Number
sequences. This number sequence should not be marked as manual,
but is should be marked as continuous.
3. Create a journal name by using the path General ledger > Setup >
Journals > Journal name. The journal type should be daily, and
select the number sequence that you created in step 2 for the voucher
series.
4. Run the class by right-clicking selecting Open. On the dialog box, in
the Name field, select journal name that you created in step 3, and
select the number sequence that you created in step 2, in the
Voucher series field. Click OK.
5. To view the journal, open General ledger > Journals > General
journal. Select the journal number that was created in the infolog
message, and then click Lines. To view the settlements that were
created, click Functions > Settlement on each line, and then click
No to not remove the settlements.

NOTE: You may receive warnings that the number sequence you created does
not allow reservations. This message can be ignored.

TIP: If you want to repeat the test, you should delete the journal generated.

7-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Summary
The Accounts receivable module is used to track customer invoices and
incoming payments. The Accounts payable module is used to track vendor
invoices and outgoing expenditures.

The Accounts receivable module has functionality for free text invoices. Free
text invoices are useful because they are not related to inventory items and
provide a simple invoice mechanism.

The Accounts payable module uses invoice journals to process invoices that are
not related to inventory. The following types of invoice journals are available.

• Invoice Register
• Invoice Approval Journal
• Invoice Pool excluding Posting
• Invoice Journal

The collection of customer payments and the generation of vendor payments is


one of the most important tasks in the finance process. They control the flow of
cash into and out of your business. After the payment set up is complete, you can
use payment journals in both modules to propose, create, generate, and post
payments.

The Accounts receivable module offers functionality for collection letters,


interest notes, and bill of exchanges. The Accounts payable module offers
functionality to create and process promissory notes.

7-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Categorize the following items.

_____ 1. Used to make a payment on a specific a. Payment Schedules


day. b. Cash Discount
_____ 2. Used to pay invoices in installments. c. Terms of Payment
_____ 3. Used to calculate due dates of d. Payment Fees
transactions.
e. Method of
_____ 4. Used to add more charges to a Payment
transaction.
f. Payment Days
_____ 5. Used to define how payments are
summarized and posted.
_____ 6. Used to accrue and reward discounts
when payment terms are met.

2. What is the primary difference between free text invoices and sales order
invoices?

3. Which tables are used for vendor invoice journals?


( ) CustInvoiceTable and CustInvoiceTrans
( ) VendInvoiceTable and VendInvoiceTrans
( ) LedgerJournalTable and LedgerJournalTrans
( ) VendJournaTable and VendJournalTrans

4. Which of the following transactions are supported in the Accounts receivable


module for customers? (Select all that apply)
( ) Free text invoice
( ) Payment journals
( ) Promissory notes
( ) Bill of exchanges

7-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

5. Which of the following frameworks and classes are used by the free text
invoice generation process? (Select all that apply)
( ) CustVoucher
( ) LedgerVoucher
( ) CustInvoiceCalcTax
( ) FormLetter framework

7-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

7-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 7: Use and Design of the Accounts Receivable and Accounts
Payable Modules

Solutions
Test Your Knowledge
1. Categorize the following items.

f 1. Used to make a payment on a specific day. a. Payment Schedules


a 2. Used to pay invoices in installments. b. Cash Discount
c 3. Used to calculate due dates of transactions. c. Terms of Payment
d 4. Used to add more charges to a transaction. d. Payment Fees
e 5. Used to define how payments are e. Method of
summarized and posted. Payment
b 6. Used to accrue and reward discounts when f. Payment Days
payment terms are met.

2. What is the primary difference between free text invoices and sales order
invoices?

MODEL ANSWER:

Free text invoices cannot be related to inventory items, and sales order
invoices can be related to inventory items.

3. Which tables are used for vendor invoice journals?


( ) CustInvoiceTable and CustInvoiceTrans
( ) VendInvoiceTable and VendInvoiceTrans
(•) LedgerJournalTable and LedgerJournalTrans
( ) VendJournaTable and VendJournalTrans

4. Which of the following transactions are supported in the Accounts receivable


module for customers? (Select all that apply)
(√) Free text invoice
(√) Payment journals
( ) Promissory notes
(√) Bill of exchanges

5. Which of the following frameworks and classes are used by the free text
invoice generation process? (Select all that apply)
(√) CustVoucher
(√) LedgerVoucher
(√) CustInvoiceCalcTax
(√) FormLetter framework

7-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

7-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

CHAPTER 8: USE AND DESIGN OF THE SALES


AND PURCHASE MODULES
Objectives
The objectives are:

• Review the general features that are supported with sales and
purchase orders.
• Describe how sales and purchase orders integrate with other
modules,
• Discuss the primary tables used in the purchase order flow.
• Describe how the PurchType, PurchLineType, and PurchTotals
classes work.
• Describe how trade agreements are used and set up.
• Review the data model for trade agreements.
• Discuss how the trade agreement classes are used and can be
extended.
• Describe how sales and purchase agreements are used and set up.
• Review the data model for sales and purchase agreements.
• Discuss how the sales and purchase agreement classes are used and
can be extended.
• Describe how pricing policies are used.
• Describe how charges are used and set up.
• Review the data model for charges.
• Describe how the FormLetter framework is used.
• List the various documents that are processed through the
FormLetter framework.
• Describe the data model for updating documents.
• Describe how the FormLetter classes relate to each other and
generally work.
• Describe how to make modifications to the FormLetter framework.
• Describe the differences between the sales order and the sales
quotation features, data model, and classes.
• Describe the differences between the purchase order and the request
for quotation features, data model, and classes.
• Describe the differences between the purchase order and the
purchase requisitions features, data model, and classes.
• Explain how to use and set up categories and category hierarchies.
• Review the data model for categories and category hierarchies.

8-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Introduction
The sales and purchasing processes are important components of every business.
Microsoft Dynamics® AX 2012 provides functionality businesses can use to
manage purchase and sales information with the integration to inventory and the
general ledger.

The order to cash process is also referred to as the sales process, and involves
many steps. These steps include gathering leads and opportunities that drive the
creation of prospective customers, followed by the quotation process, and after
the quotation is accepted, generating confirmed sales orders. Next is the picking
and shipping of the products and then invoicing or billing the customer. After the
customer receives the goods payment must be collected.

Because every business has different processes the source to sell process steps
can be conducted differently, Microsoft Dynamics AX 2012 helps businesses
manage these processes that are usually controlled by the type of customer that
includes, business-to-business (B2B), business-to-customer (B2C) or by specific
business requirements.

The procure to pay process is also referred to as the purchase process, and it also
includes many steps, and is similar to the source to sell process. These steps
include requesting and qualifying a new vendor, submitting purchase requisitions
by employees requiring various products, followed by the request for quotation
process with the vendor. When the purchase requisitions and, or the request for
quotations are approved, purchase orders are generated and then confirmed with
the vendor. After the products are delivered, a product receipt is generated and
the invoice is recorded for the purchase order, and then payments must be
generated to the vendor.

This course introduces the features in Microsoft Dynamics AX 2012 that support
the sales and purchase processes, and it also reviews the data models and coding
patterns for many of the features. Since the customer and vendor data models and
coding patterns are similar, the details of both will not be discussed.

Sales and Purchase Orders


This topic introduces the primary features available for sales orders and purchase
orders in Microsoft Dynamics AX 2012. Additionally, the data models for sales
and purchases will be reviewed and the coding patterns for purchases will also be
discussed.

Sales Order Feature Overview


Sales orders in Microsoft Dynamics AX 2012 can be accessed from the
Accounts receivable module and the Sales and marketing module. Although
there are additional list pages and reports in each module that are different, the
basic sales order information that is available in each module is identical.

8-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

The primary components of a sales order consist of a header and one or more
lines. Each sales order header is linked to one specific customer account. Each
line of a sales order is linked to one specific item number or one specific sales
category. When a sales order line is linked to an item number, the category field
is defaulted based on the category assigned to the item. You can leave the item
number field blank, and select only a category.

Several types of sales orders exist and each has different functionality.

• Journal: Does not have any inventory transactions, and cannot be


processed. Most often it is used as a template or place holder for a
future sales order.
• Sales order: The standard sales order that does have inventory
transactions and can be processed.
• Subscription: Special sales order used for repeating, for example a
magazine subscription.
• Return order: Used when a customer is returning items previously
purchased on a sales order. The quantities on this order are always
negative.
• Item requirements: Special sales order used with the Project
management and Accounting module. These cannot be created
manually, and can only be generated from a project.

After a sales order is created and the customer, item or category, quantity, and
pricing information are entered, the order must be processed. The four steps to
process a sales order include the following.

1. Confirmation: The order entry process is completed and the details


are printed or emailed to the customers to "confirm" the order.
2. Picking list: A document called a picking list is generated for the
warehouse workers. The warehouse workers use this document to
find the required items in the warehouse and bring them to a
packaging or staging location for delivery. This is also referred to as
"picking" the items. When this process is completed, the inventory is
updated to show a status of picked so that the items cannot be used
on other sales orders.
3. Packing slip: A document called a packing slip is generated for the
delivery of the items. The warehouse workers will use this document
to verify the items that need to be packaged or delivered, and this
document is usually sent with the shipment to the customer. When
this process is completed, the inventory is updated to remove the
quantities from the on hand inventory.
4. Invoice: A document called an invoice is generated. When the
invoice is generated for a sales order, it is the final step of the sales
order process where the customer is effectively billed or "invoiced"
for the items that are delivered. This process creates an open
transaction on the customer’s account that must be paid for by the
customer.

8-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

As a sales order is processed, the status of the order is updated and the related
inventory transactions are simultaneously updated. Sales orders also support
other features such as the following.

• Support for multiple delivery addresses.


• Delivery schedules used to schedule one line for delivery on
different dates.
• Ability to override pricing and discount information at the line level.
• Options to add charges such as freight or installation fees.
• Functions to create a purchase order or a production order from a
sales order.
• Options for reserving inventory. A reservation of inventory on a
sales order ensures that the items will be available for delivery on the
date agreed upon with the customer.

Sales Order Integrations


The Sales module is used to keep track of sales activities. The following figure
shows the interface with other modules in Microsoft Dynamics AX.

FIGURE 8.1 SALES ORDER INTEGRATIONS WITH OTHER MODULES

8-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Purchase Order Feature Overview


Purchase orders in Microsoft Dynamics AX 2012 can be accessed from the
Accounts payable module and the Procurement and sourcing module.
Although there are additional list pages and reports in each module that are
different, the basic purchase order information that is available in each module is
identical.

The primary components of a purchase order consist of a header and one or more
lines. Each purchase order header is linked to one specific vendor account. Each
line of a purchase order is linked to one specific item number or one specific
procurement category. When a purchase order line is linked to an item number,
the category field is defaulted based on the category assigned to the item. You
can leave the item number field blank, and select only a category.

Unlike sales orders, a purchase order only has three order types
available―Journal, Purchase order, and Returned order. Additionally, when a
purchase order is processed, the steps include a confirmation that is similar to the
sales order confirmation, a receipts list, a product receipt, and an invoice.

A receipts list is a record of received items. The task is performed for physical
accepting of the goods. Products updated on a receipts list are still not physically
available.

A packing slip is the document that accompanies physical delivery. It describes


the contents of the delivery with the focus on the delivery’s physical
characteristics. Recording the packing slip is completed by registering a product
receipt from the vendor.

Purchase orders also support other features such as the following.

• Support for multiple delivery addresses.


• Delivery schedules used to schedule one line for delivery on
different dates.
• Ability to override pricing and discount information at the line level.
• Options to add charges such as freight or installation fees.
• Ability to create and acquire fixed assets on purchase order lines.
• Integration with planned purchase orders generated from the Master
planning module.

8-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The Purchase module is used to keep track of procurement activities. The


following figure shows the interface with other modules in Microsoft Dynamics
AX.

FIGURE 8.2 PURCHASE ORDER INTEGRATIONS WITH OTHER MODULES

8-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Purchase Order Data Model


The following figure shows the purchase order data model.

FIGURE 8.3 PURCHASE ORDER DATA MODEL

The PurchTable table holds a record for each purchase order, whereas the related
lines are stored in the PurchLine table. A purchase order is always related to a
vendor to whom the goods in the purchase order will be received from. A
different vendor account might be specified to receive the invoice.

8-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When there is a delivery schedule on a purchase order line, the PurchLine table
stores one record for each delivery date, and there is "master" record for the
original purchase order line. The LineDeliveryType field is used to determine
whether the line has a single delivery or multiple deliveries. When the value is
OrderLine there is only one delivery. When the value is
OrderLineWithMultipleDeliveries, the line is original order line that has a
delivery schedule attached. When the value is DeliveryLine, the line is one of the
scheduled deliveries.

Inventory dimensions for the purchase order lines, such as size, color, and
configuration, are saved in a separate table, labeled InventDim. The
InventDimId field creates the relationship between a purchLine and the record
holding dimension values. This design is used because it reduces the number of
indexes in tables holding inventory dimensions. The InventDim table has many
indexes related to individual inventory dimensions. All indexes in the InventDim
table can be used with the PurchLine table through a join between the two tables.
This join only requires one index (InventDimIdx) on the PurchLine. The
purchase order lines are always related to a record in the InventDim table, even if
all inventory dimensions have blank values.

Inventory transactions are used to store the status and history of the inventory
receipts and issues. Each purchase order line has one related record in the
InventTransOrigin table. Each InventTransOrigin record is related to one or more
InventTrans table records. By default the relationship between the
InventTransOrigin and the InventTrans is a one-to-one relationship. However,
when a delivery schedule exists on a purchase order line, multiple InventTrans
records are created. There are other scenarios, such as partial receipts and
invoices that can cause multiple inventory transaction records to be created.
Additionally, there are scenarios where inventory transactions do not exist, such
as purchase orders with the type of journal or purchase lines with products that
are not stocked, or purchase order lines that are category based.

8-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Purchase Order Classes


Microsoft Dynamics AX 2012 supports several different types of orders such as
journals, return orders, and purchase and sales orders. Each order type supports
different tasks and functionality. Instead of using many if-statements to separate
the functionality about the order type, the properties and methods are isolated on
the class hierarchies PurchTableType and PurchLineType. Sales orders use the
class hierarchies called SalesTableType and SalesLineType. The following figure
shows the PurchTableType class hierarchy.

FIGURE 8.4 PURCHTABLETYPE TYPE HIERARCHY BROWSER

The following figure shows the PurchLineType hierarchy.

FIGURE 8.5 PURCHLINETYPE TYPE HIERARCHY BROWSER

On the PurchTable and PurchLine an object method called type() is used to


construct the actual object.

Object methods such as insert(), update(), delete(), validateWrite(), and


validateField() are implemented on the classes. The object method on the table is
activated by the kernel. However, the call is redirected to the object constructed
by the object method type(). A modification to these methods should be
implemented on the classes instead of on the table object method.

The dataflow object method called initFrom…() is also implemented on the


classes.

8-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

If you must have a new property on an existing or new subclass of these


hierarchies, add the default property to the root class and override it on the
subclass in question.

To create a new order type, start by adding a new element to the purchase order
type base enumeration, and then create a new class that extends the
PurchTableType and PurchLineType classes. Add methods to the new class that
override the base methods in the PurchTableType and PurchTableLine classes.
Then you must modify the construct() method on the classes to call the
appropriate "type" class for each purchase order header and line.

As discussed earlier, a purchase order consists of a header and several purchase


order lines. The total amounts of the purchase order are not stored in the
database, instead they are calculated when the information is needed. This
approach makes data entry faster, but reporting and inquiries slower.

The totals of a purchase order are calculated by using the PurchTotals class. This
class extends TradeTotals which Extends TradeTotalsBased which are also used
for calculating sales totals.

The totals are calculated in relation to the inquiry from the purchase order, check
of the credit limit, update to an invoice, and so on. The scope of the calculation
can range from one single purchase order line to a summary of multiple purchase
orders.

This is handled by several subclasses to the PurchTotals class. The following


figure shows the PurchTotals class hierarchy.

FIGURE 8.6 PURCHTOTALS TYPE HIERARCHY BROWSER

The classes have many object methods returning several amounts such as order
balance, volume, weight, taxes, charges, and so on.

8-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Agreements
The Agreement framework offers users of Microsoft Dynamics AX a broad set of
tools for applying and following up on commercial agreements between the
company and its customers and vendors regarding of buying/selling a certain
quantity or/and volume of an particular item as well as a range of items within a
certain category with a special policies applied to achieve an agreed price for
trading goods and/or services.

The prices and discounts of the sales or purchase agreement overrule any prices
and discounts stated in any trade agreements that could exist.

You can specify the agreement commitment type on the purchase and sales
agreements. This controls what information is required on the agreements. The
commitment type also determines how the agreement is being managed to
determine when the commitment is fulfilled.

Trade Agreements
Prices of sold and purchase items should be maintained. Prices can be set up
specifically for individual items, customers, and vendors, or prices can be set up
for a group of customers or vendors, or for all customers as one group.

The price structure also includes line, multiline, and final discounts.
Administration of sales prices and purchase prices that includes publishing to the
organization and customers, is an ongoing task.

8-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Trade Agreements Data Model


The basic or default purchase price specified directly for the item is stored in the
InventTableModule table:

FIGURE 8.7 INVENTTABLEMODULE DATA MODEL

Purchase price information is stored in the following fields:

• Price
• PriceUnit
• Markup

Each item in InventTable has exactly three related records in InventTableModule


and one record each in InventItemPurchSetup, InventItemSalesSetup, and in
InventItemInventSetup tables.

8-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

The following figure shows the design of the purchase price and discount data
model.

FIGURE 8.8 PURCHASE PRICE AND DISCOUNT DATA MODEL

When more complex pricing is required, you can use Trade agreements to define
detailed pricing information for specific vendors, currencies, quantities, or date
ranges. Trade agreements allow you to set up purchase prices, line discounts,
multiline discounts, and total discounts. This is controlled by the Relation field
on the PriceDiscTable. Each specification in the price agreement table contains
item and vendor dimensions.

• Table: Specific item and vendor


• Group: Group of items and vendors
• All: All items and vendors

This creates up to nine different levels of specification. The search for a price or
discount must use a priority between the several combinations.

Item Group All


Vendor 1 2 3
Group 4 5 6
All 7 8 9

Price groups are used to create the groups of customer, vendors, or items that you
want to handle in the same way for prices. A separate price group can be created
for each type of pricing (prices, line discounts, multiline discounts, and total
discounts) and for each group of transactions (customers, vendors, and items).
Many different relations exist between the PriceGroup table and the
PriceDiscTable.

8-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

If no price is found in the PriceDiscTable the price specified in


InventTableModule is used.

You cannot change the information in PriceDiscTable directly. Instead, you must
create a price and discount journal and make the modifications in the journal.
When the journal is posted, the records are updated or created in PricDiscTable.

The PriceDiscTable is configured to Found caching in the standard application. It


can be relevant to change this setting, depending on the amount of data in the
table. The design of the price searches does not support found (single-record)
caching as it contains criteria on quantity and date intervals.

The following figure shows the design for the price and discount journal
function:

FIGURE 8.9 PRICE AGREEMENT JOURNAL DATA MODEL

The PriceDiscAdmName table contains the journal names that are defined in the
setup. PriceDiscAdmTable contains the header for each journal, whereas
PriceDiscAdmTrans contains the individual price agreements. If the journal line
is loaded from the existing agreements, then it will be related to the existing
record in PriceDiscTable (RecId).

8-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Trade Agreements Classes


The PriceDisc class is used to search for price and discount information. It is
activated from the Sales and Purchase module when a line is created or changed.
The prices are not recalculated during updates, so you have the opportunity to
make manual adjustments to the price and discounts on the individual sales line.

The search for information in the PriceDisc class is executed in the


findPriceAgreement() object method.

Price and discount agreement journals are posted by using the


PriceDiscAdmCheckPost class. The PriceDiscAdmAdjustment class is used to
select existing trade agreements and make changes to existing trade agreements.

Sales and Purchase Agreements


The agreement is a contract that commits the customer/vendor to buy/sell a
product in a certain quantity or amount over a period in exchange for special
prices and, or discounts with a specific customer/vendor. In previous versions,
you used the blanket order type in sales orders to set up these agreements.

The prices and discounts of the sales or purchase agreement overrule any prices
and discounts stated in any trade agreements that might exist.

You can specify the agreement commitment type on the purchase and sales
agreements. This controls what information is required on the agreements. The
commitment type also determines how the agreement is being managed to
determine when the commitment is fulfilled.

The agreement framework in Microsoft Dynamics AX 2012 includes the


following features.

• Ability to express in the system a contractual commitment of sale of


purchase for a specific amount of quantity of a certain item, category
or any item/category.
• Enforces price agreements on the purchases or sales when they’re
done according to agreement.
• Follow up on sales or purchases to see if the contractual obligations
have been fulfilled.

Sales and Purchase Agreement Data Model


In Microsoft Dynamics AX 2012 the agreement framework’s data model is
completely separated form general purpose order data model. This separation
helps to optimize data structure, because there is no need for entities stored in
database to carry properties that do not make sense for agreements.

8-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The agreement framework physical data model design uses the table inheritance
feature and implement all data sub-types needed by the framework and their
behavior deviations as a table inheritance ladder, encapsulating both data- and
functional- specializations within a single type of objects – AX Data Tables.
With that done the need for supporting class hierarchy behind the used data
tables was completely eliminated.

The following figure show the data model for purchase agreements.

FIGURE 8.10 PURCHASE AGREEMENT DATA MODEL

8-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Agreement Classifications
Agreement classifications are a required field on agreements. Classifications help
group agreements into different types. Functionality does not change with
different types. These values can be used for reporting and analysis.

Purchase agreement classifications are setup on the form at the following


location: Procurement and sourcing > Setup > Purchase agreements >
Purchase agreement classification.

The following figure shows the data model for agreement classifications.

FIGURE 8.11 AGREEMENT CLASSIFICATION DATA MODEL

8-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Agreement History
The agreement framework in Microsoft Dynamics AX2012 enables users to
create a snapshot of the current agreement state at any given time. These
snapshots called “Agreement History” are stored by the system as separate
records in a database so persisted state for particular agreement can be
reconstructed by the system and accessed by user for later analysis.
To enable this functionality the agreement framework defines a number of
history entities shown in the following figure.

FIGURE 8.12 AGREEMENT HISTORY DATA MODEL

Explicit relations between history- and base- entities are established for only a
few entities (exactly only for AgreementHeader and AgreementHeaderHistory as
well as for AgreementLine and AgreementLineHistory). Besides them, all other
similar relations would be redundant for the data model and therefore were not
implemented.

8-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Also it is important to note that History entities for agreement headers and lines
do not directly implement “Header-Lines” pattern. You can see in the previous
figure that there is no relation between AgreementHeaderHistory and
AgreementLineHistory entities.

While logically each agreement header history instance contains several


agreement line history instances still, the explicit relation between these two
entities is not established by the data model because for the performance reason
the AgreementLineHistory instances are allowed to be shared between several
AgreementHeaderHistory instances.

Sales and Purchase Agreements Classes


Purchase agreements can be linked to a purchase order manually by creating a
release order from the Purchase agreements form. You can also relate a purchase
agreement to a purchase order from the Create purchase order form in the
Purchase agreement field. The last option for manually creating a link between
the purchase agreement and purchase order is to use a button on the line of each
purchase order to link to a selected purchase agreement. Each purchase order line
can have one purchase agreement linked.

You can use additional functionality that is created automatically during certain
types of updates based on parameter settings to link between purchase orders and
purchase agreements. For example, you can select an option for the system to
search for purchase agreements when you create a purchase order from a sales
order, or when you create purchase orders through Master planning.

Charges
A charge is an additional fee or cost that can be added to a purchase or sale order.
Charges can be linked to the header or the lines of the orders. They can be added
manually to an order, or a rule can be configured to have charges automatically
added to an order.

8-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the data model for the relation of charges with a sales
order.

FIGURE 8.13 SALES ORDER CHARGES DATA MODEL

Each charge that is added to an order is defined by the charge code. The charge
code defines how the charge will be assessed. For example, a sales charge can be
assessed as a fee that will post to the customer's account this type of charge
increases the invoice amount of the order. Another option on the set up of the
charge code is used for the charge to be assessed to the item. This type is most
often used as a landed cost that increases the inventory cost but does not increase
the invoice amount to be paid by the customer. Similar options exist for purchase
orders.

Additionally, options exist on the charge code set up to determine which main
account the cost or fees should post to when invoice updating the order. For
purchase orders there are additional options to select a method for allocating a
charge that is applied to the header to the lines of that order.

8-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Definitions of charge codes are stored in the MarkupTable, whereas registrations


related to the sales order and purchase order are stored in the MarkupTrans table.
When the invoice is generated, a copy of the charge transaction is created that is
related to the invoice journal. The copy is related to the original record by the
OrigTableId and OrigRecId fields.

The following figure shows charges and their relation to Purchase order
invoicing.

FIGURE 8.14 PURCHASE ORDER INVOICE CHARGES DATA MODEL

8-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

An alternative to entering charges manually for each order is to define automatic


charges. The following figure shows the design of automatically generated
charges:

FIGURE 8.15 AUTOMATIC CHARGES DATA MODEL

The AccountCode and ItemCode fields are enumerations with the following
entries.

• Table: If the value is Table, then the related information in the


Account/Item-relation is a specific customer or item.
• Group: If the value is Group, then the related information is a
specific group that is defined in the Markup group of the type
customer or item.
• All: If the value is All, then the related information is blank.

Automatic charges can be related to a specific customer or item combinations.


Only charges related to a sales line or purchase line can have an ItemCode that
differs from All.

When an order or order line is created, the application will search for related
information in the MarkupAutoTable. If the search finds some information, then
the related information in the MarkupAutoLine table is copied to the
MarkupTrans table.

The MarkupAutoTable and MarkAutoLine tables can be ignored if all charges


will be manually created.

8-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

FormLetter Framework
The FormLetter framework in Microsoft Dynamics AX is used when posting
documents for sales or purchase orders. This framework is refactored in
Microsoft Dynamics AX 2012 to provide better support for customizations,
extensibility, and performance. This lesson describes the Microsoft Dynamics
AX 2012 version of the framework.

FormLetter Framework: Base Classes


In Microsoft Dynamics AX 2012, the FormLetter framework is refactored to
separate the functionality required for the posting process into different classes.
Now, in Microsoft Dynamics AX 2012, there are a number of new class
hierarchies. The following object model shows the new set of base classes and
how the classes interact with each other.

FIGURE 8.16 FORMLETTER BASE CLASSES IN MICROSOFT DYNAMICS AX


2012

8-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

FormLetter Framework: Document Posting Flow


The base FormLetter class used in Microsoft Dynamics AX 2009 is now split
into eight base classes. It is also updated to run under the SysOperation
framework. Switching to the SysOperation framework has the advantage of
executing the code on the server tier during posting in Common Intermediate
Language (CIL). Because of the switch to the SysOperation framework, client
callbacks from code running on the server tier are no longer supported. Client
callbacks result in an exception.

The following figure shows how the various base classes are used when posting a
document for an order.

FIGURE 8.17 DOCUMENT POSTING BASE CLASSES

8-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

The following figure shows the various class hierarchies used when posting a
sales order packing slip document.

FIGURE 8.18 SALES ORDER PACKING SLIP CLASS POSTING FLOW

FormLetter Framework: FormLetterServiceController


The FormLetterServiceController class is the entry point for the FormLetter
framework and can be used to interact with the posting form (for example, the
SalesEditLines form). The FormLetterServiceController class is executed on the
client tier. The class gathers the information needed during the posting process
and passes these values to the FormLetterService class by using the data contract
class pattern. The FormLetterServiceController invokes the FormLetterService
class when the run method is called.

8-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the FormLetterServiceController class hierarchy.

FIGURE 8.19 FORMLETTERSERVICECONTROLLER CLASS HIERARCHY

The module specific classes, such as SalesFormLetter, are updated so that they
extend the FormLetterServiceController class. All functionality that does not
relate to the interaction with the Posting form is moved to other class hierarchies.
The class variables that are assigned a value to use during the posting process in
earlier releases are moved to the data contract classes.

The pattern used to assign values to the data contract classes are the parm
methods from Microsoft Dynamics AX 2009 that changed and use the data
contract class instead of a global class variable. The following code sample is an
example of a parm method.

public boolean parmDirectDeliveryUpdate(boolean


_directDeliveryUpdate =
salesFormLetterContract.parmDirectDeliveryUpdate())
{
return
salesFormLetterContract.parmDirectDeliveryUpdate(_directDel
iveryUpdate);
}

FormLetter Framework: FormLetterContract


The FormLetterContract class is the base data contract class in the FormLetter
framework. The data contracts follow the same class hierarchy structure as the
FormLetterServiceController classes. Therefore, each class in the
FormLetterServiceController class hierarchy has a corresponding data contract
class. The data contract classes pass data from the FormLetterServiceController
to the FormLetterService.

8-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

The following figure shows the FormLetterContract class hierarchy.

FIGURE 8.20 FORMLETTERCONTRACT CLASS HIERARCHY

Parm methods are used to set and get the data from a contract class. The
following code sample is an example of a parm method:

[DataMemberAttribute]
public NoYes parmDirectDeliveryUpdate(NoYes
_directDeliveryUpdate = directDeliveryUpdate)
{
directDeliveryUpdate = _directDeliveryUpdate;
return directDeliveryUpdate;
}

8-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

FormLetter Framework: FormLetterService


The FormLetterService class can be used to control the posting flow for a
number of journals. The class is bound to the server tier and executes in Common
Intermediate Language (CIL), meaning that there can be no client callbacks from
this class. Client callbacks result in an exception. The following figure illustrates
some of the FormLetterService class methods.

FIGURE 8.21 FORMLETTERSERVICE

The run method initializes the objects required for posting, creates the journal,
posts the documents, and then calls the logic to print the document if required.

The class also has a service operation method for each of the document types that
can be posted by this service, such as PostSalesPackingSlip.

[SysEntryPointAttribute]
FormLetterOutputContract
postSalesOrderPackingSlip(SalesFormLetterPackingSlipContrac
t _contract)
{
formletterContract = _contract;
this.run();
return outputContract;
}

8-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

FormLetter Framework: FormLetterParmData


The FormLetterParmData class hierarchy can be used to create and maintain
posting data in the parm tables, such as SalesParmUpdate, SalesParmTable, and
SalesParmLine. The following figure shows the data model for a sales order
update.

FIGURE 8.22 FORMLETTERPARMDATA CLASS HIERARCHY

The SalesTable and SalesLine tables contain information manually entered in the
sales table form.

The update is activated by using a button in the Action Pane of the Sales order
form. This creates an update specification in the SalesParm-tables.

General update parameters are stored in SalesParmUpdate. Specifications related


to one sales order are stored in SalesParmTable, whereas individual lines are
specified in SalesParmLine.

Lines from different sales orders can be collected in one invoice. The
SalesParmSubTable holds one record for each sales order that contributes to such
invoices. Information in SalesParmLine refers to the sales order that contains the
invoice with the SalesId field, whereas the OrigSalesId field contains the ID of
the sales order that relates to the line(s) in question. SalesParmSubLine contains
sales order line update relations.

8-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The base class uses a template pattern that defines a template for how to create
records in the parm tables. There are module specific classes such as
SalesFormLetterParmData, and one class for each document type supported, such
as SalesFormLetterParmDataPackingslip.

The class has three public Application Programming Interfaces (APIs).

• CreateData: Creates the required data in the parm tables.


• ReSelect: Recreates the data based on the specQty in the posting
form.
• ReArrange: Rearranges the data in the tables based on summary
update settings.

The following figure shows the FormletterParmData class hierarchy.

FIGURE 8.23 FORMLETTERPARMDATA CLASS HIERARCHY

FormLetter Framework: FormLetterJournalCreate


The FormletterJournalCreate class hierarchy creates one journal with a header,
for example, CustPackingSlipJour, and a number of lines, for example
CustPackingSlipTrans, and related journal data, for example,
CustPackingSlipSalesLink. The base class uses a template pattern that defines
how to create a journal. The template is similar to the following code sample,
which can be found in the FormLetterJournalCreate.createJournal() method.

8-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

if (this.check())//Validate that the journal can be


created.
{
this.initJournalHeader();//Initialize the journal
header.
this.createJournalHeader(); //Create the journal
header.
this.createJournalLines(); //Create journal lines.
if (this.isJournalCreated()) //If a journal were
successfully created.
{
this.insertRecordList();//Insert all records into
the database.
this.endCreate();//Finalize journal creation.
}
}

8-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the FormLetterJournalCreate class hierarchy.

FIGURE 8.24 FORMLETTERJOURNALCREATE OBJECT MODEL

There are also document specific classes for each of the documents created by
the framework, such as SalesPackingSlipJournalCreate. These classes hold the
logic specific for a document. Those document classes that support having
multiple versions of the same document extend the
FormLetterVersionableJournalCreate class.

The FormLetterService class instantiates this class hierarchy for each of the
journals it needs to create and calls run.

8-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

FormLetter Framework: FormLetterJournalPost


The FormletterJournalPost class hierarchy can be used to post one journal, for
example, to update the ledger and inventory. The base class uses a template
pattern that defines how to post a journal.

There is also a document specific class for each of the documents posted by the
framework, for example SalesPackingSlipJournalPost. These classes hold the
logic specific for a document. This class hierarchy requires that a journal is
created and passed in.

The FormletterService class instantiates this class for each of the journals it needs
to post and calls run.

The following figure shows the FormletterJournalPost class hierarchy.

FIGURE 8.25 FORMLETTERJOURNALPOST CLASS HIERARCHY

8-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When a document is posted, the data from the parm tables is copied to another set
of tables that are used for balancing the ledger to the sub-ledger. For example, the
sales order invoice creates transactions into the customer invoice tables. The
following figure shows the data model for a sales order invoice document.

FIGURE 8.26 SALES ORDER INVOICE DOCUMENT DATA MODEL

CustInvoiceJour contains information copied from SalesTable, whereas


CustInvoiceTrans is created based on information in SalesLine. Both tables can
be affected by information specified in the SalesParm-tables when updates are
ordered.

If multiple sales orders contribute sales lines to one invoice, then only one of the
sales IDs will be stored in CustInvoiceJour. CustInvoiceSalesLink is used to
show all invoices related to a sales table, regardless of which sales order owns
the invoice.

SalesTable and SalesLine can be changed or deleted after invoice update. So it is


important to only use information that is stored in CustInvoiceJour and
CustInvoiceTrans when you design reports and calculate statistics.

Although information in the SalesParm-table is saved after the update, reporting


should not be based on these tables. They are designed to only control updates,
and the ability to delete obsolete information in these tables without destroying
reporting capabilities, could be needed later.

8-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

TIP: A periodic job can be used to clean up and delete records from the parm
tables.

The previous pattern is repeated many times, one for each type of update in the
sales and purchase areas.

Module Document -Jour, -Trans, and-Link


Sales Quotation CustQuotation...
Confirmation CustQuotationConfirmation...
CustConfirm...
Picking list WMSPickingRoute...
Packing slip CustPackingSlip...
Invoice CustInvoice...
Purchase Confirmation VendPurchOrder...
Receipts list VendReceiptsList...
Packing slip VendPackingSlip...
Invoice VendInvoice...

FormLetter Framework: FormLetterJournalPrint


The FormLetterJournalPrint class hierarchy can be used to control the printing of
one or more journal documents. There is a document-specific class for each the
documents that can be printed by the framework.

The FormLetterService class instantiates this class either for each of the journals
being posted, or once with a list of all posted journals.

8-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the FormLetterJournalPrint class hierarchy.

FIGURE 8.27 FORMLETTERJOURNALPRINT CLASS HIERARCHY

FormLetter Framework: FormLetterProvider


The FormLetterProvider class can be used to provide module specific data to
each of the other class hierarchies. There is one child class for each module, for
example, SalesFormLetterProvider. The following figure shows the
FormLetterProvider class hierarchy.

FIGURE 8.28 FORMLETTERPROVIDER CLASS HIERARCHY

8-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Lab 8.1 - Add a Field to the Sales Invoice


Actively participating during this workshop will help you to understand the use
of the SalesParm tables and become familiar with the use of .initFrom() methods.

Estimated time to complete: 30 minutes

Scenario

The solution should contain a new field in the customer table. This field should
contain instructions for the payment of invoices sent to the customer. The field
should be implemented as a multiline field, with a limit of 100 characters.

When a new sales order is created, this field should be copied to the sales order.
You should be able to change the value for specific sales orders.

When you post an invoice, you should be able to change the field without
overwriting the original value in the sales table. The value specified while
ordering the update should be printed on the invoice.

Technical Issues
This section outlines additional information that is required to implement the new
field.

InitFrom
Transfer of information from one table to another is frequently used when you
create records and save transactions from updates. This task is typically
implemented by creating an object method in the destination table named
initFrom<sourcetable>. Creating a record in a sales table in this manner involves
the activation of the following logic

salesTable.initFromCustTable();

Extension of the existing flow of information can typically only be resolved by


adding fields to the tables and to the corresponding initFrom-methods.

Controlling the Layout of the SalesEditLines Form


When you use the path Sales and marketing > Periodic > Sales update and
select one of the menu items such as Packing slip, Picking list, or Sales order
confirmation the SalesEditLines form is displayed in the user interface. The
layout of this form depends on the kind of posting selected. However, other
criteria such as the settings of the Sales order module can also change the layout
of the SalesEditLines form.

8-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The SaleFormLetter class hierarchy is used for this posting. Depending on the
menu item that is selected, the appropriate subclass of SalesFormLetter is
instantiated. The dialog method of the SalesFormLetter object opens the
SalesEditLines form.

In the init method of the SalesEditLines form an object of one of the classes in
the SalesEditLinesForm hierarchy is instantiated. Methods of this class hierarchy
are called from the form to control the layout of the form.

The pattern used can be explained by viewing how the display of the Bill of
lading tab page is controlled in SalesEditLines. The Bill of lading tab page is
only visible if you are posting to an invoice.

A method is implemented in the SalesEditLinesForm class:


public boolean billOfLading()
{
return false;
}

This method is overridden in the SalesEditLinesForm_invoice


class:

public boolean billOfLading()


{
return
SalesParameters::find().useBillOfLadingOnInvoice();
}

This method is called in the init method of the form as


shown:

tabPageBillOfLading.visible(salesEditLinesForm.billOfLading
());

Implementation
Extend CustTable, SalesTable, SalesParmTable and CustInvoiceJour tables with
the new field that contains the instructions for the payment of invoices sent to the
customer.

1. Create a new project to store all of the objects that you modify or
create as a part of this lab.
2. Make an extended data type defining properties of the payment
instruction.
3. Create a new field in the tables that is required to implement the
requested possibilities to change and store the information.
4. Add fields to the relevant forms to view the current value and
possibly edit this value.
5. Add a field to the SalesInvoiceTmp table for the payment
instructions and modify the SalesInvoiceDP class to populate the
field. Then include the field in the header of the SalesInvoice report.

8-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

6. Verify implementation by using an example.


7. Use the pattern explained to make the new field visible when you are
posting to an invoice and not visible when doing other postings.

Step by Step: Add the Payment Instruction Field


Follow these steps to create a new project.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as NewFieldOnInvoiceLab.
6. Double-click the project to open it, and then close the Projects
window.

To add the payment instruction extended data type, follow these steps.

1. In the AOT window expand the Data Dictionary node.


2. Right-click the Extended Data Type node and select New > String.
3. In the Properties window, set the following values on the new real.
a. Name = PaymentInstruction
b. Label = Payment instruction
c. HelpText = Instruction on how the customer should pay the
invoice.
d. DisplayHeight = 3
e. StringSize = 100

4. Save the extended data type.


5. Drag the newly created PaymentInstruction extended data type into
the project that you created earlier.

To add the payment instruction field to the CustTable, SalesTable,


SalesParmTable, and CustInvoiceJour tables, follow these steps.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the CustTable.
2. Drag the table into the project that you created earlier.
3. Expand the CustTable table.
4. Select the PaymentInstruction extended data type and drag it to the
Fields node of the CustTable table.
5. Save the table.
6. Right-click the Field groups node and then click New Group.

8-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

7. Set the following values in the Properties window.


a. Name = PaymentInstruction
b. Label = Payment instruction

8. Select the Payment instruction field from the Fields node on the
CustTable table, and then drag it into the PaymentInstruction Field
group.
9. Save the table. If the Synchronize table window opens, click
Continue.
10. Repeat steps 1-9 for the SalesTable, SalesParmTable, and
CustInvoiceJour tables.

To add the payment instruction field to the CustTable, SalesTable,


SalesEditLines forms, follow these steps.

1. In the AOT window, expand Forms and then locate the CustTable
form.
2. Drag the CustTable form into the project that you created earlier.
3. Save the project.
4. Right-click the CustTable form and then click Restore.
5. In the Data Sources node of the form browse to CustTable > Fields
and then select the Payment Instruction field group (folder) from the
list.
6. Drag the Payment Instruction field group into the bottom of the Sales
order defaults FastTab (TabPageSales) under the Design node of
the form. (To locate the TabPageSales tabpage, browse to Designs >
Design > Tab:Tab > TabPage:TabPageDetails > Tab:TabHeader
> TabPage:TabPageSales in the CustTable form.)
7. Right-click on the CustTable form and then click Open.
8. Verify that the new Payment instruction field is available.
9. Repeat steps 1-8 for the SalesTable form. Place the field group on
the Setup (TabHeaderSetup) FastTab of the Header view on the
form. (To locate the TabHeaderSetup, browse to Designs > Design >
Tab:MainTab > TabPage:TabPageDetails > Tab:DetailsTab >
TabPage:HeaderView > Tab:HeaderDetailsTab >
TabPage:TabHeaderSetup in the SalesTable form.)
10. Repeat steps 1-8 for the SalesEditLines form (the field group is in
the SalesParmTable data source). Place the field group on the Setup
(TabSetup) tab on the form. (To locate the TabSetup, browse to
Designs > Design > Tab:TabSalesParmTable >
TabPage:TabSetup in the SalesEditLines form.)

NOTE: You cannot open this form directly, you must open it from the Sales
order form by selecting a delivered sales order, and then click the Invoice tab in
the Action Pane, and then click Invoice in the Generate group.

8-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Step by Step: Add Code to Populate the Field


To add logic for populating the Payment instruction field, follow these steps.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_08_01_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

1. Add the AXCustInvoiceJour class to the project.


2. Create a new method called setPaymentInstruction to set the value
of the field. Use the following code sample to guide you.

protected void setPaymentInstruction()


{
if (this.isMethodExecuted(funcname(), fieldnum(CustInvoiceJour,
PaymentInstruction)))
{
return;
}
}

3. Modify the setTableFields method in the AXCustInvoiceJour class


to call the new setPaymentInstruction method that you created in
step 2. Use the following code sample to guide you.

this.setPaymentInstruction();

4. Create a new method called parmPaymentInstruction to the


AXCustInvoiceJour class. Use the following code sample to guide
you.

public PaymentInstruction parmPaymentInstruction(PaymentInstruction


_paymentInstruction = '')
{
if (!prmisdefault(_paymentInstruction))
{
this.setField(fieldnum(CustInvoiceJour, PaymentInstruction),
_paymentInstruction);
}

return custInvoiceJour.PaymentInstruction;
}

5. Repeat steps 1-4 for the AXCustTable, AXSalesParmTable, and


AXSalesTable classes.

8-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

NOTE: The code will vary slightly for each method. Make sure to use the correct
table and field for each class.

6. Add the CustCustomer_CustTable class to the project.


7. Modify the classDeclaration to declare a macro for the payment
instruction. Use the following code sample to guide you.

#define.PaymentInstruction('PaymentInstruction')

8. Create a new method called existsPaymentInstruction to check of


the payment intruction exists. Use the following code sample to
guide you.

public boolean existsPaymentInstruction()


{
return this.exists(#PaymentInstruction);
}

9. Create a new parm method called parmPaymentInstruction. Use


the following code sample to guide you.

public PaymentInstruction parmPaymentInstruction(PaymentInstruction _value


= '')
{
if (!prmisdefault(_value))
{
this.set_Attribute(#PaymentInstruction, _value);
}

return this.get_Attribute(#PaymentInstruction);
}

10. Repeat steps 6-9 for the ProdProjEInvoice_CustTable,


ReturnReturnOrderIn_SalesTable,
ReturnReturnOrderOut_SalesTable,
SalesSalesEInvoice_CustInvoiceJour,
SalesSalesEInvoice_CustTable, SalesSalesInvoice_CustInvoiceJour,
SalesSalesOrder_SalesTable, and the
SalesSalesPackingSlip_SalesParmTable classes.

NOTE: The code will vary slightly for each method. Make sure to use the correct
table and field for each class.

11. Add the SalesEditLinesForm class to the project.


12. Create a new method that returns a false. Use the following code
sample to guide you.

8-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

public boolean PaymentInstruction()


{
return false;
}

13. Add the SalesEditLinesForm_Invoice class to the project.


14. Create a new method that returns a true. Use the following code
sample to guide you.

public boolean PaymentInstruction()


{
return true;
}

Step by Step: Modify the Sales Invoice Report


To add a field to the SalesInvoiceTmp table for the Payment instructions,
follow these steps.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the SalesInvoiceTmp.
2. Drag the table into the project that you created earlier.
3. Expand the SalesInvoiceTmp table.
4. Select the PaymentInstruction extended data type and drag it to the
Fields node of the SalesInvoiceTmp table.
5. Save the table.

To modify the SalesInvoiceDP class to populate the Payment instructions field,


follow these steps.

1. Locate the SalesInvoiceDP class and drag it into the project that you
created earlier.
2. Locate the insertIntoSalesInvoiceTmp method and then right-click
and select View Code.
3. Add a line of code to the bottom of the //Invoice section after line 79
to set the temporary tables payment instruction field equal to the
custInvoiceJour payment instruction field. Use the following code
sample to guide you.

salesInvoiceTmp.PaymentInstruction = custInvoiceJour.PaymentInstruction;

4. Save and compile the class.

To modify the sales invoice report, follow these steps.

1. In the AOT window, locate the SSRS report called SalesInvoice.


2. Add the Sales Invoice report to the project that you created earlier.

8-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

3. Locate the SalesInvoiceReport project in the Visual Studio


Projects node of the AOT window.
4. Right-click the project and select Edit.
5. When Visual Studio 2012 opens, locate the SalesInvoice report in
the Solution Explorer window and then double-click it to open.
6. Expand the Datasets node and then right-click the SalesInvoiceDS
and select Refresh.
7. Expand the Designs node and then right-click the Report node and
select Edit Using Designer.
8. Add the payment instruction field into the header section of the
report.
9. Save the report, build the project, and deploy the report.

Test
Use the following steps to create a new sales order, and to post and print the
invoice.

1. Open the Customers form by using the path Accounts receivable >
Common > Customers > All customers and specify a value in the
new field that has the payment instruction.
2. Create a new sales order by using the path Accounts receivable >
Common > Sales order and select the customer modified in step 1.
Make a modification to the payment instruction inherited from the
customer.
3. Add a line to the sales order for item number 10007.
4. Post the invoice by clicking the Invoice tab of the Action Pane and
then click Invoice in the Generate group. Change the payment
instruction inherited from the sales order. Select to print the invoice
and specify the screen as the destination of the report by clicking the
Printer Setup->Invoice button and change the print destination to
screen on the Print destination settings form.
5. You can repeat the test by creating a new sales order.

TIP: You can compare your solution to the


AX2012_ENUS_DEVIV_08_01_LAB_SOL.xpo file provided with the training
image by importing the XPO file and then comparing the objects.

8-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Other Features
There are many additional features in the Sales and Purchase Order modules.
The following lesson introduces sales quotations, request for quotations,
purchase requisitions, and categories.

Document History and Change Management


Many of the documents stored in Microsoft Dynamics AX are not static. They
can be changed or corrected by users based on changes in the environment they
describe or when errors are found. Microsoft Dynamics AX 2012 introduces a
pattern for how modifications to such documents can be effectively managed and
efficiently represented in the database.

The two main functional benefits of applying the versioning pattern are:

• Full traceability (history) of changes made to a document. At any


time a new version of the document can be recorded. Any two
versions of the document can be compared with a generic version
comparison tool.
• A standardized document state model enabling change management
with workflow approvals. Documents are editable only when they
are in a draft, in review and rejected states. A new version is
recorded upon approval.

Purchase order

The purchase order is the most complex use of the versioning pattern in
Microsoft Dynamics AX 2012. Besides the traceability and change management
with workflow integration it also enabled other procurement functionality
extensions like encumbrance accounting for confirmed purchase orders.

The change management functionality for purchase orders is optional in


Microsoft Dynamics AX 2012 and turned off by default. It can be configured at
the legal entity, vendor or specific order level. When activated any change to
order data requires workflow approval. When not activated the purchase order is
always considered pre-approved. Intercompany, Direct Delivery and
production/master planning derived orders never have change management
enabled. Any change that is identified as part of the contract requires new order
confirmation before an invoice or product receipt can be processed against it.
This applies also when change management is not activated for an order and thus
the change tracking functionality is always available (every confirmation creates
a new version of the document).

8-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Product receipt and packing slip

Product receipts and packing slips use of the pattern is limited to versioning and
no workflow integration is enabled.

Product receipt and packing slip documents can be explicitly corrected in


Microsoft Dynamics AX 2012. However, only received/delivered quantity can be
corrected and only downwards.

Intercompany direct delivery packing slip corrections are also supported.

The versioning pattern defines how multiple versions of a document can be


stored in a relational database to minimize data repetition with efficient access to
any of the versions.

The document to be versioned has a tree structure with nodes represented by


records in database tables and parent-child relations between nodes represented
by foreign keys between corresponding database tables. There is no limit to the
depth of the tree. The following figure illustrates an abstract document model.
Typically nodes would be stored in various database tables with fields
corresponding to document note type attributes.

FIGURE 8.29 ABSTRACT DOCUMENT VERSIONING DATA MODEL

The following purchase order logical data model shows how the versioning
pattern is applied to the purchase order document. White entities were present in
earlier AX versions: PurchaseOrder (PurchTable),
PurchaseOrderLine(PurchLine) and the *MiscCharge* entities (MarkupTrans).
They define the basic PO tree structure with the PurchaseOrder being the root
node, PurchaseOrderLine its child node type and MiscCharge nodes that could be
children of both PurchaseOrder and PurchaseOrderLine. The highlighted entities
were added to support versioning.

8-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Physical table names of the history tables are based on the physical table names
of the corresponding node tables, for example, the physical table name for the
purchase order line history entity is PurchLineHistory. The physical model
adjustments include the use of the IsModified flag and duplication of most of the
immutable attributes to the history tables (for example, PurchLineHistory.ItemId)
to help simplify queries against the archived versions (in other words, there is no
need to join PurchTable, PurchLine and MarkupTrans in such queries).

FIGURE 8.30 PURCHASE ORDER DOCUMENT HISTORY DATA MODEL

The VersioningCompare form can be used to visualize differences between


document versions. It displays document tree on the left side with icons
indicating changed/deleted/added nodes. For the selected node there is list of
changed attributes shown on the right side of the form with old and new value
columns. The form uses VersioningCompare abstract class as a data provider
interface. Documents for which the form is to be used need to provide a subclass
implementing all the abstract methods.

8-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Sales Quotations
A quotation is a proposal to a customer to make an order. The quotation can be
sent to prospects that are not existing customers or existing customers, and
typically the company issuing the quotes does not expect to receive orders from
all the recipients of the quotation. If a quotation is accepted, it will be
transformed into a sales order.

The SalesQuotationTable table stores one record for each quotation. The details
of the quotation are stored in SalesQuotationLine. When the quote is confirmed
the data is transferred to the sales order that is described in the following section.

The SalesQuotationLine is related with one or more inventory transactions from


the record that is created until it is confirmed, canceled, or lost. These inventory
transactions will have a status called Quotation issue or Quotation receipt (a
negative quantity on a quotation line). Sales quotations can be included in the
master planning. When the quotation is confirmed the inventory transactions
related to the quotation line are replaced by inventory transactions related to the
created sales line.

Request for Quotations


Request for quotations are documents that you send to one or more vendors
requesting them to quote a price, delivery terms, and terms of payment for
materials to be purchased. The user can accept or reject the request for quotation,
fully or partly and transfer the request for quotation to a purchase order. Options
are available to create a request for quotation, receive and compare the request
for quotation replies and create a purchase order from a request for quotation.

The PurchRFQCaseTable stores one record for each case, and the
PurchRFQTable stores one record for each vendor on a specific case. The details
of the quote are stored in PurchRFQCaseLine. When the quote is accepted the
data is transferred to the purchase order that is described in the following section.

The PurchRFQCaseTable is related with one or more inventory transactions from


the record that is created until it is accepted, returned, or rejected. These
inventory transactions will have a status called Quotation issue or Quotation
receipt. When the quote is accepted the inventory transactions related to the
quotation line are replaced by inventory transactions related to the created
Purchase line.

8-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Purchase Requisitions
You can use a purchase requisition to submit a request for items or services that
you must have to perform your job function. By using purchase requisitions, you
can do the following.

• Request items and services from a procurement catalog. You can


also request items and services that are not listed in a catalog.
• Request items or services on behalf of someone else, or in a legal
entity or operating unit other than the one in which you hold a
primary position.
• Suggest a vendor from whom to order an item or service.
• Distribute an amount on a purchase requisition line to multiple
financial accounts and dimensions.
• Perform budget checking on the purchase requisition if your
organization uses budget checking.
• Submit the purchase requisition for review and approval.

Purchase requisitions require a workflow to be configured for approval. They can


be submitted through the Order Products page on Enterprise Portal or created and
submitted through the rich client.

The PurchReqTable table contains one record for each purchase requisition. The
details of each product or category on the purchase requisition are stored in the
PurchReqLine table.

Each purchase requisition and line on a purchase requisition can contain a reason
or business justification for the request. The system can be configured to require
business justifications. The business justifications for each purchase requisition
and line are stored in PurchReqBusJustification.

The PurchReqExternalSource table contains the identifier that is used for the
purchase requisitions in an external source system when the requisition originates
from such a system.

8-49
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Summary
Sales orders and purchase orders are two of the main transactions in Microsoft
Dynamics AX. The functionality and data structures that are used with each are
very similar.

Sales orders and purchase order have many integrations with other areas and
modules of the system. Several different frameworks are provided with Microsoft
Dynamics AX to help you manage basic order information, pricing, charges and
document history.

Both areas integrate with the agreements feature which allows you to define basic
contracts for sales or purchases. The FormLetter framework allows you to
manage the data for posting documents such as confirmations, packing slips, and
invoices.

8-50
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Test Your Knowledge


Test your knowledge with the following questions.

1. Which class is used to control functionality about each type of order?


( ) PurchOrderType
( ) PurchTableType
( ) InventOrderType
( ) InventTableType

2. Describe what happens to MarkupTrans when an invoice transaction is


posted.

3. If no price is found in the PriceDiscTable which table is used to select the


price.
( ) PurchPriceTable
( ) EcoResPriceTable
( ) InventTableModule
( ) InventTablePrice

4. Which set of tables is used to store document generation information before a


document is posted for sales orders?
( ) SalesUpdate... tables
( ) SalesParm... tables
( ) SalesPost... tables
( ) SalesDocument... tables

8-51
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

8-52
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 8: Use and Design of the Sales and Purchase Modules

Solutions
Test Your Knowledge
1. Which class is used to control functionality about each type of order?
( ) PurchOrderType
(•) PurchTableType
( ) InventOrderType
( ) InventTableType

2. Describe what happens to MarkupTrans when an invoice transaction is


posted.

MODEL ANSWER:

When the invoice is generated, a copy of the charge transaction is created


that is related to the invoice journal. The copy is related to the original record
by the OrigTableId and OrigRecId fields.

3. If no price is found in the PriceDiscTable which table is used to select the


price.
( ) PurchPriceTable
( ) EcoResPriceTable
(•) InventTableModule
( ) InventTablePrice

4. Which set of tables is used to store document generation information before a


document is posted for sales orders?
( ) SalesUpdate... tables
(•) SalesParm... tables
( ) SalesPost... tables
( ) SalesDocument... tables

8-53
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

8-54
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

CHAPTER 9: USE AND DESIGN OF THE PROJECT


MANAGEMENT AND ACCOUNTING MODULE
Objectives
The objectives are:

• Describe how projects are created, and the various types of projects
that are available.
• Review the data model for projects.
• Discuss the significant classes that are used with projects.
• Describe how the work breakdown structure is used with projects
and how the data model relates to the project data model.
• Discuss the transaction types that are used for journals in the Project
management and accounting module and how categories, pricing,
and line properties control the posting of these transactions.
• Review the data model and the ProjTrans class hierarchy that is used
for posting transactions against a project.
• Describe how budgeting and forecasting works with projects.
• Review the data model for budgets and forecasts.
• Describe how project contracts are used.
• Review the data model for project contracts.
• Describe how project invoice proposals and invoices are generated in
Microsoft Dynamics® AX.
• Review the data model and classes used for generating invoice
proposals and invoices.
• Review how estimate projects and cost templates are used in the
system.
• Describe the Project Management and Accounting Add-In.

Introduction
This chapter introduces you to the Project management and accounting
module of Microsoft Dynamics AX. The design and data models for several key
areas are reviewed.

Use the project management and accounting module to plan, create, manage,
control, and complete projects for your organization. Customer-focused projects
can be set up on a time and materials or fixed-price basis. You can also use the
module to manage costs for internal and investment projects.

9-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

For external projects, you can create project quotations that can be converted to
projects. You create project contracts with one or more funding sources that will
be invoiced for project costs and fees.

Each project that you create can have one or more subprojects and activities that
are made up of the project work structure. You can create financial forecasts and
budgets for cost control and to measure project performance.

You can assign attributes for project skills and experience to workers to enable
you to search for and assign workers to a project that is based on skills and
availability. For additional project planning flexibility, you can integrate the
projects with Microsoft® Project Server.

During project execution, employees and contractors can enter project timesheets
and expense reports. Required items and services can be procured and charged
back to the customer.

Project managers have many different reports and analytical tools to examine
project performance from different perspectives. The following figure provides
an overview of the Project management and accounting module.

FIGURE 9.1 PROJECT MANAGEMENT AND ACCOUNTING OVERVIEW

9-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Projects
The project list contains the list of all projects in the current company and will be
used frequently by project managers. Open Project management and
accounting > Common > Projects > All projects.

FIGURE 9.2 ALL PROJECTS LIST PAGE

To create a new project without a template, open Project management and


accounting > Common > Projects > All projects. On the Action Pane, select
the Project tab. Then click Project in the New group. You can edit the properties
of an existing project by using the Project details form. You can optionally use a
project template when creating a new project. Project templates help make the
process of creating a new project or complex project structures easier and more
consistent.

Subprojects
Some projects can easily be processed as one large project for planning and
accounting if the subprojects and complexity are low. Other projects gain more
overview when distinct phases of the project's activities are split into separate
subprojects. For example, if a large project has several phases such as a design
phase and an implementation phase a separate subproject can be created for each
phase.

9-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

You can use subprojects to achieve a project structure that reflects the different
project initiatives, and to process special accounting situations.

Examples include invoicing expenses and materials on a fixed-price project and


keeping track of internal time consumption as part of the preparation for an
external project.

All project types can be combined in a project hierarchy, and more subprojects
can be added as a project progresses. Project hierarchy properties appear in the
Project hierarchy tab on the Project details form. Each subproject must have a
project ID that follows the format <Parent Project ID><Delimiter><Subproject
ID>.

FIGURE 9.3 PROJECT DETAILS FORM

Project Types
The Project management and accounting module, supports the following six
project types.

• Time and material: Time and material projects are invoiced as work
progresses based on the consumption of hours, expenses, items, or
fees on the project. This project type is mainly applied to projects
where costs can be matched with the revenue on each transaction and
the project is invoiced as work progresses.
• Fixed-price: Fixed-price projects are for projects that are invoiced
according to a billing schedule based on the project contract.
Revenue for a fixed-price project can be posted according to the
completed contract method or according to the completed percentage
method.
• Internal: Internal projects are financed by your company. There are
no customers for this project and it cannot be invoiced. Costs can be
posted to profit and loss accounts or balance sheet accounts.

9-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

• Cost: Cost projects are internal projects that register hours, expenses,
and item transactions. Transactions on cost projects are posted to
profit and loss accounts and cannot be capitalized to balance
accounts.
• Time: Time projects are internal projects that only register hour
transactions. Time projects are applied to the total number of hours
consumed on a task or a project. Unlike the transactions on an
internal project type, transactions on a time project are never posted
to ledger accounts. Examples of time projects include the registration
of illness or holidays.
• Investment: Investment projects are internal projects without
immediate earnings. Only costs of items, hours, and expenses can be
registered on an investment project, and the estimate feature is
applied to track and control costs. Costs registered to an investment
project are entered on profit and loss accounts and transferred to
work in progress (WIP) accounts when estimates are posted. After
the project is completed and the project is eliminated, the WIP value
is transferred to a fixed asset, a ledger account, or a new project.

Project Groups
Project groups define how the system processes the ledger postings of the project
types. Each project belongs to a single project group.

Project groups control the posting profiles to the general ledger and the project
WIP.

Rules for posting transactions are set up according to project or category type,
and the costs are posted into profit and loss or balance accounts. Because the
project group is mandatory when you create a new project, a minimum of one
project management and accounting group must be set up.

When you create a project group, you must immediately determine the project
type tied to this group. Then you will assign the specific conditions connected to
that specific type, such as invoice posting, journalizing, cost price, and sales
price.

When you create new projects, you can only select groups that are defined for
that specific project type.

9-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Open Project management and accounting > Setup > Posting > Project
groups.

FIGURE 9.4 PROJECT GROUPS FORM

9-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Projects Data Model


The following figure shows the data model for projects.

FIGURE 9.5 PROJECTS DATA MODEL

The ProjTable is the primary table for projects; each project has one record in the
ProjTable. For external (billable) projects, each project contract
(ProjInvoiceTable) is attached to one or more customers for invoicing and
payment. Each project is also attached to a project group (ProjGroup). The
project group defines how the system processes the ledger postings of the various
project types.

9-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

ProjTableType Class
Microsoft Dynamics AX 2012 supports several different types of projects such as
internal, cost, and time. Each type supports different tasks and functionality.
Instead of creating many if-statements to separate the functionality about the
project type, the properties and methods are isolated on the class hierarchy
ProjTableType. The following figure shows the ProjTableType class hierarchy.

FIGURE 9.6 PROJTABLETYPE TYPE HIERARCHY BROWSER

On the ProjTableType class an object method called type() is used to construct


the actual object.

Object methods such as insert(), update(), delete(), validateWrite(), and


validateField() are implemented on the classes. The object method on the table is
activated by the kernel. However, the call is redirected to the object constructed
by the object method type(). A modification to these methods should be
implemented on the classes instead of on the table object method.

The dataflow object method called initFrom…() is also implemented on the


classes.

If you must have a new property on an existing or new subclass of these


hierarchies, add the default property to the root class and override it on the
subclass in question.

To create a new project type, start by adding a new element to the project type
base enumeration, and then create a new class that extends the ProjTableType
class. Add methods to the new class that override the base methods in the
ProjTableType class. Then you must modify the type() object method on the
ProjTable.

9-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Work Breakdown Structure


The project work breakdown structure (WBS) defines the set of tasks that are
performed on projects and can be used for fine-grained tracking of hour, expense,
and item consumption and forecasting. To track the total cost for a specific task,
specify the activity associated with the project transaction when the project
transaction is entered through a project journal.

To set up activities, open Project management and accounting > Common >
Projects > All projects. Highlight the project for which you want to set up a
WBS. In the Action Pane, select the Plan tab, and then in the Activities group,
click Work breakdown structure.

FIGURE 9.7 WORK BREAKDOWN STRUCTURE FORM

Activities are set up by using an activity hierarchy, in which sub activities are
created as smaller tasks within one large task or phase of a project.

Information related to working with activities includes the following.

• Because activities are specific tasks that are performed on a specific


project, they are always project-specific and not shared between
projects.
• Each project transaction can be associated with an activity in the
WBS.
• Both project budgets and project forecast can refer to activities in the
WBS.
• The WBS is extended for resource scheduling by the project
management and accounting add-in.

To create a new activity, from the Work breakdown structure window, click a
specific activity and then click New.

9-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Work Breakdown Structure Data Model


The following figure shows the data model for the work breakdown structure.

FIGURE 9.8 WORK BREAKDOWN STRUCTURE DATA MODEL

Each project activity has one record in the ProjActivity table. Each project
activity record is associated with one category. Each project can have many
different activities and many projects can have the same activities.

9-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Journals and Transactions


Transactions posted against projects can be one of five types—Hour, Cost,
Revenue, Item, and On Account. Instead of creating a Type field on one table
and many redundant fields, project transactions are recorded in five tables.

After transactions are posted against projects, an invoice proposal can be created.
The system creates a suggested invoice based on user-defined criteria. The
invoice proposal for each transaction type is stored in five tables. When
transactions are invoiced, they are stored in another set of five tables.

Transaction Types
After a project is created, transactions are entered through journals or project-
related business documents. The following transaction types are supported in the
Project management and accounting module.

• Hours: Consulting, installation


• Expenses: Plane tickets, hotel accommodations, vendor services
• Fee: Surcharges
• Item: Products delivered as part of the project

In addition to these transactions, on-account transactions represent pre-payments


for a time and material project or scheduled payments for fixed-price projects.

For all transaction types:

• The system searches for sales and cost prices and applies them as a
default to the transaction. The user can override prices in the journal.
• The sales tax group is copied from the project or project contract. For
non-item transactions, the item sales tax is derived from the specified
project category.
• The line property indicates whether the registered transaction can be
invoiced or not. A line property that can be charged is only relevant
on time and material projects.

For some transaction types:

• Hour, expense, and fee transactions can use validation functionality.


• In addition to being managed in the project ledger, project
transactions are usually summarized by posting to the general ledger.

9-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Categories and Category Groups


The Project management and accounting module is an easy method to
categorize revenue and expenses on projects. It provides detailed reporting and
analysis, and steers posting to the general ledger. Additional detail on project
performance is provided by categorizing expenses and revenues separately from
the general ledger.

The following diagram shows the correlation between shared categories, project
categories, category groups, and transaction types:

FIGURE 9.9 CATEGORY BREAKDOWN

To make it easier for companies to categorize expenditures, categories are shared


among the Expense management, Production control, and Project
management and accounting modules. Additionally, categories are shared
between legal entities.

You can use category groups to share properties (primarily posting profiles)
between related categories. You must have a minimum of one category group for
each transaction type and each project category is assigned a group.

Together, the project groups, project categories, and category groups define the
posting specifications in the Project management and accounting module.

Additionally, line property defaults can also be defined for category groups.

To open the Category groups form, open Project management and accounting
> Setup > Categories > Category groups.

Project Pricing
Project transactions include a cost price, a sales price or both. The cost price is
the price for each unit that is charged to the project. If a customer is invoiced for
transactions, a sales price is specified for each unit. Sales prices are not used for
fixed-price projects or internal projects.

9-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Cost and sales prices can be specified generically at the category or employee
level, or more specifically on a project. Specifying them generically helps
standardize pricing, removing the need for users to determine the cost and sales
price at the time of transaction entry.

To access prices open Project management and accounting > Setup > Prices,
and then select one of the forms.

Line Properties
In addition to project categories and pricing, line properties are also significant to
project transactions. A line property controls whether any of the following
occurs.

• An additional cost percentage is applied to the transaction.


• An additional sales percentage is applied to the transaction—applies
only for time and material projects.
• A transaction with a line property is chargeable to a customer.
• The sales value of a transaction is accrued at the time that it is posted
on time and material projects.
• The cost is capitalized to balance accounts when transactions with a
line property are posted. This applies to time and material projects,
fixed-price projects, investment projects, and internal projects.

The line properties are set up from the Line properties form. Open Project
management and accounting > Setup > Line properties > Line properties.

Journals
Journals are used to post the various types of transactions. Each journal uses
different tables with similar data models. The following topics review the hour’s
journal.

The basic information entered for the hour registration on a project includes the
following.

• The project to which the hour costs should be allocated.


• The date the hour costs occurred.
• The name of the person initiating the hour costs.
• The type of hour costs to be allocated.
• The amount to be posted, and if invoiced to a customer, at what price
and whether sales tax is applied.

To open the hour journal form, open Project management and accounting >
Journals > Hour.

9-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Hours Journal Data Model


The following figure shows the hour's journal data model.

FIGURE 9.10 HOURS JOURNAL DATA MODEL

9-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

The following table lists the journal header, lines, and posting table that is used
for each of the types of journal.

Journal Journal Journal lines table Posted journal


type header table transaction table
Hour ProjJournalT ProjJournalTrans ProjEmplTrans
able ProjEmplTransCost
ProjEmplTransSale
Expense LedgerJourn LedgerJournalTrans ProjCostTrans
alTable _Project ProjCostTransCost
ProjCostTransSales
Item InventJourna InventJournalTrans ProjItemTrans
lTable ProjItemTransCost
ProjItemTransSale
Fee ProjJournalT ProjJournalTrans ProjRevenueTrans
able ProjRevenueTransCost
ProjRevenueTransSale

ProjTrans Class Hierarchy


The ProjTrans super class and its sub-classes control the creation and posting of
transactions. ProjTrans has a sub-class for each transaction type, and each sub-
class has a sub-class for all the stages in a project.

FIGURE 9.11 PROJTRANS TYPE HIERARCHY BROWSER

9-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

For example, the ProjTransCostTrans.invoiced() method returns true if the cost


transaction is already invoiced.

View the ProjTransCostTrans.invoiced() method.

/// <summary>
/// Determines whether this transaction has been invoiced.
/// </summary>
/// <returns>
/// Always returns false.
/// </returns>
/// <remarks>
/// This method should be overridden by classes that extend
this class to provide the necessary
/// functionality for the specific transaction.
/// </remarks>
//BP Deviation Documented
public display boolean invoiced()
{
ProjCostTransSale projCostTransSale;
boolean ret;

if (!SysDictClass::isSuperclass(classIdGet(this),
classNum(ProjTransCostTrans)))
{
while select projCostTransSale
where projCostTransSale.TransId == this.transId()
{
ret =
ProjTrans::newProjCostTransSale(projCostTrans,
projCostTransSale).invoiced();
if (ret)
break;
}
}
else
{
ret = super();
}

return ret;
}

If a ProjInvoiceCost record exists with a matching transaction ID, then the


transaction is already invoiced.

9-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Lab 9.1 - Warranty Item


This lab demonstrates how to add a field to the hours journal and copy data to a
posted transaction.

Estimated time to complete: 20 minutes

Scenario

The Contoso Company offers repairs to the items that they sell, and requires
employees to record time against a single project, which is titled Warranty
Repairs. It is required that the employee record in which item the repair work is
performed.

Challenge Yourself!
Use the information provided, to add a new warranty item field to the hours
journal that is copied to posted hours transaction record.

Need a Little Help?

1. Create a new project to store the changes.


2. Create a new string extended data type called ProjWarrantyItemId.
3. Add a new field, WarrantyItemId of the type ProjWarrantyItemId
to table ProjJournalTrans and ProjEmplTrans tables and related
forms.
4. Set ProjEmplTrans.WarrantyItemId =
ProjJournalTrans.WarrantyItemId in static table method
ProjEmplTrans::InitTransFromJournal().
5. Test the new field to make sure that it is copied correctly.

Step by Step
To create a new project, follow these steps.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as WarrantyItemLab.
6. Double-click the project to open it, and then close the Projects
window.

9-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

To add the warranty item extended data type, follow these steps.

1. In the AOT window expand the Data Dictionary node.


2. Right-click the Extended Data Type node and select New > String.
3. In the Properties window, set the following values on the new real.
a. Name = ProjWarrantyItemId
b. Label = Warranty item
c. Help text = Warranty repair item ID.
4. Save the extended data type.
5. Drag the newly created extended data type into the project that you
earlier.
6. Save the project.

To add the warranty item field to the ProjJournalTrans table and the
ProjJournalTransEmpl form, follow these steps.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the ProjJournalTrans table.
2. Drag the table into the project that you created earlier.
3. Expand the ProjJournalTrans table.
4. Select the warranty item extended data type that you created and
drag it to the Fields node of the ProjJournalTrans table.
5. Save the table.
6. Expand the Field groups node
7. Select the warranty item field that you created from the Fields node
on the ProjJournalTrans table, and then drag it into the
IdentificationHour field group.
8. Save the table. If the Synchronize table window opens, click
Continue.
9. In the AOT window, expand Forms and then locate the
ProjJournalTransEmpl form.
10. Drag the ProjJournalTransEmpl form into the project that you
created earlier.
11. Save the project.
12. Right-click the ProjJournalTransEmpl form and then click Restore.
13. In the Data Sources node of the form browse to ProjJournalTrans
> Fields and then select the warranty item field that you created.
14. Drag the warranty item field into the grid of the form. (To locate the
grid, browse to Designs >Design > Tab:Tab > TabPage:Overview
> Grid:Grid in the ProjJournalTransEmpl form.)

9-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

To add the warranty item field to the ProjEmplTrans table and the
ProjTransEmpl form, follow these steps.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the ProjEmplTrans table.
2. Drag the table into the project that you created earlier.
3. Expand the ProjEmplTrans table.
4. Select the warranty item extended data type that you created and
drag it to the Fields node of the ProjEmplTrans table.
5. Save the table.
6. Expand the Field groups node
7. Select the warranty item field that you created from the Fields node
on the ProjEmplTrans table, and then drag it into the Identification
field group.
8. Save the table. If the Synchronize table window opens, click
Continue.
9. In the AOT window, expand Forms and then locate the
ProjTransEmpl form.
10. Drag the ProjTransEmpl form into the project that you created
earlier.
11. Save the project.
12. Right-click the ProjTransEmpl form and then click Restore.
13. Save the form and the project.

To modify the InitTransFromJournal method, follow these steps.

1. Expand the Methods node of the ProjEmplTrans table in the


Project window.
2. Right-click the initTransFromJournal method and then click View
Code.
3. After line 31 in the Code Editor window, add a line of code to set
the projJournalTrans warranty item field equal to the projEmplTrans
warranty item field. Use the following code sample to guide you.

projEmplTrans.ProjWarrantyItemID = _projJournalTrans.ProjWarrantyItemID;

4. Save the table and the project.

TIP: You can compare your solution to the


AX2012_ENUS_DEVIV_09_01_LAB_SOL.xpo file provided with the training
image by importing the XPO file and then comparing the objects.

9-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test
To test the solution and verify that the Warranty item field is copied from the
journal to the posted transaction, follow these steps.

1. Open Project management and accounting > Journals > Hour.


2. Click New to create a new journal.
3. Select a Project ID such as 10001.
4. Enter 2.5 into the Hours field.
5. Enter a Warranty item number such as 2456.
6. Click Post, and then click OK.
7. Close the Infolog window.
8. Open Project management and accounting > Inquiries >
Transactions > Hour.
9. Scroll to the very bottom of the list to locate the transaction that you
just posted.
10. Select the transaction that you posted, and then click the General
tab.
11. Notice the Warranty item field is populated with the number that you
entered in step 5. Close the forms.

9-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Budgets and Forecasting


The Project management and accounting module includes project budgeting
functionality. This functionality can help companies monitor and control project
revenue and expenditures, and reallocate funding and resources to meet
budgetary goals.

Project budgeting works with general ledger (GL) budgeting. Transactions are
compared with project budgets and then against general ledger budgets. Project
budgeting is also closely related to project forecasting. You can build project
budgets from forecast models. Additionally, project budget amounts (original and
remaining) are maintained as two specified forecast models for control and
reporting. Additionally, Microsoft Dynamics AX supports a cost control
mechanism called forecast reductions.

When you create a project, you create the original budget. You can define
budgets for costs, revenues, or both. After you define the budget, you submit the
budget to workflow.

After a budget is approved, any changes to the budget must undergo the budget
revision process.

Before you create project budgets, you must define the approval process.
Approval of project budgets is implemented by using the workflow feature of
Microsoft Dynamics AX. Two workflow types are defined for project budgeting.

• Review original budget workflow


• Review budget revision workflow

After the project budget is defined, make sure that the project is configured to use
the budget. You can do this in the Budget and forecast tab on the Project
details form. After you enter a budget or budget revision you can allocate the
budget amounts across periods.

When you are entering a project item task (such as a project purchase requisition,
purchase order, or vendor invoice) you can view the impact the document will
have on the transaction on the project budget.

Demonstration: View Project Budget Status for a Project Purchase Order

1. Open Project management and accounting > Common > Item


tasks > Project purchase orders.
2. Click Purchase order in the New group of the Action Pane.
3. On the Create purchase order form select a vendor such as 1102,
and then click the General FastTab.
4. In the Project ID field, select a project such as 10002: Colorado
Airport, and then click OK.

9-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Add an item to the order such as 1101, and then click on the Manage
tab in the Action Pane.
6. Enter a Quantity and Unit price for the item.
7. Click Budget > Project budget status. The Project budget status
form will display details of the budgeted amounts for the item,
category, activity, and budget period.

FIGURE 9.12 PROJECT BUDGET STATUS FORM

At the end of the year, you can transfer any remaining budget amounts for
multiyear projects to future years. You can also create budget register details for
those amounts in the associated general ledger accounts. The
ProjYearEndProcess class contains the logic to run the process.

9-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Budgeting Data Model


The following figure shows the data model for project budgets including
revisions and allocations.

FIGURE 9.13 PROJECT BUDGETS DATA MODEL

When budgets are activated for a project, the project budget details are stored in
the ProjBudget table. Each budget amount is stored in the ProjBudgetLine table.
The ProjBudgetLine.ProjTransType field is used to determine whether the
budget is a cost or revenue.

ProjBudgetTransactionLine Class Hierarchy


You can use the ProjBudgetTransactionLine class hierarchy to hold budget
transaction information associated with various types of project transactions. For
example, you can use the ProjBudgetTransactionLine_HourJournal class to hold
and retrieve the budget information associated with the hour journal.

9-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure shows the ProjBudgetTransactionLine class hierarchy.

FIGURE 9.14 PROJBUDGETTRANSACTIONLINE TYPE HIERARCHY


BROWSER

Forecasting
You can use project forecasting to forecast expected labor, machines, expenses,
and cash flow that is needed to run projects. You can also use project forecasting
to effectively use resources and to control expenses so that a reasonable profit
margin can be earned.

In the Project management and accounting module project forecasts can be


entered against the following transaction types—expenses, fees, items, and hours.

When you set up forecasts you can create a new record for each forecast model to
use, and create submodels if a model hierarchy must be built. The model
hierarchy can only contain two levels.

After you have defined forecast models, you can enter forecasts for hours,
expenses, fees, items and on-account payments.

Open Project management and accounting > Common > Projects > All
projects. Select a project. On the Action Pane, on the Plan tab, in the Forecast
group, you can click a specific type of forecast.

9-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Forecast Scheduling
Project managers can use the Project management and accounting module to
group forecasted hour consumption by worker. You can use the resources to plan
and schedule hours, and use the hour scheduling function to perform job
scheduling and operations scheduling.

Because the scheduling function resembles the production scheduling function, a


complete setup is not required to perform the scheduling routine from the Project
management and accounting module.

Scheduling involves resources, not workers. With the Project management and
accounting module, you can use the type of resource and the capacity-related
options to determine the project schedule. When you use work centers, you can
schedule all resource types, and schedule whole processes, because it is not
limited to only human resources.

Both the Production control and Project management and accounting


modules share resource groups and resources.

The following figure shows the relation to resources.

FIGURE 9.15 GENERAL SETUP PROCESS FLOW DIAGRAM

9-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Forecasting Data Model


The following figure shows the data model for project hour forecasts.

FIGURE 9.16 PROJECT HOUR FORECAST DATA MODEL

Each hour forecast record is stored in the ProjForecastEmpl table. Each forecast
is related to a specific activity from the work breakdown structure and the
resource requirements are stored in the WrkCtrActivity... tables. These
requirements are used to schedule projects.

9-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

A similar data model exists for the other types of forecasts by using similar
tables.

Forecast type Forecast table


Hour ProjForecastEmpl
Expense ProjForecastCost
Item ForecastSales
Fee ProjForecastRevenue
On account ProjForecastOnAcc

ProjForecastPost Class Hierarchy


You can use the ProjForecastPost hierarchy to hold forecast transaction
information that is associated with various types of project transactions. For
example, you can use the ProjForecastPostCost class to hold and retrieve the
expense forecasts.

The following figure shows the ProjForecastPost class hierarchy.

FIGURE 9.17 PROJFORECASTPOST TYPE HIERARCHY BROWSER

Project Contracts
The project contract contains necessary customer information for correctly
issuing invoices to one or more project customers. All external projects must
refer to a project contract. This makes the setup of the project easier. The project
contract includes information on the following.

• Invoicing currency
• Customer and address information

9-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Terms of payment
• Sales tax and tax information
• Fixed exchange rate agreement references

To view the list of project contracts, open Project management and


accounting > Common > Projects > Project contracts.

FIGURE 9.18 PROJECT CONTRACTS LIST PAGE

You can also choose to set up project funding information for a project including
funding sources, limits, and rules for funding.

After a project contract is defined, it can be used when you create a new external
(time and material or fixed-price) project.

• One Project contract - many projects attached. A customer can be


connected to many projects. With one project contract, one invoice
can be issued for all or only parts of these projects.
• One Project - many different project contracts attached.
Although you can only link one contract to a single project, you can
link a different contract to each subproject within a project hierarchy.
This allows you to connect many different customers into the project
hierarchy for billing purposes. You can then report on the entire
project hierarchy.

Each project contract is stored in the ProjInvoiceTable. Each project can then be
related to one project contract. Multiple projects can be related to the same
project contract. The funding information on project contracts is stored in three
additional tables.

9-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

• ProjFundungSource: Each project contract can have one or more


project funding sources.
• ProjFundingLimit: Each project funding source can have one or
more limits established. The limits define the amount that is being
funded and the attributes. For example, specific activities, transaction
types, or categories.
• ProjFundingRule: Each funding limit can have one or more rules
defined. The rules are used to prevent transactions from posting
when the amounts defined are exceeded.

Invoicing
You can create project invoices by using an invoice proposal that is later
confirmed and posted to the general ledger. This proposal is populated according
to selections made by the user, which can be modified if necessary and then
posted.

Invoice Proposals
The invoice proposal is generated based on the transactions registered on the
projects. The transaction types include expense, employee hours, fee, items, and
an offset on-account payment.

The Invoice proposals form includes proposed invoice lines on separate tabs,
according to the transaction type.

Invoice proposals are created by using the ProjInvoiceChoose super class and
subclasses. On account transactions use a specific subclass. The following figure
shows the ProjInvoiceChoose class hierarchy.

FIGURE 9.19 PROJINVOICECHOOSE TYPE HIERARCHY BROWSER

When ProjInvoiceChoose is run, you are prompted to select which type of


transactions will be invoiced and you can also delimit the transactions by using
the query. This query is executed to retrieve any un-invoiced transactions and
populate the ProjProposal... transaction tables.

9-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Transaction Type Proposal Table


Hour ProjProposalEmpl
ProjProposalEmplDetail
Expense ProjProposalCost
ProjProposalCostDetail
Item ProjProposalItem
ProjProposalItemDetail
Fee ProjProposalRevenue
ProjProposalRevenueDetail
On account ProjProposalOnAcc
ProjProposalOnAccDetail

Edit Invoice Proposals


After an invoice proposal is completed it can be edited. You can make the
following changes to the proposal—cancel the proposal, delete a proposal line,
add a new proposal line, and, or edit the sales price and transaction texts.

Canceling the invoice proposal only cancels the proposal lines. To access a
canceled invoice proposal, a new invoice proposal must be created.

To delete one or more proposal lines, select the transaction(s) and then click
Remove from the toolbar. This does not delete the actual transaction, only the
line from the invoice proposal. Deleted lines are reselected as proposals the next
time that an invoice proposal is run.

If new transactions are posted within the same date range as the previously
created invoice proposal, and they must be included, use Add lines. The system
finds any transactions that fall into the same selection criteria that is specified in
the original invoice proposal and adds them to the existing proposal.

Post Invoices
After the invoice proposal is reviewed and edited, and the lines are satisfactory
you can post the invoice by clicking Post.

As with standard sales order invoicing, you can specify whether a credit limit
check of the customer must be performed when you post the invoice. The overall
control of how the system warns the user if the credit limit is exceeded is set up
in the Project management and accounting parameters form under in the
Invoice tab under Credit rating.

In addition to the Invoice proposal form, invoice proposals can also be posted by
running the periodic job, Post invoice proposals. To find this job, open Project
management and accounting > Periodic > Project invoices > Post invoice
proposals.

9-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

ProjFormLetter Class
Invoicing occurs in the ProjFormLetter class and in the ProjFormLetter_Invoice
subclass. The structure for these classes resembles the FormLetter classes used in
the Accounts receivable and Accounts payable module discussed earlier in the
“Use and Design of Sales and Purchase Modules” chapter.

The following figure shows the ProjFormLetter class hierarchy.

FIGURE 9.20 PROJFORMLETTER TYPE HIERARCHY BROWSER

When the invoice is posted new transactions are created in several tables to store
the posted information. Each invoice has a record in the ProjInvoiceJour table for
the header of the invoice. For the lines of the invoice, several tables are used for
each transaction type.

Transaction Type Posted Transaction Table


Hour ProjInvoiceEmpl
ProjInvoiceEmplDetail
Expense ProjInvoiceCost
ProjInvoiceCostDetail
Item ProjInvoiceItem
ProjInvoiceItemDetail
Fee ProjInvoiceRevenue
ProjInvoiceRevenueDetail
On account ProjInvoiceOnAcc
ProjInvoiceOnAccDetail

9-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Lab 9.2 - Put an Invoice Proposal on Hold


This lab demonstrates how to modify the project invoice proposal and project
invoice posting framework.

Estimated time to complete: 20 minutes

Scenario

Isaac, the Systems Developer, is asked to create a function so that Invoice


Proposals can be put "on hold." The invoice proposal will be put on hold while
transactions are investigated in the case that Prakash, the Project Manager,
believes there might be an error.

Challenge Yourself!
Put an invoice proposal on hold.

This requires a new field, OnHold, type = NoYes. If this field is set, then the
invoice cannot be posted, and a new invoice proposal can be created that could
include transactions included on the OnHold proposal.

Need a Little Help?

1. Create a new project to store the changes.


2. Add a new NoYes field, OnHold to ProjProposalJour.
3. Display this field on theProjInvoiceProposal form.
4. In the ProjFormLetter_Invoice class add logic to validate that the
invoice is not on hold.
5. Test the new field to make sure that the invoice cannot be posted.

Step by Step
To create a new project, follow these steps.

1. Open the Development workspace.


2. Open the Projects window.
3. Right-click the Shared node and then click New > Project.
4. Right-click the new project and select Rename.
5. Enter a name for the project such as InvoiceProposalHoldLab.
6. Double-click the project to open it, and then close the Projects
window.

9-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

To add the on hold field to the ProjProposalJour table and the


ProjInvoiceProposal form, follow these steps.

1. Under the Data Dictionary node in the AOT window, expand tables
and locate the ProjProposalJour table.
2. Drag the table into the project that you created earlier.
3. Expand the ProjProposalJour table.
4. Right-click the Fields node of the table and then click New > Enum.
5. In the Properties window, set the following values.
a. Name = OnHold
b. Label = On hold
c. HelpText = When selected the invoice proposal is on hold and
cannot be posted.
d. ExtendedDataType = NoYesId

6. Save the table.


7. Expand the Field groups node.
8. Select the on hold field that you created from the Fields node on the
ProjProposalJour table, and then drag it into the Invoice field group.
9. Save the table. If the Synchronize table window opens, click
Continue.
10. In the AOT window, expand Forms and then locate the
ProjInvoiceProposal form.
11. Drag the ProjInvoiceProposal form into the project that you created
earlier.
12. Save the project.
13. Right-click the ProjInvoiceProposal form and then click Restore.
14. In the Data Sources node of the form browse to ProjProposalJour
> Fields and then select the on hold field that you created.
15. Drag the on hold field into the grid of the the form. (To locate the
grid, browse to Designs >Design > Group:CtrlHeader >
Tab:Heading > TapPage:TabProjProposalJour >
Grid:PrijProposalGrid in the ProjInvoiceProposal form.)
16. Set the AllowEdit property on the ProjProposalJour data source in
the form to Yes.
17. Highlight all of the fields in the Grid except for the new On hold
field and set the AllowEdit property to No.
18. Next you must modify the setAllowEdit method on the form to allow
the grid to be edited. Locate the setAllowEdit method under the
Methods node of the form, and then right-click and select View
Code.
19. In the Code Editor window, locate line 17 and change the result to
true, and then locate line 48 and change the result to true.

9-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

20. Save the form and the project.


21. Right-click the form and select Open. Verify that you can modify
the On hold field but cannot edit any other fields in the grid.

To modify the ProjFormLetter_Invoice class, follow these steps.

1. Locate the ProjFormLetter_Invoice in the AOT window and drag it


into the project that you created earlier.
2. Expand the ProjFormLetter_Invoice and locate the run method.
3. Right-click the method and then click View Code.
4. Add an IF statement to the beginning of the method to call the
validate method. Use the following code sample to guide you.

/// <summary>
/// Contains the code that does the actual job of the class.
/// </summary>
public void run()
{
if(!this.validate())
{
throw error('@SYS21533');
}
super();
}

5. Locate the validate method and then right-click and select View
Code.
6. Add an IF statement to the end of the method that checks for the
invoice proposal to be on hold and return a warning message when it
is on hold. Use the following code sample to guide you.

if(this.parmProjProposalJour().OnHold)
{
ret = checkFailed("The proposal is on hold and cannot be posted.");
}

7. Save the class.

TIP: You can compare your solution to the


AX2012_ENUS_DEVIV_09_02_LAB_SOL.xpo file provided with the training
image by importing the XPO file and then comparing the objects.

9-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Step by Step: Test


To test the new hold functionality, follow these steps.

1. Open Project management and accounting > Common >


Projects > All projects.
2. Select a project such as 10001: Contoso Retail Los Angeles.
3. Click Hour in the Journals group of the Action Pane.
4. Click New.
5. Enter 5.00 in the Hours field.
6. Click Post.
7. Click OK.
8. Close the Infolog window.
9. Close the Journal lines for hours form.
10. Close the Journal form.
11. Click the Manage tab on the Action Pane in the All projects list
page.
12. Click Invoice proposals in the Bill group of the Action Pane.
13. Click New > Invoice proposals.
14. Select the Hour check box, and then click OK.
15. Close the Infolog message.
16. Select the On hold check box for the new invoice proposal that was
created.
17. Click Post.
18. Click OK, and then click OK again.
19. You should receive an error message that says the invoice proposal is
on hold and cannot be posted. Close all the forms.

9-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Estimates and Revenue Recognition


The following sections describe estimate projects and cost templates.

Estimate Projects
Estimates are maintained on individual estimate projects or on batches of
estimate projects. When estimate projects are processed in batches by using
periodic jobs, the estimate projects that are selected for processing are grouped
by period code.

You can work with estimates in the following ways:

• To maintain estimates for individual estimate projects, use the


Estimate form. Open Project management and accounting >
Common > Projects > Estimate projects. Select an estimate
project. On the Action Pane, in the Related information group, click
Estimates.
• To view the periodic features that are available for estimate
maintenance, open Project management and accounting >
Periodic > Estimates. The periodic jobs that are available
correspond to the functions available in the Estimate form.

The New, Calculate, Delete, Post, Reverse, Eliminate, and Reverse


elimination buttons on the Estimate form open dialog boxes that reflect the
typical life-cycle of an estimate.

NOTE: The data in the Hyper-V training environment does not include any
estimates. You can create a new estimate by clicking New in the Estimates form.

Cost Templates
Cost templates are used in the calculations for revenue recognition for fixed-price
projects.

In Microsoft Dynamics AX, a cost template is an attribute on an estimate project.


The cost template and cost template lines determine which forecasts and which
actual transactions are included to calculate the percentage of the project that is
completed. The percent-complete value is then used to calculate how much
revenue is recognized.

Example

You are working on a website design project for a customer for a flat fee of
10,000 United States dollars (USD). You forecast that it will take 100 hours
(5,000 USD) to complete the project, and two plane tickets and four nights in
hotels for trips to the customer’s site (1,800 USD). This results in a total
forecasted cost of 6,800 USD.

9-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

When you run the fixed-price revenue recognition process to create an estimate at
the end of the month, you find that you have already worked 35 hours on the
project to this point, without flights or hotel stays. You also had an assistant
perform five hours of research for the project that you did not plan for, at a cost
of 100 USD.

When you calculate the percent complete value for this project, you have some
choices to make.

• Do you want to include all costs (hours and expenses) or just hours?
• Do you want to include all hours or just planned hours?
• Do you want to calculate the percent complete based on the dollar
cost of the planned hours (5,000 USD) or just on the number of
hours (100)?

Your answers to these questions determine the options that you set on the cost
template and the categories that you select on the cost template lines.

The following table shows the results of different methods of calculating the
percent-complete value for this scenario.

Completion Dollar cost Percent Calculation


based on or units complete
All hours, no Dollar cost 37 percent 35 x 50 USD + 100 USD =
expenses 1,850 USD
1,850 USD / 5,000 USD
All hours, no Units 40 percent 40 hours/100 hours
expenses (including five unplanned
hours)
Planned hours, Dollar cost 35 percent 35 / 100 hours
no expenses or unit or
35 x 50 USD /5,000
All hours and Dollar cost 27.2 1,850 USD / 6,800 USD
expenses percent

9-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Deciding which approach to take to create a cost template can depend on several
considerations.

• If you include unplanned hours in the cost template, you risk


reaching 100 percent complete before the project is finished. This
occurs because actual hours will be greater than planned hours.
o Therefore, if you use either of the first two methods that are
listed in the earlier table, you should change the plan (forecasted
units) when you become aware of deviations. In this case, you
would add or subtract hours based on your knowledge of what is
required to finish the project.
o If the project requires another 65 hours to complete, you would
add five hours to the plan for a total of 105. If you know that
your assistant will have to perform another five hours of
research, the total will be 110 hours, and so on.

• If you use the third method that is listed in the table, you would only
update the planned hours for your own time to keep the percent-
complete calculation accurate. Your profitability will change when
unplanned hours are logged. However, you will remain on a known
percent-complete trajectory.
• If you use the fourth method that is listed in the table, the risk is that
expenses will occur at irregular times and might not be reflected in
your completion progress.
o Therefore, if the expenses are included, they can cause your
percent complete to fluctuate more than is desirable. For
example, because you have not yet taken a flight yet, your
percent complete is 27 percent instead of 35 percent or 37
percent if you base the calculation on time alone.
o If you had taken one trip for two nights and forecasted your
flight and hotel costs accurately, the percent complete would be
40.4 percent (1850 USD for labor and 900 USD for expenses =
2750 USD / 6800 USD = 40.4 percent). Therefore, incurring the
expenses for just one plane trip would change the percent
complete from 27 percent to 40 percent.

Project Management and Accounting Add-In


The Project Management and Accounting Add-in integrates with the Project
management and accounting and Human resources modules to help you
manage projects that consist primarily of worker services. You can use features
in the Project management and accounting module, such as contract
management, quotations, budgeting, project policies, project parameters, and
categories, with the Project Management and Accounting Add-in.

You can use the Project Management and Accounting Add-in to identify and
schedule workers with specified project experience. You can also assign direct
and indirect costs for service projects, and create customer invoices for billing
scenarios that are specific to service industries.

9-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Key Features
Some key industry-specific features of the Project Management and Accounting
Add-in include the following.

• Other worker attributes – Assign attributes for project skills and


experience to a worker.
• Resource-based scheduling – Search for and assign workers to a
project, depending on worker skills and availability.
• Project-based scheduling – Search for and assign workers to a
project, depending on the skill and experience requirements for a
project.
• Resource assignment analysis – View analyses of project activities
by worker, by department, and by project.
• Indirect cost components – Identify indirect costs, define
calculations for indirect cost amounts, and allocate indirect costs to a
project.
• Billing rules – Define billing rules to calculate customer invoice
amounts for advances, project milestones, for each unit completed,
retained amounts, and administrative fees.

Summary
This chapter described the overall use and design of the Project management
and accounting module. Several types of projects exist that you can use to create
and manage project information. Projects can be linked to one another by using
subprojects to create a hierarchy of related projects. Each project is assigned to a
group that controls how the ledger postings will work for each project.

You can use the work breakdown structure to create a hierarchy of tasks or
activities that will be completed for a specific project. Activities can be
associated to resources that can be linked to resource requirements for
forecasting and scheduling the tasks.

Projects can have many transactions posted to record the various costs and
revenues for the project. The transactions can include hours, expenses, items, fee,
and on account payments. Journals are used to post these transactions. After
transactions are recorded, you can create invoice proposals and invoices to record
the project transactions against the customer's account and into the general
ledger. This requires that a project contract is set up first.

You can also record budgets and forecasts for projects to provide better reporting
and to set limits and controls on transactions.

You can use estimate projects to record estimates into the general ledger based
on cost templates that define how the revenue is to be recognized for a specific
project. Later when the project transactions are recorded, you can eliminate the
estimates.

9-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Describe the difference between project budgeting and project forecasting.

2. Which of the following statements are true about work breakdown


structures? (Select all that apply)
( ) Activities are shared between projects.
( ) Each project transaction can be associated with one activity.
( ) Project budgets can be associated with activities.
( ) Project forecasts cannot be associated with activities.

3. Which class hierarchy is used to control the functionality for each type of
project?
( ) ProjLineType
( ) ProjTableType
( ) ProjPostingType
( ) ProjTransactionType

4. What happens to the project transactions when a project is invoiced?


( ) The records are deleted from the ProjProposal... tables and copied into
the ProjInvoice... tables.
( ) The records are updated in the ProjProposal... tables with the final
invoice ID and the invoiced status.
( ) The records are updated in the ProjProposal... tables and copied into
the ProjInvoice... tables.
( ) Reversal records are created in the ProjProposal... tables and new
records are created in the ProjInvoice... tables.

9-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

5. Which of the following statements are true about project contracts? (Select
all that apply)
( ) All projects must have a minimum of one project contract defined.
( ) Many projects can be related to the same project contract.
( ) Each project contract must have a minimum of one project funding
source defined.
( ) Each project or subproject can only be related to one project contract.

6. Which of the following statements are true about all journals and transactions
for projects? (Select all that apply)
( ) Users can override sales and cost prices in the journals.
( ) All transaction types can use validation functionality.
( ) On account transactions can be applied to all project types.
( ) The line property indicates whether the registered transaction can be
invoiced or not.

9-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

9-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 9: Use and Design of the Project Management and Accounting
Module

Solutions
Test Your Knowledge
1. Describe the difference between project budgeting and project forecasting.

MODEL ANSWER:

Project budgeting helps companies monitor and control project revenue and
expenditures. By comparing budget and actual amounts, your organization
can reallocate money and resources to meet budgetary goals.

Project forecasting is a process that is used to forecast expected labor,


machines, expenses, and cash flow that is needed to run projects. Project
forecasting is expected to help optimize the running of a project by using
resources effectively, and by controlling expenses so that a reasonable profit
margin can be earned.

2. Which of the following statements are true about work breakdown


structures? (Select all that apply)
( ) Activities are shared between projects.
(√) Each project transaction can be associated with one activity.
(√) Project budgets can be associated with activities.
( ) Project forecasts cannot be associated with activities.

3. Which class hierarchy is used to control the functionality for each type of
project?
( ) ProjLineType
(•) ProjTableType
( ) ProjPostingType
( ) ProjTransactionType

4. What happens to the project transactions when a project is invoiced?


( ) The records are deleted from the ProjProposal... tables and copied into
the ProjInvoice... tables.
( ) The records are updated in the ProjProposal... tables with the final
invoice ID and the invoiced status.
(•) The records are updated in the ProjProposal... tables and copied into
the ProjInvoice... tables.
( ) Reversal records are created in the ProjProposal... tables and new
records are created in the ProjInvoice... tables.

9-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Which of the following statements are true about project contracts? (Select
all that apply)
( ) All projects must have a minimum of one project contract defined.
(√) Many projects can be related to the same project contract.
(√) Each project contract must have a minimum of one project funding
source defined.
(√) Each project or subproject can only be related to one project contract.

6. Which of the following statements are true about all journals and transactions
for projects? (Select all that apply)
(√) Users can override sales and cost prices in the journals.
( ) All transaction types can use validation functionality.
( ) On account transactions can be applied to all project types.
(√) The line property indicates whether the registered transaction can be
invoiced or not.

9-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

CHAPTER 10: USE AND DESIGN OF THE


PRODUCTION CONTROL MODULE
Objectives
The objectives are:

• Review the basics of bill of materials and the data model


• Introduce routes and operations.
• Describe the major features of production orders.
• Review scheduling methods, resources and jobs.
• Describe master planning and the planned production order journal
model.
• Introduce lean manufacturing, Kanban, and production flow models.
• Review Process Industries in Microsoft Dynamics® AX 2012.

Introduction
Production control in Microsoft Dynamics AX 2012 consists of many aspects of
the production environment. This includes creation, estimation, scheduling,
consumption, feedback, and cost accounting for production orders.

10-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The major processes of the Production control module are shown in the
following figure.

FIGURE 10.1 PRODUCTION CONTROL OVERVIEW

In this chapter, you will review the following major components of the
Production control module.

• Bill of materials: A list of all parts, components, and raw materials


needed to produce a product.
• Routes: The path that the item takes from operation to operation
throughout the production life cycle.
• Production orders: A source document that defines what is to be
produced, how much (quantity), and a planned finished date.
• Scheduling: An iterative activity where the system tries to find a set
of resources that can deliver the product on or before the requested
date.
• Planned production orders: A special type of "pre" production
orders that is used to generate firmed production orders that is based
on demand and other factors.
• Lean, Kanban, and Production flow: Introduce industry best
practices for pull based production.
• Process Industries: Review of how Microsoft Dynamics AX 2012
can support process manufacturing principles.

10-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Bill of Materials
A bill of materials (BOM) is a complete list of all the components, parts, raw
materials, assemblies and their quantities that are required to make a finished
product.

BOMs define the relationship between the components and the finished product
or sub-assembly. The item number that represents the BOM is often referred to as
the finished product, and the components that make up the finished good are
referred to as raw materials. In some cases the item number that represents a
BOM is not a finished good and is instead referred to as a sub-assembly which is
used in another BOM to create a finished product or another sub-assembly. A
clear definition of this relationship is important for the following.

• Allocation of materials
• Scheduling of operations or jobs
• Creation of production orders
• Costing of the BOM and production order

Every item that must be physically accounted for in a finished product or sub-
assembly product or financially accounted for in the costing phase must be
included in the BOM. Although BOMs define the components and their
relationships, they do not define the sequence of steps to produce or assemble the
finished item.

BOMs are made up of product types, versions, configurations, sites, levels, lines,
and information used for cost calculations. In the following sections, these
components and the data model for BOMs are reviewed to illustrate the
relationship between the tables.

BOM Product Types

BOMs can contain two types of products in Microsoft Dynamics AX 2012,


depending on whether the item is purchased or produced in-house or defined as a
service. The product types that are used in a BOM include the following.

• Item: An item in a BOM that is defined as the product type Item is


purchased from an outside source or produced in-house, depending
on the default order settings type. When the default order type is set
to purchased, then the item is purchased. When the default order type
is production or Kanban, then the item is manufactured.
• Service: An item in a BOM that is defined as the product type
Service represents and quantifies a service that is a part of the
manufacturing process. For example, you are producing
personalized, hand painted coffee mugs. The BOM for the finished
product coffee mug includes three products.
o Blank Mug: That has a product type of item.
o Paint: That has a color dimension and a product type of item.

10-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

o Painting: That has a product type of service because the


painting is not tangible and not stocked in the inventory. The
painting must be accounted for and the users must select the font
for the painting in the configuration. Certain fonts cost more, and
must be financially accounted for in the BOM.

BOM Version

A BOM can have multiple versions. When you create a BOM, you must have at
least one version. In order to use the BOM it must be approved and activated.
Later, if the BOM is no longer required, the activation and approval can be
removed. The BOM version is used to define which finished product item
numbers are linked to the BOM. You can also specify information about the date
of validity, site, quantity ranges, whether the version is active, and who approved
it.

Zero or more BOM versions can be valid or active for any item at any given
point in time. However, only one version can be applied. The applied version is
selected based on time, site, and quantity. The BOM version is useful in these
cases.

• Two products that consist of the same raw materials but different
production processes will be able to use the same BOM but different
routes. For example, the same product is produced in two different
sites by using different equipment.
• When changing the raw materials of a product over time, different
BOMs can be attached as of a specific date. In the example of the
personalized coffee mug, the paint that is used for the mug was
originally paint X, and now they are going to use paint Y to make the
mugs. This change can be reflected in a new BOM version as of the
date that the change occurs.

BOM Configuration

For planning, calculation, and consumption purposes, each BOM line must
specify whether the item has any configurations. A configuration is a standard
component combination, such as a satellite speaker and a sub-woofer that can be
specified for a BOM item during the ordering process. For example, the user
might select the size and color of speaker to be included in the home theater
system.

BOMs with Sites

A finished product can be set up so that parts of the finished good can be
produced at different production sites. A typical scenario for production at
multiple sites might involve an end item that includes component items, where
the component items are produced at and moved between different sites, and the
sites share common item numbers. Each BOM version can be linked to a specific
site, or each line of BOM can have a different site assigned.

10-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

BOM Levels

BOMs can contain many levels of goods to produce. A simple BOM is all on
level one. For example, when assembling a cabinet, you will have the frame,
shelves, and hardware. These are all on the same level, because each primary
component is in the assembly.

When a BOM contains another BOM as its component, then it is known as a


multilevel BOM, where the sub BOM is referred to as level one and its
components as level two. BOMs can consist of as many levels as necessary,
depending on the type of product being produced. For example, adult bicycles
consist of two wheels, a seat, handlebars, and a frame. All these components are
reflected in the bicycle BOM. However, the frame also consists of several
discrete items (three or four tubes welded together). Therefore, the frame has a
BOM of its own. It is known as a sub BOM, that is, a bill of material within the
bill of material for the end-product, the bicycle.

BOM Lines and Line Types

The lines in the BOM are the individual items or services that make up the BOM.
Each product has its own BOM line. An unlimited number of lines or items can
make up the BOM.

There are four types of BOM lines in Microsoft Dynamics AX 2012.

• Item: The item is a raw material or semi-finished item that must be


picked from inventory.
• Phantom: An item is a transient (non-stocked) BOM item. A
phantom BOM represents an item that is assembled, but frequently
not stocked in inventory until it is actually needed in the
manufacturing process. Phantom BOMs are used so that the Material
Requirement Planning (MRP) logic can calculate requirements for
the needed components. When a BOM includes a phantom item, no
separate production order is created for the phantom item. Instead,
the main BOM is "expanded" with the BOM lines from the phantom
item's BOM. The Phantom line type can only be specified for an
item.
• Pegged supply: Select pegged supply when you want to include an
item for which the pegging rules should apply, regardless of the type
of production. When a BOM line is set to pegged supply then that
item will be pegged (signaling a product demand requirement)
according to the method of production (lean or normal), or purchased
when the default order type is set to Purchase. Referring to the
example of the coffee mug again, when you are producing made-to-
order coffee mugs, the painting of the coffee mug can be marked as
Pegged supply to indicate that the production order should not be
created unless there is a demand (sales order) for a personalized
coffee mug.

10-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Vendor: A vendor provides the component item and the method


through which the item is provided depends on the default order type
for the component item. The production is conducted by using a sub-
contractor. This option can also be used for the product type Service
and for a sub-BOM.

BOM Costing

Bills of material calculations use data from several sources to calculate the
rolled-up or total costs of a manufactured item. The sources include information
about items routing details, indirect cost calculation formulas, and the costing
version. The purchased item information that is used in a standard cost BOM
calculation includes cost, cost group, and warning conditions.

The manufactured item information that is used in a standard cost BOM


calculation includes standard order quantity for inventory and warning conditions
that are embedded in the item's BOM calculation group.

The bill of material information that is used in a standard cost BOM calculation
depends on the following.

• BOM version
• BOM line item quantity
• BOM line item scrap
• BOM line item valid dates
• The default order type of the BOM line item
• Parameters for the cost calculation
• Sub-route for a manufactured component
• Effect of operation scrap percentages

BOM Data Model


The key components of the Bill of Materials Data Model are four tables, the
BOMTable, the BOM, BOM Version and the ProdBOM table. Other BOM tables
involve calculations, costs, parameters, and related information that support these
primary tables.

10-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

The following figure shows the relationship between the BOMTable, BOM and
BOMVersion. These do not include all the available fields for the tables, because
of size limitations and relevance.

FIGURE 10.2 BOM DATA MODEL

The BOMTable is the primary table of the construct. Contained within is the
setup for a Bill of Material, including Approved, BOMId, Name, Version, and
SiteId. This is best described as the header information that you must define for
the BOM. For example this is an Eight inch woofer speaker assembly.

The BOM is the line items associated with the primary table. You can have many
line items that are related to each BOMTable. Each BOM record is related to one
InventTable record to create the link for the components to the raw materials
items and services. For example, the woofer speaker assembly might include the
speakers, cabinet, and cross over assembly needed to construct the speaker. For
the speaker assemblies, they can be used for other cabinets or other
configurations.

The BOMVersion is the final table needed for the basic BOM set up. The
relationship between the BOMTable and BOMVersion is one or more versions
for each BOM. Each BOMVersion record is related to one InventTable record to
create the link to the finished product item number. For example, one version
could be used for one site and a different version for another site. Frequently
BOMs are phased out, with new components that are included in the latest
version.

10-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The ProdBOM table is used to store the production ready, approved BOM. It is
copied from the original BOMTable (header) and BOM (lines) tables. This
follows the goods being produced throughout the life cycle of the product. This
design allows users to modify the BOM for a specific production order without
affecting the original BOM definition. Frequently it is referred to as the product
revision. From this all items or services are picked, assembled, quality assured,
reported as finished, and ended.

Routes
Routes are the path or sequence that the product takes from operation to
operation, starting with the beginning of the production process and continuing to
the end. It is a set of sequential operations, or tasks, that are required to produce a
product. The route operations describe the requirements for the resources that are
required for performing each operation. Each route includes the following:

• Operations to be performed.
• Operations relations.
• Sequence of the operations.
• Resources requirements involved in completing the operations.
• Standard times for the set up and run of the production.

One or more routes can be mapped for each product, depending on the product
and the process. You can create a completely new route, or you can base a new
route on existing route information, and then adjust or update the information to
match the new production process. The same route can also be used for multiple
products.

In the following section, you will review how to use routes and operations and
the data model associated with them.

Routes and Operations Feature Overview


Operation to be Performed

Operations are set up in sequence to establish an appropriate order and context


for the total production process of a product. An operation is a task or process
connected with the production of an item. It includes the necessary details for an
efficient production schedule. What you should know before setting up an
operation:

• Know which task or activity must be completed


• Know how many resources are needed for performing the operation,
and what those resources must be capable of. You should create
capabilities and also create resources and resource groups before you
set up the operations, because operations are closely related to
resources.

10-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Operation Relations

Operation relations simplify and streamline the creation and maintenance of


operation base data. They are used to control which operation is customized to a
specific route or item. The main characteristics of operation relations include the
following.

• Each relation contains the information that is used by production


orders when they are created or updated. This includes the resource
requirement, route, consumption calculation, cost categories,
measurement, times, and overlap quantity that applies to the order.
o If the information that applies to the operation is general and
applies to all items, only one relation for the operation has to be
created.
o If the item or route has specific parameters for an operation that
deviates from the standard parameters for that operation,
individual relations are considered (table/group relation are
used). When the production order is created, information from
the specific relation in question is copied to the production route.

• The use of the operation relation is limited in the way it is attached to


items and routes. Each relation is attached to an item, an item group,
or all items. At the same time, each relation is attached to either a
route or all routes. This means that one operation could include
different information on times, cost categories, properties, and so on,
specified in separate relations. Therefore, the same operation can be
used in several routes by creating a relation for each route.

Sequence of Operations

Operations in a route must be attached to each other in a logical way to reflect the
production process. Depending on the complexity of the production, this can
result in a route network. For simple routes, where the operations are executed
one after the other, a route network is not required.

However, complex networks are frequently needed to reflect the production


environment. If this is the case, you can construct routes that contain several
operation branches that can be started independently.

Another network operation is concurrent operations. In this case, prerequisites


are run first, and then several operations run in parallel, ending in a completion
operation. Each operation in a route can have multiple predecessors, but only one
successor. As a consequence, a route may have multiple starting points, but only
one end-point. Therefore, only a subset of all possible networks may be modeled
as routes.

10-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure displays a simple network, a complex network, and a


network in which there are concurrent operations.

FIGURE 10.3 ROUTE NETWORKS

NOTE: Simultaneous operations can be modeled as primary or secondary


operations.

10-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Routes and Operations Data Model


The RouteTable is connected to many different supporting tables that help define
the data model. For example, the RouteVersion table contains the key
information for Item ID that restricts the route to the current and approved item.

The following figure shows all the key Route tables.

FIGURE 10.4 ROUTE TABLE DIAGRAM

Also important for this model, is the relationship between Routes, ReqRoute, and
ProdRoute tables. For example, a regular route includes how the task or activity
is completed, the order and operation priority, and the requirements for the
resources that will perform them. The ReqRoute table is primarily populated
during master planning to record which operations are used for a production
order, and when the planned order is firmed. This data is then combined with the
operation relation to make up the production route in the ProdRoute table. This
makes sure that the route does not change mid-process and still allows planners
and schedulers to be able to update the Route table. The route on a specific
production order can be modified; much like a BOM can be, without affecting
the original route.

Production Orders
The production order contains information about what is to be produced, how
much (quantity), and the planned finish date. The system assigns an order status
to each step in the life cycle of the order. The status shows where the item is in
the production process.

The following sections include an overview of production orders, orders statuses,


the data model, the journal framework, and three production order classes.

10-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Production Order Feature Overview


In-house Production Orders

In companies where production is conducted in-house, production orders are


frequently created for the following reasons.

• Meet sales demand when inventory is insufficient.


• Supply a BOM as subassemblies to other items in demand.
• Meet forecasted end item demand.
• Increase safety stock.

External Production Orders

If a production, or part of a production, is subcontracted and the component items


are released and provided to the vendor, the subcontracted item must be created
as a BOM. If the component that the vendor is producing is a sub-BOM, the line
type Vendor must be used. When the production order producing the item is
estimated, Microsoft Dynamics AX 2012 automatically creates a vendor
purchase order for the produced component item.

If the vendor's capacity is not scheduled, do not attach the route for the sub-
BOM. When no route is attached, the delivery time for the sub-BOM is taken
from the component items released products' base data.

If you want to schedule the vendor's capacity, create the route for the component
item and specify Vendor as the resource on the appropriate lines.

Production Order Statuses


The status on the production order reflects the sequential steps of the production
life cycle. The overview of the statuses a production order can have includes the
following.

• Created: Status of the production order when it is first created.


• Estimated: Status of the production order after you run a material
and cost estimation.
• Scheduled: Status after you run operation or job scheduling.
• Released: Status when production orders are scheduled and released
to production.
• Started: Status of the production order when production starts.
• Reported as finished: Status of the production order when
production is finished.
• Ended: Status of the production order after final costs are applied,
the item is complete, and the order is no longer active.

10-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

The first status of a production order is Created. When a production order has
this status, you can edit the production's BOM and route. However, changes to
the production's BOM or routes when it has any status other than Created, require
that the previous update jobs be run again. For example, if you make changes in a
BOM or route for a production in which the status is Released, then the prior
steps Estimated and Scheduled must be run again. Not all steps are required for a
production order. The steps that are required are based on the configuration of the
Production control parameters.

The following topics provide a review of the production control steps, with an
emphasis on how each step applies to financial journals and the interaction with
the general ledger.

Step 1 – Created

When you create production orders, you can specify the settings that determine
how production order transactions are posted to the ledger. These settings apply
to production orders created manually or automatically from a sales order or
master planning schedule.

Step 2 – Estimated

This step involves the calculation of the most likely material and labor for the
production. The system creates inventory transactions that are issue transactions
for raw materials with the status of On order and receipt transactions for the
BOM with the status of Ordered. In some cases, the system will create purchase
orders and subproductions for the production order. Items are reserved and the
prices of the finished goods are calculated based on parameter settings.

Step 3 – Scheduled

The third step in the production order life cycle is Scheduled. Production orders
can be scheduled based on operations scheduling or job scheduling.

• Operations scheduling: This scheduling method creates a rough


long-term plan. By using this method, the system assigns start and
end dates to production orders.
• Job scheduling: This scheduling method provides a detailed plan.
Each operation is broken down into individual jobs with specific
dates, times, and assigned resources. If finite capacity is used, jobs
are assigned to resources based on availability.

Step 4 – Released

In this step, the system releases the production order when the schedule is
realistic. At this point, you can print production order documents such as the job
card and the route card. Now, the status of the production order changes to
Released and indicates that the production can start.

10-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Step 5 – Started

When a production order is started, you can post costs against the order. You can
automatically allocate estimated material and route costs to the order when it is
started. This allocation is known as forward flushing or auto consumption. You
can manually allocate material to the order by creating picking list journals. You
can also manually allocate labor and other route costs to the order. If you use
operations scheduling, you can allocate these costs by creating a route card
journal. If you use job scheduling, you can allocate these costs by creating a job
card journal.

Step 6 – Reported as Finished

When the production order is reported as finished, the quantity of finished goods
completed is updated in the Inventory and warehouse management module. If
you use work-in-process (WIP) accounting, the system uses the standard cost
from the On-hand form to create a ledger journal to reduce the WIP accounts
and increase the inventory of the finished goods.

If the material and labor costs associated with the production are not already
allocated in a journal or by forward flushing, they can be automatically allocated
by back-flushing. This involves the post-deducting of inventory transactions
processes.

Step 7 – Ended

Before you end production, the system calculates the actual costs for the
produced quantity and all estimated costs of material, labor, and overhead are
reversed and replaced with the actual costs. If you select the End job check box
when you run the cost calculation, the production order status changes to Ended.
This status prevents any additional costs from being unintentionally posted to a
completed production order.

10-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Production Order Data Model


The following figure shows the data model for the primary tables related to
production orders.

FIGURE 10.5 PRODTABLE RELATIONSHIP DIAGRAM

The ProdTable is the primary production order table, which contains the header
information about all of the production orders. Each production order contains is
related to at least one InventTransOrigin and InventTrans table record. Each
production order can be connected to a planned production order, a sales order or
a project.

When a production order is created from master planning, the planned production
order is stored in the ReqPO table. The ProdTableProj table contains information
about production orders that belong to projects. Such a production order is
connected to a real production order stored in the ProdTable table and to a project
stored in the ProjTable table.

The ProdBOM table contains a productions bill of materials. This information is


copied from the BOM and BOMTable.

10-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The ProdRoute table contains production route information. This information is


copied from the Route and RouteTable. The WrkCtrActivity table is an interface
to activities that are defined in other tables. The WrkCtrProdRouteActivity table
works as an interface to the ProdRoute table. The WrkCtrActivityRequirement
table is a supertype for activity requirements.

Production Order Journal Framework


Production journals contain a record of each different type of transactions that
occur when you are working with production orders. These transactions have a
direct effect on the company's financial records.

Production journals are located by opening Production control > Common >
Production orders > All production orders. Click the View tab in the Action
Pane, and then you can view the journal types in the Journals group. The
production journal types include the following.

• Picking list: This journal is a record of the raw materials removed


from the inventory.
• Route card: This journal is a record of the route consumption.
• Job card: This journal is a record of the resource consumption by
using feedback job cards.
• Reported as finished: This journal is a record of finished items.

When a production journal posts, all transactions are automatically transferred to


the General ledger. The General ledger is the centralized location for financial
information in Microsoft Dynamics AX 2012. Information posted from various
journals in the system is used in the General ledger when companywide financial
transactions are calculated.

Production journals consist of two main parts—the journal header and the journal
lines, or actual journal records. Journal lines reflect the actual records or entries
present in the journal. These records can include a list of production materials
ready for release, the time consumed, the number of good and defective items,
and so on.

Production Order Classes


The following are three important production classes, including sample code.

ProdMulti

You can update production orders one at a time or update multiple orders one
time. You can use the RunBaseMultiParm structure to run different parameter
(parm) tables that use the same structure. The ProdMulti class is the base class
that you can use to update production orders. It is based on the
RunBaseMultiParm class. A user interface (UI) should be implemented for
derived classes.

10-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Syntax:

class ProdMulti extends RunBaseMultiParm

Much of the functionality is the same as what is implemented in Microsoft


Dynamics® AX 2009, with a large increase from six extensions on the base
ProdMulti class to eleven.

From the base UI form, it makes a call to ProdMulti for all updates. For example,
updating to Estimated calls ProdMultiCostEstimation::main().

1. View the ProdMultiCostEstimation::main() method:

public client server static void main(Args _args)


{
ProdMultiCostEstimation prodMultiCostEstimation;

if (_args.parmEnum() == RunChoose::Run)
{
prodMultiCostEstimation =
ProdMultiCostEstimation::construct(_args);

RunBaseMultiParm::initFromForm(prodMultiCostEstimation,_arg
s);

if (! prodMultiCostEstimation.prompt())
return;

prodMultiCostEstimation.runOnServer();
prodMultiCostEstimation.refreshCaller(_args);
}
else
{
RunBaseMultiParm::runSpecial(_args);
}

ProdMultiCostEstimation is instantiated, and then passed into the static method


RunBaseMultiParm::initFromForm(), together with args.

2. View the RunBaseMultiParm::initFromFormInternal() method:

/// <summary>
/// Initializes an instance of the <c>RunBaseMultiParm</c>
class by using a container of packed records.
/// </summary>
/// <param name="_includeRecords">
/// A Boolean parameter that indicates whether records are
included.
/// </param>

10-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

/// <param name="_packedRecords">


/// A container of packed records.
/// </param>
private void initFromFormInternal(boolean
_includeRecords,

container _packedRecords)
{
Common common;
int recordCounter;
ParmBuffer parmBuffer;

//sets the parm id


RunBaseMultiParm::initParm(this);

//init and insert update parameters that goes for all


updates.
this.insertParmUpdate(this.defaultParmUpdate());

if (_includeRecords)
{
parmBuffer = this.defaultParmBuffer();
parmBuffer.Linenum = 0;

for (recordCounter = conLen(_packedRecords);


recordCounter >= 1; --recordCounter)
{
parmBuffer.Linenum++;
common = conPeek(_packedRecords,
recordCounter);
this.insert(common,parmBuffer);
}
}
}

parmBuffer is a table map that is mapped to the different parm tables.


RunBaseMultiParm.defaultParmBuffer() is overridden in the sub-classes and
returns the appropriate parm table.

RunBaseMultiParm::initParm() retrieves saved data (from sysLastValue by


calling getLast()) and sets the ParmId used in the update.

static server void initParm(RunBaseMultiParm


runBaseMultiParm)
{
runBaseMultiParm.getLast();
runBaseMultiParm.initParmId();
}

All selected records in the form data source are added to the appropriate parm
table. If the update is called from the main menu, there is no data source and no
records are found.

10-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

3. Return to the ProdMultiCostEstimation::main() method.

public client server static void main(Args _args)


{
ProdMultiCostEstimation prodMultiCostEstimation;

if (_args.parmEnum() == RunChoose::Run)
{
prodMultiCostEstimation =
ProdMultiCostEstimation::construct(_args);

RunBaseMultiParm::initFromForm(prodMultiCostEstimation,_arg
s);

if (! prodMultiCostEstimation.prompt())
return;

prodMultiCostEstimation.runOnServer();
prodMultiCostEstimation.refreshCaller(_args);
}
else
{
RunBaseMultiParm::runSpecial(_args);
}

The prompt displays the form where the user can change the settings to update
the order. There is also a Select button on the form that the user can click to
modify the query and select more records. When the form is opened from the
main menu (Production control > Periodic > Production orders), the query is
empty and the user must click this button to select the records for update.

The run() method is then called.

4. View the ProdMultiCostEstimation.run() method:

...
while (curParmCostEstimation)
{
try
{
prodTable =
this.initProdTable(curParmCostEstimation.ProdId);

prodTable.status().runCostEstimation(curParmCostEstimation,
false,prodPurch,this);
}
catch (Exception::Deadlock)
{
retry;
}
...

10-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

next curParmCostEstimation;
}
}

All records in the parm table are looped over. The ProdStatusType sub-class is
instantiated by using the status of the prodTable record, then the update is called.

ProdStatusType

Production order updates are controlled by using the ProdStatusType class and
subclasses.

Each stage of the update process must occur. If the current status of an order is
Estimated, and you try to update it to Report as Finished, then it must be
Scheduled, Released, and Started before it can be reported as Finished. The
required status and status sequences are configured in the Production control
parameters form.

Before each update is run, the system checks to determine whether the previous
status is already processed. If the update is not installed, then the system runs that
update. It also handles which updates can occur with a production order. For
example, a production order with the status Finished, cannot be Estimated.

Update a Production Order with a Status of Released to a


Status of Report as Finished

The update to the status is called by ProdMultiReportFinished, which is


discussed in the next section.

The following steps demonstrate the use of ProdStatusType.

1. View ProdMultiReportFinish.Run().

...
while (prodParmReportFinished)
{
try
{

this.initProdTable(prodParmReportFinished.ProdId).status().
runReportFinished(prodParmReportFinished,false,this);
}
catch (Exception::Deadlock)
{
retry;
}
...
next prodParmReportFinished;
}
}

10-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

ProdMultiReportFinished.Run() instantiates the ProdStatusType_Released


subclass by using the status of the production order, and calls
ProdStatusType.runReportFinished().

2. View ProdStatusType.runReportFinished().

...

if (!_ask)
{
if
(this.shouldRunPreviousJob(ProdStatus::ReportedFinished))
{
ProdUpdReportFinished::runPreviousJob(

_prodParmReportFinished,

_multi);
}
prodTable.type().runReportFinished(

_prodParmReportFinished,

_multi);
}

return true;

...

ask is set to true only when the method is called to ask whether the update is
allowed, not to run the update.

ProdUpdReportFinished::RunPreviousJob runs the update to the status Started.

3. View ProdUpdReportFinished::RunPreviousJob.

static void runPreviousJob(


ProdParmReportFinished
prodParmReportFinished,
RunbaseRecsMapable _multi
= null)
{
ProdParmStartUp prodParmStartUp =
ProdUpdStartUp::initParmBufferFromRepFin(prodParmReportFini
shed);

prodParmStartUp.insert();

ProdTable::find(prodParmStartUp.ProdId).status().runStartUp
(

prodParmStartUp,

10-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

false,

null,

_multi);
}

A record in ProdParmStartUp is created by using the ProdParmReportFinished


record that is used for the update to Report as Finished.

The ProdStatusType_Released sub-class is instantiated by using the status of the


production order and calls ProdStatusType.runStartUp().

4. View the ProdStatusType.runStartUp() method.

if (!_ask)
{
if (this.shouldRunPreviousJob(ProdStatus::StartedUp))
{
ProdUpdStartUp::runPreviousJob(

_prodParmStartUp,
_prodPurch,
_multi);
}
prodTable.type().runStartUp(

_prodParmStartUp,
_multi);
}

return true;

Because the previous status to Started is released, and because this order is
already released, it is not necessary to run the previous job.

As soon as the update to the status Started occurs, it returns to


ProdStatusType.runReportFinished(), then runs the update to Report as Finished.

10-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

ProdUpd

The ProdUpd class is the base class of production classes used to update the
production order status. The following figure shows the class hierarchy for the
ProdUpd class.

FIGURE 10.6 PRODUPD CLASS HIERARCHY

The ProdUpd class is an abstract class, and you cannot make an instance out of it.
You can only inherit this class from other production update classes. To update
production order stage, the following classes are used:

• ProdUpdBOMCalc
• ProdUpdCostEstimation
• ProdUpdScheduling
o ProdUpdScheduling_Operation
o ProdUpdScheduling_Job

• ProdUpdRelease
• ProdUpdStartUp
• ProdUpdReportFinished
• ProdUpdHistoricalCost

To decrease production order status, the following classes are used:

• ProdUpdStatusDecrease
o ProdUpdStatusDecrease_CostEstimate
o ProdUpdStatusDecrease_Finished
o ProdUpdStatusDecrease_Release
o ProdUpdStatusDecrease_Schedule
o ProdUpdStatusDecrease_StartUp

10-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When a production order is updated, there are two main events that can occur.

• The status is updated to the new status.


• Journals can be created and posted to consume items and operations
as required, depending on the settings on the update, the production
parameters, and the item. For example, updating to Started could
post the picking list journal and consume all items in the BOM at this
point.

ProdStatusType.RunStartUp() runs the update to the Startup status.

The following steps demonstrate the use of ProdUpd.

1. View the ProdStatusType.RunStartUp() method. This method was reviewed


earlier in the "ProdStatusType" topic.

ProdUpdStartUp is instantiated by using the parm table, and then run.

2. View the ProdUpdStartUp.run() method.

void run()
{
#OCCRetryCount
RecordViewCache viewCacheProdRoute;

setprefix(ProdMultiStartUp::description());
setprefix(#PreFixField(ProdParmStartUp,ProdId));

try
{
ttsbegin;
this.setParameters();
if (! this.validate())
{
throw Exception::Error;
}

viewCacheProdRoute = null;
viewCacheProdRoute =
ProdRoute::viewCacheProdId(prodTable.ProdId,true);

this.updateProduction();
this.updateBOMConsumption();
prodTable.status().startUpUpdateRouteJobs(this);
this.updateRouteConsumption();
this.startupReferences();
this.updateJobJournal(ParmJobStatus::Executed);

TransactionLog::create(TransactionLogType::ProdStartUp,

strfmt("@SYS76498",

10-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

prodTable.ProdId,

"@SYS77138"));

ttscommit;
this.printout();
}
...

ProdUpdStartUp.setParameters() retrieves ProdTable and initializes BomCalc. It


is called when component dimensions are used in the calculation of item
consumption.

viewCacheProdRoute activates cache on all prodRoute records for the current


production order.

3. ProdUpdStartUp.updateProduction updates the prodTable.Status,


prodTable.StartedUpQty, and prodTable.StUpDate.

void updateProduction()
{
if (prodParmStartUp.StartUpProduction)
{
prodTable.QtyStUp += prodParmStartUp.StartUpQty;
}

prodTable.ProdStatus =
prodTable.status().isBefore(ProdStatus::StartedUp) ?
ProdStatus::StartedUp : prodTable.ProdStatus;
prodTable.StUpDate = prodParmStartUp.PostDate ?
prodParmStartUp.PostDate : systemdateget();

prodTable.update();

this.addUpdateRec(prodTable);
}

4. ProdUpdStartUp.updateBOMConsumption() creates the picking list journal. If


the update is set to post the BOM consumption, it also posts the journal.

5. The production route is updated and the route journal is created and posted.
(This sample comes from the ProdUpdStartUp.run method reviewed earlier.)

this.startupReferences();

this.updateJobJournal(ParmJobStatus::Executed);

TransactionLog::create(TransactionLogType::ProdStartUp,
strfmt("@SYS76498", prodTable.ProdId, "@SYS77138"));

ttscommit;

10-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Any references (meaning production orders that are created because of this
production order) are also updated, and the parm table record is updated to show
it is posted.

Scheduling
Scheduling is an iterative activity where the system tries to find a set of resources
that can deliver the product on or before the requested date. In the following
sections, you will review the main production scheduling concepts that provide
an overview of scheduling, resources, the resources data model, and jobs.

Scheduling Overview
The scheduling engine is aligned with the new resource model in Microsoft
Dynamics AX 2012. This introduces capabilities and priorities, and replaces
work centers and work center groups by using resources and resource groups.

You can run scheduling after the production order is created and estimated.
Production dates and other information important to the production process are
established at this point. The role of the scheduling system is to plan the actual
production process so that each operation in the production route is assigned a
starting and ending date and time, and that the materials needed for production
are available when the operation starts.

Another important role of the scheduling system is to assign jobs and operations
to a resource or resource groups. This depends on whether job scheduling or
operation scheduling is used. Running scheduling raises the production status to
Scheduled.

Resources Overview
Microsoft Dynamics AX 2012 introduces resources that are assigned to jobs and
operations. Resources can be different types including machines, tools, human
resources, vendors or locations. The scheduling engine aligns with the new
resource model and can schedule resources based on their capabilities. Resources
and capabilities replace work centers and task groups to provide for more
flexibility in setup and maintenance. In Microsoft Dynamics AX 2012, resources
can be allocated to jobs and operations by matching the capabilities of the
resources with the requirements of the operation.

Alternative resources with the same capabilities are considered, unless there are
requirements for a specific resource or resource group. This applies whether you
select to run job scheduling or operations scheduling. The selection process
consists of matching the requirements of the operation with the capabilities of the
resources. Other requirements, such as location, resource working time, and
resource type are also considered when planning the production. Microsoft
Dynamics AX 2012 has changed the following to the Operations Resource
Model.

10-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

• Separated the way resources are grouped for managing capacity from
the way resource requirements are specified for activities.
• Enabled resources to change resource groups and thereby location
(Site) over time.
• Eliminated the need for defining resources multiple times.

In the following section, you will review resources and recourse capabilities.

Resources

Resources are used throughout the production or project processes. They can be
machines, tools, people, vendors or locations that contribute to the production of
an item. After an operations resource is created, you can assign it to a resource
group and specific productions.

Resource groups have fixed location. You can move resources to another location
by reassigning them to a different resource group. However, a resource can only
be assigned to one resource group at a time. The Effective and Expiration date
fields on the Resource groups tab represent when the resource in question can
be used for production.

With this setup you can share a resource across many sites. When a resource
becomes a member of the resource group that has a different location, it
represents the physical move from one site to another. You can also copy
resources to make the setup of resources easier.

During the scheduling process, the capacity of a resource group is calculated as


the sum of the capacity of its resources. Resources are used in the detailed
planning of capacity requirements and in job scheduling. When job scheduling is
run, the operations in each resource are scheduled into individual tasks or "jobs."

Five types of resources are available.

• Vendor: Select this type when the resource is an external operations


resource, for example, with a subcontractor.
• Human resources: Select this type when the operations resource is a
worker. Typically, you schedule the human resources type if the
personnel capacity is limited.
• Machine: Select this type if the resource is considered a production
machine.
• Tool: Select this type if the resource is considered a tool. If you want
to schedule for tools, machines, or personnel at the same time, select
a primary operations resource that determines the capacity available.
• Location: Select this type if the resource is considered a location.

10-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Resource Capabilities

Resource capabilities are a new concept in Microsoft Dynamics AX 2012. A


capability is the ability of a resource to perform a given activity relevant to
production and the scheduling of resources for production.

When designing a route, the requirements that resources must have to perform
the various operations in the route can be expressed as the set of resource
requirements. This allows the allocation of resources to be deferred until
production is scheduled.

You can define capabilities to organize the resources for your operation.
Resource planning and production scheduling depend on correctly defined
capabilities because the requirements of a production are matched with the
capabilities of a resource.

A capability must be assigned to a resource to effective. Two different resources


can have the same capability, but the specifics, such as grade, priority, or
effective date for the capability may be different for the two.

For example, a sheet metal press may have the “Aluminum sheet press”
capability assigned and have a grade of 50, whereas an older sheet metal press
would have the same capability assigned, but the older sheet metal press can only
manage a grade of 30.

Capabilities can also be assigned to resources on a temporary basis by defining a


start date and expiration date on the capability assignment. Capabilities that have
expired on a resource will prevent the resource being scheduled for production if
the production requires that capability. An expired capability can be renewed at a
later date. Additionally, a capability can also be assigned to any type of resource.

EXAMPLE:

On a route, the drilling process time is set to 10 units per hour, but the
requirement itself is defined as “Drilling”.

The capability “Drilling” is assigned to two different machine resources: M1


and M2.

M1 can drill two units per hour and M2 can drill 11 units per hour.

Both machines can be picked up by the scheduling engine because both satisfy
the requirement: “Drilling”. However, the M1 machine can only drill two units
per hour, far less than the 10 units per hour specified on the route. This will
cause production problems. To resolve this, two separate capabilities should be
created: “Low-speed drilling” and “High speed drilling”. “Low-speed drilling”
is defined by a drilling process time of one to nine units per hour. “High speed
drilling” is defined by a drilling process time of 10 to 19 units per hour.

10-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

In this setup, the M1 machine is given the “Low-speed drilling“ capability and
the M2 machine has the “High-speed drilling” capability. The scheduling engine
will then select the correct machine (M2).

Resource Requirements

When defining the requirements for a production route, you can also specify
skills, courses, certifications or title as requirements in addition to capabilities.
This does not require a relation to a worker. These values are set up in the
Human resource module and are not defined in the Capabilities form. When
defining skills, courses, certifications or title as requirements, you must have the
Human resources module enabled. You can define capabilities in the
Capabilities form that resemble or duplicate those from the Human resources
module. However, the Capabilities form does not contain the functionality that
is required to maintain skills, courses, certifications or titles.

• Skills: You can use the Skills form to create and manage
competencies that are specified for employees or jobs. An operation
can require a human resource with a specific skill, and the
scheduling engine will find resources with the specific skills. It does
this by searching for the skill information on the worker to which the
resource is linked. This is only applicable for job scheduling, and not
operation scheduling.
• Courses: You can create and maintain the courses your employees
have attended. An operation can require a human resource with a
specific course, and the scheduling engine can find resources with
specific courses. It does this by searching for the course information
on the worker to which the resource is linked. This is only applicable
for job scheduling.
• Certificate: You can add certificates to a user in human resources
and use this to track all employee certificates. An operation can
require a human resource with a specific certificate, and the
scheduling engine can find resources with specific certificates. It
does this by searching for the certificate information on the worker to
which the resource is linked. This is only applicable for job
scheduling.
• Title: The title an employee has can also be a requirement for a job.
An operation can require a human resource with a specific title, and
the scheduling engine can find resources with specific titles. It does
this by searching for the title information on the worker to which the
resource is linked. This is only applicable for job scheduling.

10-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Resources Data Model


The resources data model is changed significantly in Microsoft Dynamics AX
2012. It moved from a work center model to a resources model that is more
flexible, date effective, and able to handle production operations.

To make sure the system can be easily upgraded from earlier versions, the table
names have not changed. For example, ResourcesTable continues to be called
WrkCtrTable in the physical data model, with the changes in the content of the
table, and in many new relationships.

An example of the new relationship model is the work center resource group,
represented by the WrkCtrResourceGroup table. Now through the association
with the Resource Calendar, WorkCalendarTable (new), and
WrkCtrResourceGroupResource, any resources can have scheduled working
times based on the calendar that is attached to a specific resource. Now the model
can support equipment downtime, swap outs, and upgrades. Additionally, it also
incorporates a more realistic model of human resource management where
workers and other personnel are not available continuously.

The following diagram shows the new resource table associations.

FIGURE 10.7 RESOURCES TABLE ASSOCIATIONS

10-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Jobs Overview
Scheduling types differ from one another as measured by detail. Operations
scheduling is limited to scheduling by date (while calculating the duration of the
individual operation), whereas job scheduling calculates the starting and ending
times of individual operations throughout the day. Additionally, there is a
significant difference in the way operations are planned and in how scheduling is
performed in resource groups. Job scheduling splits the different operations into
jobs, and they are planned in detail, for each of the operation resources. When
allocating resources to an operation, the system examines the following resource
requirements types.

• Specific resource
• Specific resource group
• Resource type
• Capability
• Skill
• Course
• Certificate
• Title

These requirements types are important to many companies.

EXAMPLE: Food and drug companies because their modern production


facilities must be in compliance with the United States Food and Drug
Administration (FDA), Code of Federal Regulation, (CFR) Title 21, Part 11,
requirements that involve the validation and control of safe practices. The system
is designed to make sure that workers are educated in their respective positions
and can validate they are current on all training, certifications, and have
sufficient authority (through title) to complete operations.

Planned Production Orders


In Microsoft Dynamics AX 2012, master planning acts as the planning engine for
automated integration to the Production control module, and it calculates the
following.

• What to produce: Based on information about open sales orders,


on-hand inventory, and sales forecasts.
• When to produce it: Based on, for example, delivery dates for sales
orders.
• How much to produce: Based on the need to fulfill sales orders,
maintain safety stock, and cover requirements that derive from
production orders.

10-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Net requirements of what is needed in a production order: A plan


is usually run as an overnight batch process in most companies so
that the list of requirements that includes materials and
subcomponents, is updated with changes and additions every
morning.

When the requirements are not met by the current inventory, a planned
production order can be issued that specifies what is needed and when. Then the
planner knows what is missing and he or she can make decisions about how to
meet these requirements.

NOTE: Master planning can generate several types of planned orders such as
planned transfer, planned purchases, or kanbans, not just planned production
orders.

The following figure shows the steps for the Master planning module that must
be completed to run and generate the planned production orders.

FIGURE 10.8 MASTER PLANNING BUSINSESS PROCESS

10-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

LEAN Manufacturing
Lean manufacturing is a both a process philosophy and workable process
methodology. It introduces best practice material handling and best in class
manufacturing methods that are now standard across industries. The core
concepts for lean manufacturing provide a base level understanding of the system
functionality within Microsoft Dynamics AX 2012.

In the following section, you will review the Lean production principles, the
overview and rules for Kanban, and production flow processes.

LEAN Manufacturing Overview


Five Lean Principles

The five Lean principles include the following.

• Customer Value: When you identify the value, you specify what
creates value from the customer's perspective.
• Identify the Value Stream: The Value Stream is the sequence of
processes that start from the raw material to the final customer or
from the product concept to the market launch. If it is possible, view
the whole supply chain.
• Flow: Create flow wherever possible in the process. Use one piece of
the flow by linking all the activities and processes into the most
efficient combinations to maximize value-added content while
minimizing waste.
• Pull: Make only what is needed by the customer (short term response
to the customer’s rate of demand).
• Perfection: In striving for perfection, Lean is a journey of
continuous improvement. The goal is to economically produce
exactly what the customer wants, and exactly when the customer
wants it. Because perfection is an aspiration, anything and everything
can be improved.

Kanban Overview
In Microsoft Dynamics AX 2012, the Lean manufacturing module introduces
kanbans as a pull-based just-in-time production system. Kanbans relate to a
sequence of kanban jobs. Each kanban job has a status that indicates its current
stage in the production or transfer process. Each kanban also has a status, the so-
called handling unit status that indicates the overall state of a kanban and the
related handling unit.

10-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Kanban means visible record in Japanese, and it is adopted by many industries as


a method of controlling production and internal supply. Kanban is an important
part of a pull system of supply, which is a very important element of the Lean
production/supply. When a Kanban is consumed, it should be passed (triggered)
to the source of supply to replenish it. This source of supply is defined through
the production flow activities that the Kanban is linked to. It provides the
definition of how the Kanban is filled.

All types of Kanbans can support manufacturing, or internal (store-to-store)


replenishment.

FIGURE 10.9 LEAN MANUFACTURING GRAPHIC

Kanbans are created based on kanban rules. Kanban rules operate on a


production flow or on part of a production flow. There are two types of kanbans:

• Withdrawal kanbans
• Manufacturing kanbans

Similarly, there are two types of kanban jobs:

• Process jobs
• Transfer jobs

10-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Kanban and Kanban Rules Overview


Lean manufacturing in Microsoft Dynamics AX provides two Kanban types that
are used to define how the empty signal is filled—manufacturing and withdrawal.

Kanban Type: Manufacturing

A Kanban of the type “manufacturing” is assigned to at least one process that


adds value. The Kanban is assigned to a production flow activity and therefore a
resource group that has the role of a work cell, where the value is added.
Manufacturing Kanbans relate to at least one process activity. The first activity of
a manufacturing Kanban must be a process activity. A process activity can be
followed by a transfer or another process activity where the Kanban can span to
multiple activities.

Kanban Type: Withdrawal

A Kanban with the type “withdrawal” creates a transfer job that is based on a
single transfer activity. Withdrawal Kanbans are used to move a Kanban of a
specific item between supermarkets, warehouses, and production locations.
Withdrawal Kanbans do not add value.

Fixed Quantity Kanbans

A fixed quantity Kanban rule relates to a fixed number of bins or Kanban cards.
This means that the number of active Kanbans is constant. When a material
handling unit related to a Kanban is consumed (emptied), a new Kanban of the
same type is recreated. Fixed quantity Kanbans are frequently used with fixed
circulating cards, but can also be used with single use cards. When circulating
cards are used, the card is detached from the consumed Kanban and assigned to
the newly created Kanban.

Single Use Kanbans

A fixed quantity Kanban is a “make-to-stock” scenario. Additional single use


Kanbans can be used to cover additional demand to level specific exceptional
demand. Single use Kanbans are only (and always) based on fixed quantity rules
and no specific rules have to be created for this replenishment strategy. Instead,
the Kanbans have a flag that marks them as manual. You can also use event
Kanbans for exceptional demand above a certain quantity to maintain the buffer
stock of a fixed Kanban.

Scheduled Kanbans

Master planning creates scheduled Kanbans automatically for planned Kanban


orders to cover the requirements within the firm horizon of the production
forecast. Scheduled Kanbans can also be manually created.

10-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Event Kanbans

Event Kanbans are only created out of the related demand so that those event
Kanbans belong to the category “make-to-order.” The creation of event Kanbans
is initiated when certain events occur. In Microsoft Dynamics AX 2012, these
events include when you create sales lines, estimate production orders based on
the creation of upper level Kanban demand, or when you reach a certain level of
on hand inventory.

Production Flow
Typically, a Lean manufacturing scenario is more than an accumulation of
unrelated Kanban rules or material supply policies. The flow of material and
products throughout work cells and locations for a specific production or supply
scenario is described as a sequence or small network of process or transfer
activities, which is known as a production flow.

Microsoft Dynamics AX 2012 introduces the activity based production flows to


establish a production and cost context for various Kanban scenarios. All Kanban
rules are directly connected to this predefined structure. The activity based model
is used to set up a wider range of scenarios than those supported by earlier
versions of Lean manufacturing in Microsoft Dynamics AX. Additionally, it is
now easier for shop floor workers to use because all scenarios use the same
activity based user interface.

Production Flow Function

Production flows are the backbone of Lean manufacturing, and they perform the
following functions.

• Define the process and transfer activities of the Value Stream.


• Support the Kanban rules in defining the activities a Kanban follows.
• Provide an activity based context for the planning and production
processes.
• Establish a cost context for the various Kanban production scenarios.

To better support continuous improvement, the production flows are


implemented in time-effective versions. You can copy an existing production
flow version—including all related Kanban rules—to a future version of the
production flow, and model the future-state production flow before validating
and activating it for production. Existing Kanbans from old production flow
versions are automatically related to the new version to make sure a seamless
material flow on the transition date and beyond.

Creating and Activating a Production Flow Version

To map a Lean manufacturing scenario to Microsoft Dynamics AX, the


definition of a production flow is mandatory. The production flow defines the
organizational context of a manufacturing scenario and relates to accounting and
costing.

10-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

The production flow requires the following settings.

• Unique name
• Description
• Legal entity that owns the operations in the production flow
• Operating unit of type value stream

NOTE: An operating unit can be configured to be used as a financial dimension.

• A production group.

NOTE: The production group defines the set of accounts that are used for the
financial postings that are related to the production flow. The most important
accounts are the WIP and Offset accounts. These are the basis of the variance
calculation for the production flow.

The setting of the financial dimension for the production flow is optional.

TIP: For more information about lean manufacturing, refer to the following two
whitepapers.

Lean manufacturing - kanban and pull-based manufacturing


(http://go.microsoft.com/fwlink/?LinkId=238243)

Lean Manufacturing – Production flows and activities


(http://go.microsoft.com/fwlink/?LinkId=238244)

Additionally, you can refer to the Lean Manufacturing for Microsoft Dynamics
AX 2012 course.

Process Industries
Process Manufacturing for Microsoft Dynamics AX 2012 supports a range of
manufacturing processes. This includes make to order, make to stock, and mixed
mode. Mixed mode is a hybrid environment that enables discrete, lean, and
process requirements to coexist. You can integrate production processes to build
a flexible solution that meets your needs.

Overview
Process industry requirements are reflected in the following Microsoft Dynamics
AX 2012 functionalities.

• Integration with the Manufacturing execution system


• Integration with Warehouse Management Systems II (WMSII)

10-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

• Supporting catch weight throughout multiple areas of Microsoft


Dynamics AX 2012
• Improvements to formula maintenance and control
• Improved customer rebates
• Integration with sales and purchase agreements
• Integration with delivery schedules
• Improved integration to quality management
• Improved product compliance
• New inventory batches list page used to perform most inventory
batch related actions from one form
• Improved production costing calculations
• Additional functionality and validations for batch attributes including
the ability to assign targets for all attribute types
• Enabling non-stock items, catch weight items, stocked items to work
with the Process manufacturing solution
• Improved commodity pricing to include financial dimensions
• Report modifications for easier tracking of catch weight, shelf
advice, and batch costing

Some features can be used with any license of Microsoft Dynamics AX2012,
while other features can be used only with a Process Manufacturing installation.

The two installations for Process Manufacturing include the following.

• Process Manufacturing Logistics: The Process Manufacturing


Logistics installation contains all production and manufacturing
functionality.
• Process Manufacturing Distribution: The Process Manufacturing
Distribution installation contains all inventory distribution
functionality.

If your organization wants to use the Process Manufacturing solution, you must
implement one or both of the Process Manufacturing installations.

10-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Lab 10.1 - Bill of Material


This lab demonstrates how to modify the bill of material framework.

Estimated time to complete: 15 minutes

Scenario

Victor, the Business Systems Developer, is tasked to add a BOM line item field
to both the BOM and ProdBOM tables. Specifically, the Finance team wants a
new check box called "IsReturnable" to represent if the item or good is
returnable. The objective is to make sure that if the BOM is canceled before the
actual production, the Logistics group is aware they can receive a refund for the
unused goods that are planned for on the BOM, or picked for the ProdBOM.

Challenge Yourself!
Use the following tables, maps, and forms to create a new field for Victor to
track returnable items at the BOM line level.

• BOM table
• ProdBOM table
• ProdBOM form
• BOMConsistOf form
• BOMMap

Need a Little Help?

1. Create a new enum extended data type.


2. Create a project.
3. Drag the new data type to the project.
4. Drag the BOM table and ProdBOM tables to the project.
5. Attach the new data type to the tables.
6. Save and restore the project.
7. Drag the BOMConsistOf and ProdBOM forms to the project.
8. Drag the new fields in the BOM and ProdBOM to the
BOMConsistOf and ProdBOM forms
9. Save and compile.
10. Test and check the BOM form.
11. Drag the BOMMap to the project.
12. Attach the new enum extended data type to BOMMap.
13. Configure for both BOM and ProdBOM.
14. Save and compile.

10-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

15. Test and check the form.


16. Test and validate the Production order and Production order
details forms.

Step by Step

1. Open the Development Workspace.


2. In the AOT window, expand the Data Dictionary node and then
right-click the Extended Data Types node and select New > Enum.
3. Set the following properties.
a. Name = IsReturnable
b. Label = Is returnable
c. Help text = Item can be returned to the vendor
d. Enum Type = NoYes

4. Save the extended data type. If you are prompted to synchronize the
database, select Yes.
5. Create a project (View > Project or Ctrl+Shift+P ).
6. Right-click the Shared space, New > Project.
7. Name the project.
8. Open the project.
9. Drag the new IsReturnable extended data type to the project.
10. Find the BOM table in the AOT.
11. Drag BOM table to the project.
12. Expand to the Fields node.
13. Find the ProdBOM table in the AOT.
14. Drag the ProdBOM table to the project.
15. Expand the Fields node.
16. Right-click IsReturnable(usr) and select Open New Window.
17. From the new window drag IsReturnable to the BOM fields and the
ProdBOM tables.
18. Close the AOT window with the IsReturn(usr) extended data type.
19. Save the project.
20. In the AOT window, expand the Forms node and locate
BOMConsistOf and ProdBom.
21. Drag the forms to the project.
22. Right-click the project and select Restore.
23. Expand the BOMConsistOf form to Data Sources > BOM > Fields
> IsReturnable, and then right-click and select Open New Window.
24. Expand the BOMConsistOf form to Designs > Design >
[Group:GroupBOM] > [Tab:Tab] > [TabPage:Overview] >
[Grid:GridBOM].
25. Drag IsReturnable to the [Grid:GridBOM].

10-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

26. Close the AOT window with the IsReturnable form.


27. Expand the ProdBOM form to Data Sources > ProdBOM > Fields
> IsReturnable, and then right-click and select Open New Window.
28. Expand the ProdBOM form to Designs > Design > [Tab:Tab] >
[TabPage:Overview] > [Grid:Grid].
29. Drag IsReturnable to the [Grid:Grid].
30. Save and compile the project.
a. Test and check the BOM form. In Microsoft Dynamics AX
2012, open Product information management > Common >
Released products.
b. Select the record 11001 HomeTheaterSystem7.1High Perf.
c. Click the Engineer tab in the Action Pane. Click Lines in the
BOM group.
d. The new IsReturnable check box will display.
e. Check item number 1101.

31. In the AOT window, open Data Dictionary > Maps > BOMMap
and drag it to the project.
32. Expand BOMMap > Fields.
33. Right-click IsReturnable and select Open New Window.
34. Drag it to the BOMMap fields’ node.
35. Right-click BOMMap and select Restore.
36. Expand BOMMap > Mappings > BOM.
37. Map IsReturnable to IsReturnable in the Properties form.
38. Expand BOMMap > Mappings > ProdBOM.
39. Map IsReturnable to IsReturnable in the Properties form.
40. Save and compile the project.
41. Test and validate the Production order form.
a. In Microsoft Dynamics AX 2012, open Production Control >
Common > Production Orders > All production orders.
b. Click Production order in the New group of the Action Pane.
c. Select item number 11001 HomeTheaterSystem7.1High Perf.
d. Click Create.
e. Double-click the newly created production order.

42. Click the BOM in the Production details group of the Action Pane.
In the BOM form, verify that the Is returnable field is selected for
item number 1101.

TIP: You can import the AX2012_ENUS_DEVIV_10_01_LAB_SOL.xpo file to


verify and compare your solution.

10-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Summary
A bill of material is a complete list of all the components, parts, raw materials,
assemblies and their quantities that are required to make a finished product. The
BOM Version identifies which BOM to use for producing an item under specific
circumstances.

Routes and operations are the path that the item takes from operation to
operation, starting with the beginning of the production process and continuing to
the end. It is a set of sequential operations, or tasks, that are required to produce
an item.

Production orders are used to track information about what is to be produced,


how much (quantity), and the planned finish date. The system assigns an order
status to each step in the life cycle of the order. The status shows where the item
is in the production process. Scheduling assigns resources and attempts to
schedule the operations on possible dates and times so that the requested date can
be met.

Planned production orders are created by master planning when requirements are
not met by current inventory. A planned production order is issued that specifies
what is needed and when. Then the planner knows what is missing and he or she
can make decisions about how to meet these requirements. This interacts with the
journals for each step for both real time information and auditing purposes.

Lean is a both a process philosophy and a workable process methodology. It


introduces best practice material handling and best in class manufacturing
methods that are now a standard across industries. Microsoft Dynamics AX 2012
integrates the concept of Kanbans and their effect on the production process.

You can integrate production processes in Microsoft Dynamics AX 2012 to build


a flexible solution that meets your needs by using process industries
functionality.

10-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Test Your Knowledge


Test your knowledge with the following questions.

1. Which of the following are items that are found on a BOM? (Select all that
apply)
( ) Components
( ) Parts
( ) Assemblies
( ) Raw materials

2. Which of the following is not a BOM line type?


( ) Phantom
( ) Pegged
( ) Vendor
( ) Shortest route

3. The applicable resources of an operation in Microsoft Dynamics AX 2012


can be restricted by which new feature?
( ) Operations to perform
( ) Capabilities
( ) Sequence of operations
( ) Customer value

4. Which of the follow is true about Production Orders? Select all that apply.
( ) Meeting sales demand when inventory is insufficient
( ) Creating safety stock based on possible demand
( ) Developing templates for receiving control
( ) Supply the BOM as sub-assemblies to other items in demand

10-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

10-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 10: Use and Design of the Production Control Module

Solutions
Test Your Knowledge
1. Which of the following are items that are found on a BOM? (Select all that
apply)
(√) Components
(√) Parts
(√) Assemblies
(√) Raw materials

2. Which of the following is not a BOM line type?


( ) Phantom
( ) Pegged
( ) Vendor
(•) Shortest route

3. The applicable resources of an operation in Microsoft Dynamics AX 2012


can be restricted by which new feature?
( ) Operations to perform
(•) Capabilities
( ) Sequence of operations
( ) Customer value

4. Which of the follow is true about Production Orders? Select all that apply.
(√) Meeting sales demand when inventory is insufficient
(√) Creating safety stock based on possible demand
( ) Developing templates for receiving control
(√) Supply the BOM as sub-assemblies to other items in demand

10-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

10-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

CHAPTER 11: WORKFLOW


Objectives
The objectives are:

• Implement a new line-item workflow.


• Review the workflow providers in Microsoft Dynamics® AX 2012.
• Create a custom workflow provider.
• Enable queues for a workflow document.
• Discuss how currency type fields function within the Condition
Editor.
• Review the steps required to implement a new hierarchy type field to
be used in the Condition Editor.

Introduction
Workflow in Microsoft Dynamics AX 2012 uses a combination of Application
Object Tree (AOT) elements created by the developer and additional set up that
is completed by the end-user to control the configuration and process a workflow
will follow.

This course introduces advanced development topics that explain how to


implement line-item workflows, create workflow work item queues, create new
workflow providers, implement currency support in the Condition Editor, and
implement conditions on fields that represent hierarchies in the Condition Editor.

11-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Line-Item Workflows
Workflows act on business documents. Sometimes patterns exist where there is a
relationship between two tables―one is a header table; for example, Expense
header, and the other is a line-item table. The line-item table contains records that
relate to the header, for example, an expense report has many expense lines.

Line-item workflow in Microsoft Dynamics AX 2012 supports this header and


line pattern. The developer must enable line-item support for each workflow
where a header and line-item relationship exists. Then the business user can
configure a workflow that includes a "Line-item workflow" element. In that
element, the business user can select the workflows that he or she wants to act on
the line items. For example, some transactions might be processed by using a
project approval workflow, others might be processed by using a workflow that
only requires approval by the manager. End-users interact with line-item
workflows in the same manner as other workflows—by taking workflow actions
on the line items.

NOTE: Some tables are enabled for line-item workflows out of the box, such as
purchase requisitions and expense reports.

Create a Custom Line-Item Workflow


The high-level steps a developer must take to implement a new line-item
workflow include the following.

1. Identify the header and line table that have to be workflow enabled,
and then make sure that there is a table relationship between them.
a. Open the AOT and browse to Data Dictionary > Tables.
b. Select the line-item table and then expand the Relations node.
c. Verify that a relation exists back to the header table.

2. Assuming that a workflow already exists for the header table, create
a new line-item workflow under the Line-item workflow node of
the header workflow.
3. Set the properties of the new line-item workflow including the
relation, event handlers, and menu items as needed.
4. Optionally, you can set the EnableLineItemWaitSelection to Yes if
you want to give the business user access to choose whether the line-
item workflow element should be wait for all line-item workflows to
complete before you move on to the next element.

11-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

5. Create a new Line-item workflow type under the Line-item


workflow that is created in step 2, and then select the Workflow type
for the line-item workflow. This step constrains the line-item
workflow to only be available for the business user based on that
workflow type. Multiple line-item workflow types can be added if it
is required.
6. Enable the common workflow user interface elements at the line
level of the forms that the end-user will use to interact with the
header and line records.

Now, the business user can create a new workflow on the line-item table by using
the line-item workflow type, then create a new workflow on the header table by
using the header workflow type, and then configure the line-item workflow
element in the header workflow by selecting the line-item workflow he or she
just created.

TIP: You can review the Purchase requisition review workflow to see how steps
2, 3 and 4 are implemented for this workflow. (Open AOT > Workflow >
Workflow Types > PurchReqReview.)

Scenario: Line-Item Workflows


Isaac, the Business Systems Developer, has just finished creating a workflow for
purchase orders. He has also created all the classes, event handlers, and menu
items for a new purchase order line workflow. Now he must create the new
purchase order line workflow type and link it to the purchase order header
workflow.

NOTE: Before you can begin this demonstration, you must create a duplicate of
the PurchOrderHeaderTemplate.

To create a new purchase order line template, follow these steps.

1. Open the Development Workspace.


2. Open the Projects window, and expand the Shared Projects folder.
3. Right-click the LineItemWorkflowDemonstration project and
select Open.
4. Right-click LineItemWorkflowDemonstration and select New >
Workflow > Workflow type.
5. Select the newly create WorkflowType1 node, and open the
Properties window.
6. Set the Name to PurchOrderLineTemplate.
7. Set the CanceledEventHandler property to
PurchLineTemplateEventHandler.
8. Set the CancelMenuItem property to PurchLineWorkflowCancel.
9. Set the Category to PurchCategory.

11-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

10. Set the CompletedEventHandler property to


PurchLineTemplateEventHandler.
11. Set the Document property to PurchLineDocument.
12. Set the DocumentMenuItem property to PurchTable.
13. Set the Label property to @SYS301073.
14. Set the HelpText property to @SYS301074.
15. Set the StartedEventHandler property to
PurchLineTemplateEventHandler.
16. Save the project.

To link a line-item workflow to a header workflow, follow these steps. In this


example, the PurchOrderLineTemplate will be added to the
PurchOrderHeaderTemplate.

1. In the LineItemWorkflowDemonstration project, expand the


PurchOrderHeaderTemplate workflow type.
2. Right-click the Line-item Workflows node, and then select New
Line-item Workflow.
3. Set the Name property to PurchOrderLineTemplate.
4. Set the CancelMenuItem property to WorkflowLineItemCancel.
5. Set the EnableLineItemWaitSelection property to No.
6. Set the HelpText property to @SYS301074.
7. Set the Label property to @SYS301073.
8. Set the LineItemWorkflowRelation property to PurchLine.
9. Right-click the Line-item Workflow Types node under the
PurchOrderLineTemplate node, and then select New Line Item
Workflow Type.
10. In the LineItemWorkflowType property enter
PurchOrderLineTemplate.
11. Save the project.

Workflow Providers
Workflow providers in Microsoft Dynamics AX provide application specific data
for a workflow at run time. The application data provided can include the
following:

• User IDs based on user groups.


• Due dates based on employee or manager working days.
• Specific user or manager IDs based on their maximum approval
limits.
• Groups of users assigned to a specific work item queue.

The following topics describe the default workflow providers in Microsoft


Dynamics AX and how to implement them.

11-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Workflow Provider Overview


In Microsoft Dynamics AX, you can use workflow providers to provide
application-specific information to a workflow instance at run time. For example,
you can use workflow providers to determine who is required to approve an
invoice, or by which date an invoice payment is considered late. This topic
describes the default providers available in Microsoft Dynamics AX.

There are several types of workflow providers that you can implement in
Microsoft Dynamics AX workflow.

• Hierarchy: Determines a user ID based on search in a hierarchy.


• Due date: Determines the due date for a task or approval, or the due
date for a step in a task or approval.
• Participant: Resolves a user group or role into one or more specific
user IDs.
• Queue: Determines a queue name to assign the work item to. A
particular user that is assigned to that queue can then manually
accept or claim the work item. When a work item is accepted it will
no longer be possible for any other member of the queue to act on it,
unless it is delegated or released back to the queue.

Each task or workflow must have a due date provider defined to determine the
last date by which the workflow element can be compeleted. For example, the
maximum number of days to complete a task, or the maximum time permitted to
wait for an approval before automatic denial of the approval.

A provider is also used to select a user or group of users for the task or approval
step. For example, the participant provider could select a manager from a
manager's role to approve an expense report. In Microsoft Dynamics AX 2012
the providers for a workflow element are inferred. There are no special
parameters that must be set on the elements in the AOT to specify the type of
provider. Each workflow element can have many different types of providers
available. However, only one type of provider can be selected when configuring
a workflow element.

The WorkflowHierarchyProvider.getNextNode method is called when an


approval or task is started to retrieve the identity of the user in the hierarchy that
should be assigned a work item.

The WorkflowHierarchyProvider.getNodeDataType method is called when


the approval or task is started to return an object of the type the hierarchy
provider expects as input. Because each hierarchy provider implementation can
have a different input type, the input type is based on the type of hierarchy. For
example, an organizational hierarchy provider might return employee ID,
whereas a product hierarchy provider might return a product ID.

The WorkflowHierarchyProvider.convertToNodeDataType method is called


at run time when an extended data type value must be converted to a data type
that the hierarchy supports as the start node.

11-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The WorkflowHierarchyProvider.convertUserIdToNodeDataType method is


called at run time to convert a user ID value to a data type that the hierarchy
supports. When a reserved word is selected, such as workflow owner or
workflow originator, a user ID is passed.

The WorkflowHierarchyProvider.getSupportedDataType method is called to


return the set of supported extended data types that the hierarchy provider can
convert into node data types. The set is displayed as a drop-down list in the user
interface.

Due Date Provider


You can use a due date provider to determine a specific due date for a task or
approval based on a specified start date. Microsoft Dynamics AX workflow
provides the WorkflowWorkCalendarDueDateProvider class that returns the
date before which the workflow work item must be completed.

The due date provider can use the company calendar defined in the Basic module
to resolve a time span for a task or approval into a date that takes nonworking
days into consideration. For example, the default due date provider can calculate
the correct date for an expense report approval that should be approved within 10
workdays. Any holidays or non-working days specified in the calendar setup in
the Organization administration module are calculated into the approval due
date.

The WorkflowWorkCalendarDueDateProvider class implements the


WorkflowDueDateProvider interface that contains the following methods.

• WorkflowDueDateProvider.getCalendarTokens
• WorkflowDueDateProvider.resolve
• WorkflowDueDateProvider.resolveNonUser

The WorkflowDueDateProvider.getCalendarTokens method is called from


the workflow configuration user interface so that the user can select a calendar
from the list of supported calendars. This method provides a list of the calendars
IDs from a calendar system, such as the calendar defined in the Organization
administration module's Calendars form.

The WorkflowDueDateProvider.Resolve method is called when a task or


approval step is started to determine the due date of the step. For example, the
workflow configuration is set up to require an expense report approval within 10
work days. When the approval step or task is started, the due date provider's
resolve method is called to return the actual due date. The calendar ID specified
in the configuration user interface is passed into this method to resolve the time
span for a workflow work item into the due date for the work item based on the
calendar ID.

11-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

The WorkflowDueDateProvider.resolveNonUser method is called to


determine the due date for the workflow element itself. In the configuration user
interface, this is the due date for Set a time limit for the task. This method is
implemented when you do not have a user to determine the maximum duration
for a work item.

Participant Provider
You can use a participant provider to return a list of users from any abstraction,
such as a user group. Microsoft Dynamics AX workflow provides the
WorkflowUserGroupParticipantProvider class that returns a list of users
based on a Microsoft Dynamics AX user group.

The WorkflowUserGroupParticipantProvider class implements the


WorkflowParticipantProvider interface that contains the following methods:

• WorkflowParticipantProvider.getParticipantTokens
• WorkflowParticipantProvider.resolve

The WorkflowParticipantProvider.GetParticipantTokens method is called


from the workflow configuration user interface to display a list of supported
participant tokens. Participant tokens are IDs of user roles or user group names.

When you implement a customer provider, the participant token represents the
abstraction when you implement a different concept. For example, if you
implemented a new provider for commission groups, the IDs could represent the
commission group ID.

The WorkflowParticipantProvider.Resolve method is called when a task or


approval step is started to determine the specific user who will complete the step.
For example, the workflow configuration is set up to require the approver of a
step to be the purchasing manager. When the approval step is started, the
participant provider resolve method is called to return the user ID of a specific
purchasing manager.

Queue Provider
You can use a queue provider to return a list work item queues that are
configured in the Home module. Microsoft Dynamics AX workflow provides the
WorkflowQueueProvider class that returns a list of work item queues.

The WorkflowWorkItemQueueProvider class implements the


WorkflowQueueProvider interface which contains the following methods:

• WorkflowParticipantProvider.getQueueTokens
• WorkflowParticipantProvider.queueIDToQueueName
• WorkflowParticipantProvider.queueNameToQueueID
• WorkflowParticipantProvider.resolve

11-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The WorkflowParticipantProvider.getQueueTokens method is called from the


workflow configuration user interface to display a list of queue names for queue-
based assignment.

The WorkflowParticipantProvider.queueIDToQueueName method is called


to convert a workflow queue ID to a name.

The WorkflowParticipantProvider.queueNameToQueueID method is called


to convert a workflow queue name to a workflow queue ID.

The WorkflowParticipantProvider.Resolve method is called when a task or


approval step is started to determine the specific queue to assign the step. For
example, the workflow configuration is set up to require the approver of a step to
be one of the purchasing agents that are all part of a queue called Purchasing.
When the approval step is started, the queue provider resolve() method is called
to return the queue ID.

Create Custom Workflow Providers


In Microsoft Dynamics AX, there are four default workflow providers. In some
cases, these default providers might not meet your application requirements. The
following procedure describes the steps that you have to implement a custom
workflow provider.

You must complete the following high level steps to implement a new workflow
provider.

1. Create a "provider" class that contains the business logic for your
new provider.
2. Create a new provider under the appropriate Providers node in the
AOT, and then set the Name, Label, and HelpText properties.
3. Specify the AssociationType property. This defines the
organizational scope of the provider. For example, organization wide
versus company specific. This requires that the business logic be
written in such a way that it respects the value of this property.
4. Set the AvailableForAllWorkflowsTypes property.
a. If a new provider is implemented for a specific workflow, then
set this property to No. Next, create new workflow types for
each type that the provider can be used for under the Workflow
Types node. This limits the visibility and use of the provider in
to the selected workflows.
b. If a new provider is general purpose in nature and does not have
an affinity to a specific workflow, then set this property to Yes
and it will be available throughout Microsoft Dynamics AX.

5. Set the ProviderClass property by selecting the name of the class


that is developed in step 1.

11-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Procedure: Create a Custom Workflow Provider


To create a new workflow provider, follow these steps.

1. In the AOT, expand the Classes node.


2. Right-click the Classes node, and then select New Class. A new
class group displays under the Classes node.
3. Expand the new class, right-click classDeclaration, and then click
Edit.
4. Enter the following code in the class declaration.

public class <MyCustomWorkflowParticipantProviderClassName>


implements WorkflowParticipantProvider
{
}

5. Right-click in the Code Editor window, click New, and then enter
the following code for the getParticipantTokens method.

public WorkflowParticipantTokenList getParticipantTokens()


{
// Constructs the new user group list.
WorkflowParticipantTokenList userGroups =
WorkflowParticipantTokenList::construct();
;

// ToDo Define your user groups here.

return userGroups;
}

6. Right-click in the Code Editor window, click New, and then enter
the following code for the resolve method.

public WorkflowUserList resolve(WorkflowContext _context,


WorkflowParticipantToken _participantTokenName)
{
// Declare the variables.
UserGroupList userGroupList;
WorkflowUserList userList =
WorkflowUserList::construct();
;
// Verify that the participant token is set or throw
an error.
if (!_participantTokenName)
throw error("@SYS105453");

// ToDo Enter code to add users to the user list.

{
userList.add(userGroupList.UserId);
}

11-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

return userList;
}

7. Close the Code Editor window and then click Yes to save the
changes.

Work Item Queues


Microsoft Dynamics AX 2012 introduces the queue functionality that is used to
assign work items (from workflow) to specific groups of employees. Several
setup steps occur in the rich client including creating queue groups, queues, and
queue assignment rules. However, the developer must perform some actions to
make sure that the setup of a work item queue works correctly when it is selected
in a workflow elements configuration.

Developer Actions
The developer must complete the following high level steps to enable queues for
a document.

1. Enable queues in the workflow document by setting the following


attribute on the workflow document class in the class declaration
WorkflowDocIsQueueEnabledAttribute(true,"<label>")
a. <label> is the label ID that represents the business document
name.
b. The business document name tells the workflow system that any
workflows based on this workflow document can have work
items generated that are assigned to a queue.

2. Next, create a custom WorkflowQueueCreatedEventHandler


class. This is necessary to store additional data that is used when you
view the work items that are assigned to a queue in the user
interface.
a. The custom class must derive from the base class
WorkflowQueueCreatedEventHandler
b. You have to override the mapFields() method

HINT: For an example of how to implement this, refer to the


TrvDocumentQueuedTaskEventHandler class in AOT. The mapFields method is
overridden to set the DocumentID, Type and Company.

3. Set the WorkItemsCreatedEventHandler property on the task


element in AOT with the custom
WorkflowQueueCreatedEventHander class created previously.
This guarantees that it is used at run time.
4. Create custom list page queries to allow for filters based on queue
assignment.

11-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

5. Bind the queries to the menu items for each list page. For example,
refer to the PurchReqwAllMyReports and
PurchReqMyDirectReports Display Menu Items for an example
of how this is achieved.

Scenario: Enable Queues for a Document


Isaac, the Business Systems Developer, has just finished creating a new
workflow for expense reports. Now, he can allow the expense reports tasks to be
assigned to a queue so that one of the accountants can review the expense
reports. He also wants to create two new list pages that will filter the expense
reports assigned to queues so that users can easily view expense reports that are
assigned to them or to their queues.

Demonstration: Enable Queues for a Document


To enable queues for a document, follow these steps.

1. Open the Development Workspace.


2. Select the document class or create a new document class for the
workflow document.
3. Right-click the classDeclaration and select View Code.
4. Decorate the method with the
WorkflowDocIsQueueEnabledAttribute.

The following code sample is an example of the TrvWorkflowExpHeader class


declaration which is decorated with the
WorkflowDocIsQueueEnabledAttribute (the first line) to enable queues for the
expense report workflow.

[
WorkflowDocIsQueueEnabledAttribute(true, "@SYS317210"),
ExpressionCurrencyFieldMapAttribute(methodstr(TrvWorkflowEx
pHeader, parmTotalExpenseAmount),
methodstr(TrvWorkflowExpHeader,
parmAccountingCurrencyCode)),
ExpressionCurrencyLEAttribute(tableStr(TrvExpTable),
fieldStr(TrvExpTable, LegalEntity)),
ExpressionCurrencyLEAttribute(tableStr(TrvExpTrans),
fieldStr(TrvExpTrans, LegalEntity)),
ExpressionCurrExchRateDateAttribute(tableStr(TrvExpTrans),
fieldStr(TrvExpTrans, TransDate))
]
class TrvWorkflowExpHeader extends WorkflowDocument
{
}

11-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Demonstration: Create a Workflow Queue Event Handler


To create an event handler for managing the queue data in the user interface,
follow these steps.

1. Right-click the Classes node in the AOT, and then select New Class.
2. Right-click the newly created class and select View Code.
3. In the classDeclaration, create a name the class
<Workflow>DocumentQueuedTaskEventHandler where
<Workflow> is the name of the document that you are enabling
workflow for.
4. Make sure that the class extends
WorkflowQueueCreatedEventHandler, and then save the class.
5. Right-click the new class in the AOT, and then select Override
method and select mapFields.
a. Declare the Workflow macro.
b. Declare the table that stores the data for your document.
c. Declare the WorkflowDocIsQueueEnabledAttribute.
d. Declare the DictClass.
e. Set the DictClass equal to the class that is used for your
document workflow.
f. Set the WorkflowDocIsQueueEnabledAttribute variable that you
created in step 5.c. equal to the WorkflowDocumentAttribute in
the Workflow macro.
g. Set the document table variable created in step 5.b. to the record
that is currently selected.
h. Set the parameters in the WorkflowQueueCreatedEventHandler
class equal to the fields from the table fields in the document
table that you declared in step 5.b.

The following code sample is an example of the


TrvDocumentQueuedTaskEventHandler class.

public class TrvDocumentQueuedTaskEventHandler extends


WorkflowQueueCreatedEventHandler
{
}

protected void mapFields()


{
#Workflow

TrvExpTable trvExpTable;
WorkflowDocIsQueueEnabledAttribute attribute;
DictClass dictClass;

dictClass = new

11-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

DictClass(classNum(TrvWorkflowExpHeader));
attribute =
dictClass.getAttribute(#WorkflowDocumentAttribute);

trvExpTable =
TrvExpTable::findRecId(this.parmWorkflowWorkitemTable().Ref
RecId);

this.parmDocumentId(trvExpTable.ExpNumber);
this.parmDocumentType(attribute.parmFriendlyName());
this.parmCompanyInfo(trvExpTable.company());
}

Demonstration: Link the Workflow Queue Event Handler


to the Workflow Type
After you have created an event handler for the work item queue, you have to
link the new event handler class to the task or approval in the AOT. To link the
workflow event handler to a workflow task, follow these steps.

1. In the AOT, expand the Workflow node, and then expand the Tasks
node.
2. Select the task that you want to allow work item queues for, or if it
does not exist, create a new task and set the properties as required.
3. Right-click the task and select Properties.
4. Set the WorkItemsCreatedEventHandler property to the event
handler class that you created in Demonstration: Create a Workflow
Queue Event Handler.
5. Save the Task.

NOTE: Queues are not supported for approval elements because the way users
interact with them is different than tasks.

Demonstration: Create a List Page Query for Queues


Next, you must create a query or multiple queries to filter the documents based
on the queue assignment. For example, you could create a query to filter for
expense reports that are assigned to the current user logged on (Expense reports
assigned to me), or to view all expense reports work items that are assigned to a
queue that the current user is a part of (Expense reports assigned to my
queues).

11-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Work Items Assigned to Me

To create a query that filters for work items that are assigned to the current users,
join the WorkflowWorkItemTable and add a range on the UserID field and set
the Value property to (UserID = currentUserID()). The following sample is
taken from the TrvExpTable_AssignedToMe query that controls the filter for the
Expense reports assigned to me form located in Travel and expense > Common
> Expenses > Expense reports assigned to me.

FIGURE 11.1 TRVEXPTABLE_ASSIGNEDTOME QUERY

11-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Work Items Assigned to My Queues

To create a query that filters for work items that are assigned to a queue the
current users belongs to, join the WorkflowWorkItemQueueAssignee table and
add a range on the UserID field and set the Value property to (UserID =
currentUserID()). The following sample is taken from the
TrvExpTable_AssignedToMyQueues query that controls the filter for the
Expense reports assigned to me form located in Travel and expense >
Common > Expenses > Expense reports assigned to my queues.

FIGURE 11.2 TRVEXPTABLE_ASSIGNEDTOMYQUEUES QUERY

For other examples of queries and list pages that you can add to a document,
refer to the Purchase requisition list pages that are located in Procurement and
sourcing > Common > Purchase requisitions.

Demonstration: Bind the Query to a Menu Item


The final step in the process is to create menu items that are bound to the query
that you created in Create a List Page Query for Queues demonstration. Then
you must add the menu item to the menu.

To create a menu item that is bound to your query, follow these steps.

1. In the AOT expand Menu Items.


2. Right-click the Display node and select New Menu Item.
3. Right-click the new menu item and select Properties.
4. Enter a Name for the menu item.
5. Specify the Label and the HelpText property for the menu item.
6. Select the primary list page in the Object property.

11-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

7. In the Query property, specify the query that you created in the
Create a List Page Query for Queues demonstration.
8. Specify the other properties as required and then save the menu item.

When you are finished, drag the menu item into the menu where you want the list
page to appear.

Currency in the Condition Editor


Earlier releases of Microsoft Dynamics AX do not include any support in the
Condition Editor used to compare amounts in different currencies. In Microsoft
Dynamics AX 2012, the Condition Editor is extended so that conditions can be
created when the currencies being used on either side of the condition could be
different. Additionally, Microsoft Dynamics AX 2012 introduces the following
features.

• The currency code can be obtained for a field on the left side of the
condition that contains an amount.
• The end-user can select a currency code for an amount entered on the
right side of the condition.
• The left and right side of the condition can be converted into a
common currency so that they can be evaluated.

The most basic approach to implementing currency fields in the Condition Editor
is to set meta-data that will be used by the default currency provider. This meta-
data is then used by the Condition Editor together with a default currency
provider without any additional development. This is true only when the
currency code field is on the same table as the currency amount field. In all
other cases, coding is required to either extend the default currency provider
implementation or to implement a new currency provider that meets your
application needs.

Scenario: Currency Code in the Record


In this example it is assumed that the currency code field is stored in the same
table as the currency value or amount field. This is the most common scenario
and the following steps are required.

1. Set the currency meta-data for the currency code field. Refer to the
Define Currency Meta Data procedure for more information.
2. Review the behavior of the ExpressionCurrencyDefaultProvider
class to determine whether the requirements are met.
3. If the ExpressionCurrencyDefaultProvider meets your requirements,
then no additional action is required.

11-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

4. If the ExpressionCurrencyDefaultProvider does not meet your


requirements, you must either:
a. Extend the default provider. Refer to the Extend the Default
Currency Provider procedure for more information.
b. Implement your own provider. Refer to the Implement a New
Currency Provider procedure for more information.

Scenario: Currency Code Associated to the Ledger


In this scenario, the Accounting currency and Default exchange rate type are
obtained from the Ledger form associated with the legal entity that is referenced
by the record. There are two possible outcomes in this scenario dependent on the
SaveDataPerLegalEntity property on the table.

When the SaveDataPerCompany property is set to Yes, no additional


development steps are required because the dataAreaID field will be
automatically set in the meta data to the default currency provider.

When the SaveDataPerLegalEntity property is set to No, then the legal entity is
represented by a field other than the dataAreaID on the record. In this scenario
the developer must add an attribute to the workflow document class to identify
the table and field that stores the legal entity value.

[ExpressionCurrencyLEAttribute('<Query.DataSource.Name>','<
Field.Name>')]

NOTE: There are no additional steps required to implement this scenario.


However, this scenario will only be used if the method described in the Currency
Code scenario does not apply, and there is no calculated field that returns the
currency code.

IMPORTANT: A "global" or system currency code is not supported in the base


implementation. Therefore, you must implement a new currency provider or
extend the default currency provider if this is a requirement.

Scenario: Currency Code in a Calculated Field or


Business Logic
If you have written application-specific business logic, or if you must obtain the
currency code by using a calculated field, you can extend the default currency
provider or implement a new currency provider.

When the currency to be used is not stored in same table or is calculated, you
must set the ExpressionCurrencyFieldMappingAttribute to be the field
(calculated or otherwise) from the workflow document that provides the currency
code. Use the following code sample to guide you.

11-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

[
ExpressionCurrencyProviderAttribute(classstr(<Your>Currency
Provider),
ExpressionCurrencyFieldMappingAttribute('parm<CalculatedFie
ld1>', '<Field in the document’s root table>'),
ExpressionCurrencyFieldMappingAttribute('parm<CalculatedFie
ld2>', 'parm<CalculatedField3 representing the currency
code>')
]
class <yourWorkflowDocumentClass> extends WorkflowDocument
{
...
}

IMPORTANT: A relation must be defined on the field that stores the currency
codes. This relation is used by the system to create a lookup for currency codes
in the Condition Editor. If a relation does not exist, the ellipses button will not
appear in the Condition Editor and the user cannot select the currency code from
a list.

Procedure: Define Currency Code Meta Data


To set the meta data for a currency amount field, follow these steps.

1. Open the Development Workspace.


2. In the AOT, expand Data Dictionary, and then right-click
Extended Data Types and select New > Real.
3. Enter a Name and Label for the extended data type.
4. Set the Extends property to either Amount or AmountMST.
5. Set the other properties on the extended data type as required.
6. Save the extended data type.

NOTE: You can choose to skip steps 2 through 6 and just add the Amount or
AmountMST extended data types directly to your table.

7. In the AOT expand Data Dictionary, and the under the Tables node
select the table that you want to implement a currency for.
8. Drag the extended data type that you created in step 2 into the table.
9. Drag the CurrencyCode extended data type into the table.
10. Create other fields on the table as required.
11. Save the table.
12. Right-click the Relations node on the table and select New >
Relation.
13. Enter a Name for the relation such as Currency.
14. Select Currency in the Table property.
15. Set the other properties as required. Refer to the TrvExpTrans table
> Currency relation for an example of how to implement this.

11-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

16. Right-click the relation created in step 12, and then select New >
Normal.
17. In the Field property, select the field that you created in step 9.
18. Set the Related field property to the CurrencyCode field (which is
from the Currency table).
19. If required, specify the SourceEDT property as the extended data
type for the Field.
20. Save the table.

Procedure: Extend the Default Currency Provider


The following developer actions are required to extend the default currency
provider.

1. Create a class that extends ExpressionCurrencyDefaultProvider.


2. Extend specific method(s) as needed based on your requirements.
Refer to the Implement a New Currency Provider procedure for a list
of the methods that can be extended.
3. Register the new class in the workflow document by using the
ExpressionCurrencyProvider attribute.

Procedure: Implement a New Currency Provider


To implement a new currency provider, follow these steps.

1. Create a class that implements ExpressionCurrencyProvider.


2. Implement the following methods:
a. boolean isCurrencyEnabled: Used to determine whether the
field is currency enabled or not.
b. getCurrencyCodeLookup: Used to display a currency code
lookup form and returns the selected currency code.
c. getCurrencyCode: Used to return the currency code for a field,
for the current record.
d. getExchangeDate: Used to obtain the date that is passed into the
currency conversion.
e. getExchangeRateType: Used to obtain the exchange rate type
that is passed into the currency conversion.
f. ConvertAmountField: Used to convert an amount value in the
fromField and fromField's currency code to the toField's
currency code. The converted amount is returned.
g. ConvertAmountValue: Used to convert the fromAmount in
the fromCurrencyCode to a value in the toCurrencyCode. The
converted amount is returned.

3. Register the new class in the workflow document by using the


ExpressionCurrencyProvider attribute. Use the following code
sample as a guide.

11-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

[ExpressionCurrencyProviderAttribute(classstr(<Your>Currenc
yProvider))]
class <YourWorkflowDocumentClass> extends WorkflowDocument
{
...
}

Example: Currency in the Condition Editor


The expense report document class, TrvWorkflowExpHeader, includes an
example of how some currency attributes are implemented. The following figure
displays the code in the class declaration which includes the attributes.

FIGURE 11.3 CLASSES\TRVWORKFLOWEXPHEADER – CODE EDITOR


FORM

Line 3 is the ExpressionCurrencyFieldMapAttribute which is used to set the


currency code and currency value. The two parameters that are being passed in
are value and the currency code. In this example, there are two methods in the
class that define what the currency code and values are.

The parmTotalExpenseAmount method returns the total amount of the expense


report by calling the total() method on the TrvExpTable for the record that is
passed in.

The parmAccountingCurrencyCode method returns the accounting currency in


the Ledger form for the legal entity that is linked to either the expense line or the
expense header, depending on the record that is passed in. This method is also
decorated with the ExpressionFieldHideAttribute which is used to hide the
currency code field in the Condition Editor. This prevents the user from
selecting a different currency than the currency that is selected on the transaction
that is passed in.

Lines 4 and 5 use the ExpressionCurrencyLEAttribute which sets the legal


entity for a table that is passed in. The legal entity is used by the
ExpressionCurrencyDefaultProvider to perform the conversion in the
Condition Editor. Each data source in the document query that included amounts
that need currency conversion support must have their own attribute defined. In
this example, there are two data sources-one for the expense header
(TrvExpTable) and one for the expense lines (TrvExpTrans).

11-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Line 6 uses the ExpressionCurrExchRateDateAttribute which sets the


exchange rate date that will be used by the currency converter for making the
conversion from one currency to another. In this example the transDate field
from the TrvExpTable is passed in.

This class also includes a method which returns the spending limit for the
requester. This method also includes the currency for the spending limit so that a
currency conversion can be complete when this field is selected in the Condition
Editor.

After you have implemented the classes and methods with the correct attributes,
you can use the Condition Editor in the workflow type to select or compare
amounts with relation and accuracy for the currencies. The following figure
illustrates two samples of how these fields can be used.

FIGURE 11.4 EXPENSE REPORT – WORKFLOW APPROVAL – CONDITION


PROPERTIES EXAMPLE

In this example, the first condition is comparing the total expense report amount
to the requesters spending limit. For both fields, the currency code is passed in
automatically based on the record passed into the query. There is no need for the
user to select a currency code.

The second condition in this example is comparing the total expense report
amount to a fixed value of 10,000 United States dollars (USD). The user can
click the ellipsis button (...) to specify the currency for the value that is entered
into the right side of the condition. The currency code is still hidden on the left
side of the condition because it is being calculated by the system in the
parmAccountingCurrencyCode method.

11-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Hierarchy Type Fields in the Condition Editor


Microsoft Dynamics AX 2012 supports adding fields and data that have a
hierarchical structure. Examples of these types of fields and data in the user
interface include the organization models and procurement categories.

When a field that has a hierarchical data structure is presented in the Condition
Editor for workflow, the comparison function should include operators such as
"at or above", "above", "at", "below", and "at or below".

Example: Procurement Category Hierarchies

Contoso has created a procurement category hierarchy that includes several


levels for the brands, types, and categories that each product belongs to. Each
buyer at Contoso is responsible for certain brands of products and is therefore
also responsible for the types and categories that are below the selected brand in
the hierarchy.

Now you are creating a new purchase requisition line-level workflow and want to
assign a task in the workflow based on the procurement category that is assigned
to each line of the purchase orders. When you add the procurement category field
to the left side of the condition, the operator for that condition can be set to "at or
below" which will include the brand selected on the right side of the condition
and all the types and categories that are below the brand selected.

The system uses the getLookup() method to display the hierarchy in the
condition, and then at run time the condition is evaluated by using the
getDistance() method.

Developer Actions
To implement a new field that supports hierarchies in the Condition Editor, the
developer must follow these steps.

1. Create a new class that implements the


ExpressionHierarchyProvider base class. This class must
implement the methods that are required to enable hierarchy support
in the Condition Editor
a. getDistance(): Returns the distance from the target node to the
source node in a hierarchy. If a direct path from the source node
to the target node does not exist then a nonzero value must be
returned.
b. getLookup(): Displays a lookup table that represents the
hierarchy from which the user can select a node. The lookup
table is typically the primary key table for this field in the
foreign key table.

11-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

2. Register the new class on the workflow document class that is used
by decorating the class with the following attribute:
[WorkflowHierarchyProviderAttribute
(classstr(MyHierarchyProviderImplementation), myTableId,
myFieldId)]

The parameters myTableId and myFieldId are needed to specify the


table and field within the data source for which this applies. At run time,
when the Condition Editor is invoked, and the hierarchy-enabled field is
selected on the left side of a condition, the Condition Editor will show a
set of hierarchical operators (at or above, above, at, below, at or below),
and will enable a lookup on the right side that allows the end-user to
choose a node in the hierarchy to compare the field on the left side
against.

Developer Actions
To implement a new field that supports hierarchies in the Condition Editor, the
developer must follow these steps.

1. Create a new class that implements the


ExpressionHierarchyProvider base class. This class must
implement the methods that are required to enable hierarchy support
in the Condition Editor
a. getDistance(): Returns the distance from the target node to the
source node in a hierarchy. If a direct path from the source node
to the target node does not exist then a nonzero value must be
returned.
b. getLookup(): Displays a lookup table that represents the
hierarchy from which the user can select a node. The lookup
table is typically the primary key table for this field in the
foreign key table.

2. Register the new class on the workflow document class that is used
by decorating the class with the following attribute:

[WorkflowHierarchyProviderAttribute
(classstr(MyHierarchyProviderImplementation), myTableId,
myFieldId)]

11-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The parameters myTableId and myFieldId are needed to specify the table and
field within the data source for which this applies. At run time, when the
Condition Editor is invoked, and the hierarchy-enabled field is selected on the
left side of a condition, the Condition Editor will show a set of hierarchical
operators (at or above, above, at, below, at or below), and will enable a lookup on
the right side that allows the end-user to choose a node in the hierarchy to
compare the field on the left side against.

Example: Hierarchy Type Fields in the Condition Editor


To see an example of how this is implemented, refer to the
PurchReqExpressionProvider class. This class contains the getDistance() and
getLookup() methods for a procurement category hierarchy field. This attribute is
then used in the PurchReqWFLineDocument class.

11-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Lab 11.1 - Workflow Workshop


The workflow workshop is designed to demonstrate from start to finish, how to
implement a new workflow that includes an approval element. In addition, the
workflow that is created will be added as a line-item workflow to another
workflow. It includes concepts covered in the Development III for Microsoft
Dynamics AX 2012 course in addition to concepts covered in this chapter.

Estimated time to complete: 50 minutes

Scenario

Contoso uses Free Text Invoices to manage service agreements with many
customers. Currently, workflow is only supported on the header level of the
document. Kevin, the Sales Manager, wants the sales representatives to approve
the free text invoices that are created by the Accounting Department by using the
free text invoice recurring invoice batch job.

Because each line of the free text invoice might be routed to a different sales
representative or might require different levels of approvals, Kevin would like to
implement workflow for each line of the free text invoice.

Kevin has also specified that the new line-item workflow for free text invoices
should include an approval element and the line-item workflow should support
work item queues.

Challenge Yourself!
By using the information that is provided in the scenario, create a new workflow
type for free text invoice lines called
CustFreeTextInvoiceLineWorkflowTemplate that includes a new approval
element. Make sure that you create a new status field on the lines of the free text
invoice and that you enable work item queues for the free text invoice template.

When you are finished, add the new free text invoice line workflow into the
CustFreeTextInvoiceTemplate as a line-item workflow.

Challenge Yourself: Posting Logic Extra Credit


Modify the free text invoice posting logic to make sure that the invoice cannot be
posted when one or more lines are not approved.

NOTE: There are no step by step instructions for completing this. For an
example of how this is implemented, refer to the Development III in Microsoft
Dynamics AX 2012 class for more information about how this would be
achieved.

11-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Need a Little Help?

1. Create a new project named WorkflowWorkshop to store all the


objects that will be modified or created in this workshop.
2. Create a new workflow status field on the free text invoice line table
by using the same extended data type that is used for the free text
invoice header.
3. Add the new status field to the Free text invoice form.
4. Create a new query to define the data that is used by the workflow.
5. Run the Workflow Type Wizard to create a new workflow type.
6. Complete the tasks that are documented by the wizard in the
compiler for the new workflow type.
7. Run the Approval Wizard to create a new approval element for the
workflow.
8. Complete the tasks that are documented by the wizard in the
compiler for the new workflow approval element.
9. Add the approval element to the workflow type.

Step by Step: Create a Project


To create a project for the new workflow, follow these steps.

1. Open the Development Workspace.


2. Click the Projects icon in the toolbar.
3. Right-click the Shared Projects node, and then select New >
Project.
4. Right-click the new project, and then select Properties.
5. In the Properties window set the Name to WorkflowWorkshopLab.
6. Double-click on the WorkflowWorkshop project to open the project
details.

Step by Step: Free Text Invoice Line Status


To implement a new status field in the free text invoice line table and the Free
text invoice form, follow these steps.

1. In the AOT expand Data Dictionary > Tables, and then select the
CustInvoiceLine table.
2. Drag the CustInvoiceLine table into the WorkflowWorkshop
project.
3. Expand the CustInvoiceLine table and then right-click the Fields
node.
4. Select New > Enum.
5. In the Properties window for the new field, set the Name to
WorkflowStatus.
6. Set the Enum property to CustFreeInvoiceWFApprovalStatus.

11-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

7. Set the AllowEdit and the AllowEditOnCreate properties to No.


8. Save the project.
9. In the AOT expand Forms and then select the CustInvoiceTable
form.
10. Drag and drop the CustFreeInvoice form into the project.
11. Right-click the project and then click Restore.
12. Expand Data Sources > CustInvoiceLines > Fields, and locate the
Workflow status field.
13. Browse to the lines grid on the form by expanding Designs > Design
> Tab:TabMain > Tab:TabPageDetails > Tab:TabDetails >
TabPage:CombinedViewTabPage > TabPage:CVFastTab >
TabPage:CVLinesFastTab > Grid:LinesGrid.
14. Drag the Workflow status field from the Data Sources node to the
last field on the grid.
15. Save the project.

Step by Step: Create a Query


To create a new query to use with the new free text invoice line document class,
follow these steps.

1. In the AOT, right-click the Queries node and then select New
Query.
2. Select the new query that is created, and then in the Properties
window set the Name to CustFreeTextInvoiceLineDocument.
3. Expand the query node and then right-click the Data Sources node
and select New Data Source.
4. Set the Name property to CustInvoiceLine.
5. Set the Table property to CustInvoiceLine.
6. Expand the CustInvoiceLine data source and then right-click in the
Data Sources node and select New Data Source.
7. Set the Name property to CustInvoiceTable.
8. Set the Table property to CustInvoiceTable.
9. Set the Relations property to Yes.
10. Expand the CustInvoiceTable node.
11. Right-click the Fields node under CustInvoiceLines and set the
Dynamic property to Yes.
12. Right-click the Fields node under CustInvoiceTable and set the
Relations property to Yes.
13. Right-click the Fields node under CustInvoiceTable and set the
Dynamic property to Yes.
14. Save the project.
15. Drag the new query into the WorkflowWorkshopLab project.

11-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Step by Step: Create a Workflow Type


To create a new workflow type by using the wizard, follow these steps.

1. In the AOT, expand the Workflow node.


2. Right-click the Workflow Type node and then select Add-Ins >
Workflow type wizard.
3. On the Workflow Wizard click Next >.
4. In the Name field enter CustFTLineTemplate.
5. In the Category field, select CustCategory.
6. Set the Query property to CustFreeTextInvoiceLineDocument.
7. Set the Document menu item property to CustFreeInvoice.
8. Click Next.
9. Click Finish.
10. On the Workflow type created dialog box, click OK.

TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_11_01_LAB_CODE.txt file. You can copy and paste
these code samples into the correct methods.

Next you must update the methods in the CustFTLineTemplateEventHandler


created by the workflow wizard. Follow these steps to update the started method.

1. In the Compiler window, double-click the message which reads


Write code to execute once the workflow is started.
2. In the Code Editor window for the started() method enter the
following code.

public void started(WorkflowEventArgs _workflowEventArgs)


{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Pending;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

11-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

To update the canceled method, follow these steps.

1. In the Compiler window, double-click the message which reads


"Write code to execute once the workflow is canceled".
2. In the Code Editor window for the canceled() method enter the
following code.

public void canceled(WorkflowEventArgs _workflowEventArgs)


{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Cancellation;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

To update the completed method, follow these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is completed."
2. In the Code Editor window for the completed() method enter the
following code.

public void completed(WorkflowEventArgs _workflowEventArgs)


{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Completed;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

11-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

To create a submit method for class CustFTLineTemplateSubmitManager, follow


these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is submitted".
2. In the Code Editor window, click New.

void submit(Args args)


{
// Variable declaration.
recId recId = args.record().RecId;
WorkflowCorrelationId workflowCorrelationId;
// Hardcoded type name
WorkflowTypeName workflowTypeName =
workflowtypestr(CustFTLineTemplate);
// Initial note is the information that users enter
when they
// submit the document for workflow.
WorkflowComment note ="";
WorkflowSubmitDialog workflowSubmitDialog;
CustInvoiceLine custInvoiceLine;
// Opens the submit to workflow dialog.
workflowSubmitDialog =
WorkflowSubmitDialog::construct(args.caller().getActiveWork
flowConfiguration());
workflowSubmitDialog.run();
if (workflowSubmitDialog.parmIsClosedOK())
{
recId = args.record().RecId;
CustInvoiceLine = args.record();
// Get comments from the submit to workflow
dialog.
note = workflowSubmitDialog.parmWorkflowComment();
try
{
ttsbegin;
workflowCorrelationId =
Workflow::activateFromWorkflowType

(workflowTypeName,
recId,
note,
NoYes::No);
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Submitted;
// Send an Infolog message.
info("Submitted to workflow.");
ttscommit;
}
catch(exception::Error)
{
info("Error on workflow activation.");
}
}
args.caller().updateWorkFlowControls();

11-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

3. Save the class.


4. Close the Editor window.

To update the main method of CustFTLineTemplateSubmitManager, follow


these steps.

1. In the Code Editor window, select the Main method.


2. Enter the following code sample into the method.

public static void main(Args args)


{
CustFTLineTemplateSubmitManager
CustFTLineTemplateSubmitManager;
CustFTLineTemplateSubmitManager = new
CustFTLineTemplateSubmitManager();
CustFTLineTemplateSubmitManager.submit(args);
}

3. Save the class.


4. Close the Code Editor window.
5. Close the Compiler output window.
6. Drag all of the objects from the Project
CustFTLineTemplateWFType window into the Project
WorkflowWorkshopLab window.
7. Close the Project CustFTLineTemplateWFType window.

Step by Step: Create an Approval Element


To use the approval wizard to create a new approval element, follow these steps.

1. In the AOT, expand the Workflow node.


2. Right-click the Approval node and then select Add-Ins > Approval
wizard.
3. Click Next on the Workflow wizard form.
4. Enter FreeTextLineApproval into the Name field.
5. Select CustFTLineTemplateDocument in the Workflow document
field.
6. Select CustomerFreeTextInvoiceLine in the Document preview
field group.
7. Select CustFreeInvoice in the Document menu item field.
8. Click Next.
9. Click Finish.
10. On the Workflow approval element created dialog box, click OK.

11-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Next you must update the methods in the FreeTextLineApprovalEventHandler


created by the workflow wizard. To update the canceled method, follow these
steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is canceled."
2. In the Code Editor window for the canceled() method, enter the
following code.

public void canceled(WorkflowElementEventArgs


_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Cancellation;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

To update the completed method, follow these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is completed."
2. In the Code Editor window for the completed() method, enter the
following code.

public void completed(WorkflowElementEventArgs


_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Completed;
custInvoiceLine.update();
ttsCommit;
}

11-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

3. Save the class.

To update the changeRequested method, follow these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once change is requested for the workflow."
2. In the Code Editor window for the changeRequested() method,
enter the following code.

public void changeRequested(WorkflowElementEventArgs


_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::ChangeRequested;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

To update the returned method, follow these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is returned."
2. In the Code Editor window for the returned() method, enter the
following code.

public void returned(WorkflowElementEventArgs


_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Rejected;
custInvoiceLine.update();
ttsCommit;
}

11-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

3. Save the class.

To update the started method, follow these steps.

1. In the Compiler window, double-click the message that reads "Write


code to execute once the workflow is started."
2. In the Code Editor window for the started() method, enter the
following code.

public void started(WorkflowElementEventArgs


_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;

custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::PendingApproval;
custInvoiceLine.update();
ttsCommit;
}

3. Save the class.

To update the class declaration, follow these steps.

1. In the FreeTextLineApprovalApprovalElement project, expand the


FreeTextLineApprovalEventHandler class.
2. Double-click the classDeclartion.
3. In the Code Editor window for the classDeclaration enter the
following code.

class FreeTextLineApprovalEventHandler implements


WorkflowElementCanceledEventHandler,
WorkflowElemChangeRequestedEventHandler,
WorkflowElementCompletedEventHandler,
WorkflowElementReturnedEventHandler,
WorkflowElementStartedEventHandler
{
}

4. Save the class.

11-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

To delete the created and denied methods, follow these steps.

1. In the FreeTextLineApprovalApprovalElement project, expand


the FreeTextLineApprovalEventHandler class.
2. Right-click the created() method and select Delete.
3. On the Confirm remove dialog box, click OK.
4. Right-click the denied() method and select Delete.
5. On the Confirm remove dialog box, click OK.
6. Save the class and then close the Code Editor windows.
7. Drag all of the objects from the Project
FreeTestLineApprovalElement window into the Project
WorkflowWorkshopLab window.
8. Close the Project FreeTestLineApprovalElement window.
9. Close the Compiler output window.

Next, you must add the approval element to the workflow type. To add the
approval element to the workflow type, follow these steps.

1. In the AOT window expand Workflows > Workflow Types.


2. Expand the CustFTLineTemplate node.
3. Drag the FreeTextLineApproval from the
FreeTextLineApprovalApprovalElement project into the Supported
Elements node.
4. Save the workflow type.

Next, you must add the new free text invoice line template to the free text invoice
header template so that it is available as a line-item workflow. To add the line
template to the header template, follow these steps.

1. In the AOT window expand Workflows > Workflow Types.


2. Locate the CustFreeTextInvoiceTemplate and drag it into the
WorkflowWorkshopLab project.
3. Expand the CustFreeTextInvoiceTemplate, and then right-click the
Line Item Workflows node of the CustFreeTextInvoiceTemplate
and select New Line Item Workflow.
4. Set the Name property to CustFTLineTemplate.
5. Set the Label to Free text invoice line.
6. Expand the new CustInvoiceLine node and then right-click the Line
Item Workflow Types node and then select New Line Item
Workflow Type.
7. In the LineItemWorkflowType property, select
CustFTLineTemplate.

11-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

8. Save the project.


9. Compile the project and verify that there are no errors. There will be
one Task, which can be ignored.
10. In the Development Workspace, click Build > Generate
Incremental CIL.

TIP: You can import the AX2012_ENUS_DEVIV_11_01_LAB_SOL.xpo file to


verify and compare your solution.

11-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Summary
Workflow in Microsoft Dynamics AX 2012 supports many new advanced
features. The line-item workflow types are used to create a workflow for data that
has a header and line relationship.

Additionally, the workflow provider framework gives developers the flexibility


to assign workflow elements to participants, queues, and users in a hierarchical
structure.

This chapter also reviewed the classes and attributes that can be called and
extended by the developer to present currency and hierarchy type fields in the
Condition Editor.

11-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Put the following steps for developing a new work item queue in order:

Step:

_____: Add the menu item on the main menu.

_____: Create a new menu item.

_____: Create a new query.

_____: Override the mapFields() method.

_____: Set the query property on the menu item.

_____: Set the WorkItemsCreatedEventHandler property on the approval or


task element.

_____: Create a new class that extends


WorkflowQueueCreatedEventHandler.

_____: Add the WorkflowDocIsQueueEnabledAttribute attribute to the


workflow document.

2. Categorize the following items:

_____ 1. Used to provide a specific end item, when a. Due Date Provider
a particular starting item is provided. b. Participant
_____ 2. Used to determine a specific due date for Provider
a task or approval based on a specified start date. c. Queue Provider
_____ 3. Used to provide a list of users from any d. Hierarchy
abstraction, such as a user group. Provider
_____ 4. Used to provide a list of users from a
work item queue that is configured in the Home
module.

11-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

3. Describe the difference between the getDistance() and getLookup() method


in a class that implements the ExpressionHierarchyProvider class.

4. Describe why you would set the EnableLineItemWaitSelection to Yes on a


line-item workflow.

11-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

11-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow

Solutions
Test Your Knowledge
1. Put the following steps for developing a new work item queue in order:

Step:

8 : Add the menu item on the main menu.

6 : Create a new menu item.

5 : Create a new query.

3 : Override the mapFields() method.

7 : Set the query property on the menu item.

4 : Set the WorkItemsCreatedEventHandler property on the approval or


task element.

2 : Create a new class that extends


WorkflowQueueCreatedEventHandler.

1 : Add the WorkflowDocIsQueueEnabledAttribute attribute to the


workflow document.

2. Categorize the following items:

d 1. Used to provide a specific end item, when a a. Due Date Provider


particular starting item is provided. b. Participant
a 2. Used to determine a specific due date for a Provider
task or approval based on a specified start date. c. Queue Provider
b 3. Used to provide a list of users from any d. Hierarchy
abstraction, such as a user group. Provider
c 4. Used to provide a list of users from a work
item queue that is configured in the Home module.

3. Describe the difference between the getDistance() and getLookup() method


in a class that implements the ExpressionHierarchyProvider class.

MODEL ANSWER:

getDistance(): Returns the distance from the target node to the source node in
a hierarchy. If a direct path from the source node to the target node does not
exist then a nonzero value must be returned.
getLookup(): Displays a lookup table that represents the hierarchy from
which the user can select a node. The lookup table is typically the primary
key table for this field in the foreign key table.

11-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

4. Describe why you would set the EnableLineItemWaitSelection to Yes on a


line-item workflow.

MODEL ANSWER:

If you want to give the business user access to choose whether the line-item
workflow element should be wait for all line-item workflows to complete
before moving on to the next element.

11-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

CHAPTER 12: REPORTING


Objectives
The objectives are:

• Explain the report capabilities in Microsoft Dynamics® AX 2012.


• Describe the key concepts involved when specifying data for your
reports.
• Create a new query and then bind the query to a new SQL Server
Reporting Services report together with an auto design.
• Add sorting, grouping, filters, and parameters to a report.
• Save, deploy, and view a report in Microsoft Dynamics AX.
• Discuss the Model-View-Controller (MVC) pattern.
• Define the report dataset.
• Create a temporary table to store the report dataset.
• Manage report parameters in a data contract class in X++.
• Create a report data provider (RDP) class.
• Work with report precision design.
• Explain how to print a report, set the print settings, prevent the
display of print setup, set the query range, and set a report parameter
value in X++.
• Review how reports bound to a report data method can contain
business logic to access data.
• Describe the components of print management and the steps that are
used to implement each component of print management.

Introduction
SQL Server Reporting Services (SSRS) is the primary reporting platform for
Microsoft Dynamics AX 2012. The default, out-of-the-box reports that are
provided with Microsoft Dynamics AX run on the Reporting Services platform.
They give users better looking reports, more export formats, and a more capable
report designer. The goals for this transition include following:

• Use the Microsoft technology stack.


• Keep business logic in Microsoft Dynamics AX.
• Transition for X++ and C# developers to the new reporting
architecture is simplified.

12-1
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

This chapter introduces you to the features of SSRS and shows how to create
simple reports by using a query and an auto-design. In addition, a complex report
using by the new report data provider framework in a precision design is
reviewed. The model-view-controller coding pattern for report data providers is
discussed and tips for selecting the correct development technology for your
reports are reviewed.

Reporting Features Overview


The following topics review the features and capabilities of SSRS in Microsoft
Dynamics AX 2012.

Reporting Architecture
The report development pattern in used for SSRS reports Microsoft Dynamics
AX 2012 uses the Model-View-Controller (MVC) design pattern variation. This
pattern allows many client types to call Microsoft Dynamics AX 2012 Reporting
Services reports including: Microsoft Dynamics AX clients, Enterprise Portal,
and Batch Job. This also means that Reporting Services can be replaced by a
different application for rendering reports.

The following figure illustrates the SSRS architecture in Microsoft Dynamics AX


2012.

FIGURE 12.1 SSRS REPORTING ARCHITECTURE

12-2
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Installation and Deployment


When you installed the components in Microsoft Dynamics AX 2009, you had to
install the reporting extensions while running the Setup wizard. For Microsoft
Dynamics AX 2012, the Setup wizard is changed. It no longer includes an option
for installing the reporting extensions.

When you run the Setup wizard for Microsoft Dynamics AX 2012, you can
install the business intelligence components. While installing the business
intelligence components, the Setup wizard will:

• Verify that prerequisite software is installed on the server.


• Prompt you to select a SQL Server Reporting Services instance.
• Prompt you to select a SQL Server Analysis Services instance.

Reports in Microsoft Dynamics AX 2012 are deployed by using PowerShell


scripts.

Upgrade Consideration
Reports and cubes are not upgraded to Microsoft Dynamics AX 2012. The X++
reporting framework is being deprecated in Microsoft Dynamics AX 2012.
Reports that are based on the X++ reporting framework and existing SQL Server
Reporting Services reports will be copied to the Microsoft Dynamics AX 2012
system. However, they will not be upgraded. It is recommended to use a SQL
Server Reporting Services report that is provided with Microsoft Dynamics AX
2012 as a template and customize it to meet your needs.

Configuration
You can use the Reporting services framework to modify the queries used to
retrieve data for reports. This means that you can now use SQL Reporting
Services capabilities to filter, group, and sort data in reports.

Auto-Reports
With Microsoft Dynamics AX 2012, you can use the Auto-report wizard to
create custom, ad hoc reports that are based on the SQL Server Reporting
Services framework. To start the Auto-report wizard, click the Print icon on a
form.

Batch Support
SQL Server Reporting Services reports in Microsoft Dynamics AX 2012 are now
integrated with the Microsoft Dynamics AX batch framework. You can schedule
a long-running report to print during off-peak hours and schedule a report to print
on a recurring basis.

12-3
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Report Web Parts


The Web Part used to display reports in Role Centers and other Enterprise Portal
pages is updated. This Web Part used for adding an SSRS report is called
Microsoft Dynamics AX Report. The Web Part has also been updated to improve
usability. Now it is easier to add the Web Part to a page, select a report to display
in the Web Part, and select parameters to filter the data displayed on the report.

Support for Multiple Languages


In Microsoft Dynamics AX 2012, you can deploy a report that will automatically
reflect all supported languages when labels are used for the static text.

Report Data Overview


You can use the Microsoft Visual Studio tools for Microsoft Dynamics AX to
create reports by using data from several different sources. This topic provides a
description of the key concepts involved when specifying data for your reports.

Report Data Sources


A data source represents a source of data for one or more reports. Depending on
where the data is located, you can use the data source for Microsoft Dynamics
AX, or you can define your own data source.

Dynamics AX Data Source

The Dynamics AX data source is provided for you. It connects to the Microsoft
Dynamics AX database. With this data source, you can use queries and Report
Data Provider classes that are defined within the Application Object Tree (AOT)
in Microsoft Dynamics AX, and data methods that are defined within your
reporting project in Visual Studio.

The Microsoft Dynamics AX data source does not display in the model with the
other report elements. It is available from the drop-down menus in the reporting
tools, and it can be used for a system that works from a SQL database with no
additional modifications needed for reports.

When you select Microsoft Dynamics AX as the data source for the report, you
will point to the active Application Object Server (AOS). If you want to use an
AOS from another computer that is not the active AOS, you must configure the
Business Connector session by using the client configuration utility to point to
another AOS.

Defining Additional Data Sources

You can define additional data sources as needed. For example, you can create a
data source to connect to data from a legacy system, online analytical processing
(OLAP) data, or some other external database.

12-4
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

NOTE: You can use the Dynamics AX OLAP data source type to connect to
databases deployed by using the Cube Administration wizard.

You define a data source in a model with the other report elements, and you must
also specify a data provider and a connection string. The data provider serves as a
bridge between a report and its data and is used to retrieve the data. There are
two providers that you can choose from when defining a data source: SQL and
OLAP. The connection string that you supply contains the information that is
used when connecting to the data source.

For example, if you are connecting to an SQL database, you can specify the
server name, the database name, and the authentication method for validating a
user. After you have defined a data source, it is displayed as an element in your
model and is available as an option in drop-down menus in the reporting tools.

A data source can be shared by one or more reports. A report can use one or more
data sources.

Report Datasets
A report dataset identifies the data from a data source that displays in a report.
When you define a dataset, you must specify the data source and the means used
to retrieve the data, such as a query or data method. The following table describes
the options for retrieving data for a report.

Data source Option


Dynamics AX • Queries that are defined in the AOT
• Report Data Provider classes that are defined in the
AOT
• Data methods that are defined within a reporting
project in Microsoft Visual Studio
SQL • TSQL query
• Stored procedure
• Dynamics AX OLAP
OLAP MDX query, this is used to connect to third party
databases.

If your report uses the Dynamics AX data source and a query that is defined in
the AOT in Microsoft Dynamics AX, you must be especially careful when
updating the query in the AOT. For example, if you remove a field in the query
and the field displays in the report, the report will display an empty column for
the field. Whenever you make updates to a query, consider how those updates
can affect your reports. Updates to a query can also require updates to your
reports.

A report can have multiple datasets. A dataset can be used by one or more data
regions in a report.

12-5
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Security Considerations
When accessing data from the Microsoft Dynamics AX database, it is
recommended that you use the Microsoft Dynamics AX data source to make sure
that appropriate security is enforced. When you use the Microsoft Dynamics AX
data source, you can use queries or Report Data Provider classes that are defined
in the AOT. All data access requests are processed by using the MorphX security
system. When you use an external SQL or OLAP data source, security from the
MorphX security system is not applied when accessing data. In this case, you can
use the role-based security features that are available from Microsoft SQL Server
to help secure the data.

Guidance for Choosing Data Source Types


When you define a report in Microsoft Dynamics AX you must specify how to
access the data for your report. The options for a data source type are query,
business logic, and report data provider.

The following table provides detail on when to use each data source type to
access data for your report.

Data Source Type Description


Query Use when data can be accessed by using an AX
Query. An AX Query is a query that is defined in
the AOT. No X++ code is involved except for
display methods.
A query to access data has the following
advantages:
• A query with a display method has no code
that needs to run. You can query for data
directly from a table. Filtering occurs in SQL
which is faster.
• There are no X++ classes to develop. You
define a query in the AOT.
Business Logic Use when your business logic is contained in C#
code. Your code must return a dataset.

12-6
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Data Source Type Description


Report Data Use when portions of the report data set are
Provider derived from business logic contained in X++
code. The following lists specific examples.
• Business logic processing is based on
parameters values.
• Data to be rendered can be materialized by
calling X++ business classes.
• Use dynamic filters to allow the user to add
more filters to an underlying query at run time.
NOTE: A query should be considered before you
use a Report Data Provider class.
AX Enum Provider Use when the report parameter is an Enum type.
These parameters expose Enum types on a report
in a friendly drop-down list. You can create a
range on a query to expose an enum parameter in
the Microsoft Dynamics AX client. However, if
you want the report to be run from the Enterprise
Portal, you must use an AX Enum Provider to
define the parameter.

A controller class runs the report by creating the UI, calling SQL Server
Reporting Services, and preprocessing the parameters for the report.

If any of the following scenarios occur, you must extend the


SrsReportRunController class to create a custom controller for the report.

• Report requires input data to be preprocessed.


• Report requires input data to be manipulated or modified.
• Multiple reports should be run from the same dialog box.

NOTE: Reports that use a controller class must take care of the parameters
when the report is used on the Enterprise Portal.

12-7
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Creating Basic Reports from a Query


This lesson focuses on the basics for developing simple reports. There are several
ways to retrieve data for reports. In this walkthrough, you will use a query that is
defined in the AOT within the Microsoft Dynamics AX development
environment. The following illustration shows the report that you will create.

FIGURE 12.2 SAMPLE CUSTOMER TRANSACTION LIST REPORT

Development Actions
The following demonstration shows how to create a query bound report that
exposes Customer Transaction data.

The steps that are involved include create a Microsoft Dynamics AX query, add
field data to the query, create a new report model in Visual Studio, create a report
dataset, create a report design and apply style templates.

Demonstration: Define a Query


To create a new query in the AOT, follow these steps:

1. Open the Development Workspace.


2. In the AOT, right-click the Queries node, and then click New
Query.
3. Right-click the node for the query, click Rename, and then type a
name such as CustTrans_W1.
4. Expand the CustTrans_W1 node.
5. Right-click the Data Dictionary node, and then click Open New
Window.
6. In the new window, expand the Tables node.
7. Locate the CustTrans table and drag it onto the Data Sources node
for the CustTrans_W1 query.

12-8
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Demonstration: Add Table Field Data to a Query


To select fields on the query, follow these steps:

1. Locate the CustTrans_W1 query.


2. Expand the CustTrans_1 dataset node.
3. Right-click the fields node of the query, click Properties.
4. Set the Dynamic property to Yes, and then save the report. Then set
the property to No so fields can be removed from the view.
5. Only include the following fields in your dataset view
"AccountNum", "AmountCur", "Invoice", "TransDate",
"TransType", and "Txt". You can delete fields by highlighting the
desired fields and then right-click and select Delete, then click OK
to accept the deletion.
6. Save the query.

Demonstration: Create a New Report in Visual Studio


To create a new reporting project and report, follow these steps:

1. Open Microsoft Visual Studio 2010.


2. On the File menu, point to New, and then click Project. The New
Project dialog box is displayed.
3. In the Installed Templates pane, click the Microsoft Dynamics AX
node, and in the Templates pane, click Report Model.
4. In the Name box, type a name for the project such as CustTrans_W1,
and in the Location box, type a file path to save the project.
5. Click OK.
6. If the Solution Explorer pane is not open click View > Solution
explorer.
7. In the Solution Explorer pane, click the Add button and select
Report. An empty report model named Report1 is created.

Demonstration: Create a Report Dataset


The dataset in a report is similar to the data sources of a form. They are used to
define the data that will be selected and displayed on a report. To create a query
based dataset, follow these steps:

1. In the Model Editor, right-click the Report1 node, and then click
Rename.
2. Type CustTrans_W1 as the name.
3. Expand the CustTrans_W1 node if it is not already expanded.
4. Right-click the Datasets node, and then click Add Dataset.
5. Select the node for the dataset.

12-9
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. In the Properties window, specify the following values.


a. Data Source = Dynamics AX
b. Data Source Type = Query
c. Default Layout = Table
d. Name = CustTransDS
e. Query = Select * from CustTrans_W1

Demonstration: Create a Report Design


To view the report data by using an AutoDesign, follow these steps:

1. In the Model Editor, select the CustTransDS node and drag it onto
the Designs node. An auto design named AutoDesign1 is created for
the report.
2. Right-click the AutoDesign1 node, and then click Preview. The
Error List pane will open with warnings. This can be ignored.
3. Click the Report tab on the Preview window to view the report. The
report appears unformatted, because you have not yet applied any
layout or style templates to it. The following figure is a sample of
how the report will look.

FIGURE 12.3 REPORT PREVIEW SAMPLE

4. Close the Preview window.

12-10
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Demonstration: Apply Layout Templates


The Error List window shows two warnings about the layout template and the
table style template. This warnings must be corrected to change the formatting of
the report to appear more like a standard report. To apply layout and style
templates, follow these steps.

1. In the Model Editor, select the AutoDesign1 node.


2. In the Properties window, set the LayoutTemplate property to
ReportLayoutStyleTemplate.
3. Type "Customer Transaction List" for the Title property.
4. In the Model Editor, expand the AutoDesign1 node, and then select
the node for the CustTransDSTable data region.
5. In the Properties window, set the Style Template property to
TableStyleTemplate.
6. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new style settings for the report.
7. When the Preview window opens, click the Report tab. The
following figure is a sample of how the report will look.

FIGURE 12.4 REPORT PREVIEW SAMPLE

8. Close the Preview window.

12-11
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Demonstration: Add Column Sorting to the Report


The following demonstration shows how to add column sorting to an AutoDesign
report by using built in tools. The two steps that are involved include establishing
default sorting, and enabling run-time column sorting.

Procedure: Add Default Sorting to the Report

To establish default sorting based on a dataset column follow these steps:

1. In the Model Editor, expand the AutoDesign1 node, and then select
the Sorting node under the CustTransDSTable data region.
2. Right-click the Sorting node, and then click Add Sort.
3. Type AccountNum as the name.
4. In the Properties window, set the Sort By property to
=Fields!AccountNum.Value.
5. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new sorting for the report.
6. When the Preview window opens, click the Report tab.
7. Close the Preview window.
8. Save the report.

Procedure: Enable Run-Time Sorting

To modify the column properties so that the user can decide the column sorting,
follow these steps.

1. In the Model Editor, expand the AutoDesign1 node, and then select
the AccountNum field under the Data region of the
CustTransDSTable node.
2. In the Properties window, set the Interactive sorting property to
True.
3. Repeat step 1 and 2 for the AmountCur, TransDate, and
TransType1 columns.
4. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new style settings for the report.

12-12
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

5. When the Preview window opens, click the Report tab. The
following figure is a sample of how the report will look when sorted
by the date. Notice the sorting arrows next to the Customer account,
Amount transaction in currency, and Date fields.

FIGURE 12.5 REPORT PREVIEW SAMPLE

6. Close the Preview window.


7. Save the report.

Demonstration: Grouping Report Data


The following procedures show how to group report data by using Visual Studio
Tooling. The two steps that are involved include group report data based on
customer account and then aggregate group data to display totals.

Procedure: Group the Report Data

To group the report dataset, follow these steps:

1. In the Model Editor, expand the AutoDesign1 node.


2. Right-click the Groupings node under the CustTransDSTable data
region, and then click Add Grouping.
3. Type Group1 as the name.
4. In the Properties window, set the Label property to
=Fields!AccountNum.Value.
5. Right-click the Group on node, and then click Add Group on.
6. Type AccountNum as the name.

12-13
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

7. In the Properties window, set the Expression property to


=Fields!AccountNum.Value.
8. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new style settings for the report.
9. When the Preview window opens, click the Report tab. The
following figure is a sample of how the report will look when
grouped by the account number.

FIGURE 12.6 REPORT PREVIEW SAMPLE

10. Close the Preview window.


11. Save the report.

Procedure: Aggregate Grouped Data

To aggregate report data in the footer, follow these steps:

1. In the Model Editor, expand the AutoDesign1 node, and then select
the AccountNum field under the Data node.
2. Right-click the Group1 node, and then click Properties.
3. In the Properties window, expand Instance Aggregates, and set
Render Location to Group Footer.
4. Select the AmountCur field under the Data node
5. In the Properties window, expand the Aggregation item, and set
Aggregate Function to Sum.
6. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new style settings for the report.
7. When the Preview window opens, click the Report tab. Notice the
totals for each customer.

12-14
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

8. Close the Preview window.


9. Save the report.

Demonstration: Add Filtering to a Report


The following procedure shows how to filter report data based on user input by
using a free text control. The steps that are involved include adding a range to the
Microsoft Dynamics AX query, adding a parameter to the report, and filtering the
data by using the parameter value supplied.

Procedure: Add a Range to the Query

To add a query range, follow these steps:

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Queries node, and then locate the
CustTrans_W1 query.
4. Browse to Data Sources > CustTrans_1 > Ranges node.
5. Right-click the Ranges node, and then click New Range. A default
range by using the AccountNum field is created for you by
Microsoft Dynamics AX.
6. Save the query.

Procedure: Add a Parameter to the Report

To add a report parameter, follow these steps.

1. Open the report in Visual Studio.


2. In the Model Editor, select the CustTransDS node.
3. Right-click the node and select Refresh to reflect changes that were
made to the Microsoft Dynamics AX query
4. Expand the Parameters node of the report (make sure not to select
the Parameters node of the dataset) to display the list of report
parameters.
5. Right-click the node and select Add > Parameter
6. Type AccountParam as the name
7. In the Properties window, set the Prompt String property to
Account.
8. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new parameter for the report. Notice the
new Account field on the Parameters tab.
9. Close the Preview window.
10. Save the report.

12-15
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Filter Data by Using the Parameter Value

At this point the report has a parameter added. However, the data on the report is
not being filtered when a value is entered into the parameter field. To filter the
report dataset, follow these steps.

1. In the Model Editor, expand the AutoDesign1 node.


2. Right-click the Filters node and select Add Filter.
3. Type AccountFilter as the name.
4. In the Properties window, set the Expression property to
=Fields!AccountNum.Value.
5. Set the Operator property to Like.
6. Set the Value property to =Parameters!AccountParam.Value
7. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new settings for the report.
8. On the Parameters tab, enter 1101 into the Account field, and then
click the Report tab. The following figure is a sample of how the
report will look when filtered for account number 1101.

FIGURE 12.7 SAMPLE REPORT PREVIEW

9. Close the Preview window.


10. Save the report.

Demonstration: Add Dynamic Parameters to the Report


The last example showed how to add a parameter to the report that allows users
to enter a free form string. However, in a more realistic example, report
parameters often times have a predefined list of values. For example, there is a
predefined list of customer account numbers. Instead of allowing the user to type
in any value, which might not be valid, you can change the parameter to include
a drop-down list of valid values.

12-16
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

The following demonstration shows how to filter report data based on a dynamic
parameter that is bound to a Microsoft Dynamics AX query. The steps that are
involved include creating a Microsoft Dynamics AX query, creating a new
dataset and binding it to the query, binding the report parameter to the query
results, and filtering the report dataset by using the parameter value.

Procedure: Define a Query

To define a query, follow these steps:

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. Create a new query.
4. Rename the query to CustTable_W1.
5. Expand the CustTable_W1 node.
6. Locate the CustTable table and drag it onto the Data Sources node
for the CustTable_W1 query.
7. Select the CustTable_1 data source, and then highlight the Fields
node and set the Dynamic property to No.
8. Right-click the Fields node and select New > Field.
9. Save the query.

Procedure: Bind a Dataset to the Query

To bind a dataset to the Query, follow these steps:

1. Open the report that you created earlier in Visual Studio.


2. In the Model Editor, right-click the Datasets node, and then click
Add Dataset.
3. Type CustomersDS as the name.
4. Select the node for the dataset.
5. In the Properties window, specify the following values:
a. Data Source = Dynamics AX
b. Data Source Type = Query
c. Default Layout = Table
d. Name = CustomerDS
e. Query = Select * from CustTable_W1

Procedure: Bind Report Parameters to a Data Source

To bind report parameter to a dataset, follow these steps.

1. In the Model Editor, select the AutoDesign1 node.


2. Expand the Parameters node to display the list of report parameters
3. Select the AccountParam node.

12-17
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

4. In the Properties window, click the elipses (...) button in the Values
property.
5. Select the From Dataset option and set the following:
a. Dataset: CustomersDS
b. Value Field: AccountNum
c. Label Field: AccountNum

6. Click OK.
7. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new settings for the report. Notice the
Account field on the Parameters tab now shows a list of all
customers and a check box next to each customer number which
allows you to select multiple customers.
8. Close the Preview window.
9. Save the report.

Demonstration: Save and Deploy the Report


At this point you have only viewed the report from inside Visual Studio. In order
for users to be able to use the new report that you have created, you must save
and deploy the report. To save the report to the AOT and deploy to the SSRS
Server, follow these steps.

1. Rebuild the solution


a. Right-click the project (CustTrans_W1) in the Solution
Explorer pane, and select Rebuild.
b. Verify that you have no build errors.
2. Save the report to the AOT
a. Right-click the project (CustTrans_W1) in the Solution
Explorer pane, and select Add CustTrans_W1 to AOT.
b. Verify that you can add to the AOT.

3. Deploy the Report


a. Right-click the project (CustTrans_W1) in the Solution
Explorer pane, and select Deploy.
b. Verify that you can deploy the report.

12-18
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Demonstration: View the Report in Microsoft Dynamics


AX
The following demonstration shows how to view the report in the Microsoft
Dynamics AX client. The steps that are involved include creating a Microsoft
Dynamics AX menu item linked to the newly created report design, viewing the
report in the Microsoft Dynamics AX client, and adding the menu item to the
menu.

Procedure: Create a Menu Item

To create a menu item in Microsoft Dynamics AX, follow these steps.

1. Open the Development Workspace.


2. In the AOT window, expand the Menu Items node and select the
Output node.
3. Right-click the Output node and then click New Menu Item.
4. Type CustTrans_W1 as the name.
5. Right-click the CustTrans_W1, select Properties, and then set the
following
a. ObjectType: SSRSReport
b. Object: CustTrans_W1
c. ReportDesign: AutoDesign1
d. Label: Customer transaction list

6. Save the menu item.


7. Right-click the CustTrans_W1 menu item and select Open.

FIGURE 12.8 CUSTOMER TRANSANCTION LIST REPORT DIALOG BOX

12-19
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Add a Menu Item to the Menu

To add a menu item to the menu, follow these steps:

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, expand Menu Items node and select the Output node.
4. Right click the Output node, and then select Open New Window.
5. In the original AOT window, expand Menus.
6. Expand AccountsReceivable > Reports > Transactions >
Customer.
7. Select the Menu Item to add to the menu in the new AOT window
that was opened in step 4.
8. Drag the Menu Item into the Menu.

IMPORTANT: You cannot view the changes to the menu unless you log off
Microsoft Dynamics AX and then log on again.

BEST PRACTICE: It is recommended that all menu items have security


implemented. For more information about how to develop security permissions
and privileges, refer to the Help.

TIP: You can import the AX2012_ENUS_DEVIV_12_01_DEMO.xpo file which


contains the sample customer transaction list report created in this
demonstration.

12-20
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Lab 12.1 - Report Workshop


This lab demonstrates creating a report from a query. The report design includes
sorting, grouping, filtering, and parameters.

Scenario

Isaac, the Developer, wants to create a Reporting Services report to expose


vendor transaction data.

Challenge Yourself!
Use the information that is provided to create a query bound report that exposes
vendor transaction data. Create the new report in Visual Studio and add sorting
and grouping by vendor account to the report. Then add a report filter for the
account number, and add a dynamic parameter for the vendor account. When you
are finished, save and deploy the report and add a menu item to the Accounts
Payable module to view the report on the menu.

Need a Little Help?

1. Create a Microsoft Dynamics AX query for the VendTrans table.


2. Add field data to the query.
3. Create a new report model in Visual Studio.
4. Create a report dataset.
5. Create a report design.
6. Apply Style Templates.
7. Add sorting and grouping for the account number.
8. Filter report data by account number.
9. Create a dynamic parameter for the account number.
10. Save and deploy the report.
11. Create a menu item.
12. Add the menu item to the Accounts Payable > Reports >
Transactions > Vendor menu.
13. View the report in Microsoft Dynamics AX 2012.

Step by Step: Create a Query

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Queries node, and then click New
Query.
4. Right-click the node for the query, click Rename, and then type
VendTrans_W1.
5. Expand the VendTrans_W1 node.

12-21
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. Right-click the Data Sources node and then select New Data
Source.
7. Enter VendTrans into the Table property field.
8. Expand the VendTrans_1 Dataset node.
9. Right-click the Fields node of the query, click Properties.
10. Change the Dynamic property to No so that fields can be removed
from the view.
11. Only include the following fields in your dataset view AccountNum,
AmountCur, TransDate, TransType, and Txt.
12. Save the query.

Step by Step: Create a New Report in Visual Studio

1. Open Microsoft Visual Studio 2010.


2. On the File menu, point to New, and then click Project. The New
Project dialog box appears.
3. In the Installed Templates pane, click the Microsoft Dynamics AX
node, and in the Templates pane, click Report Model.
4. In the Name box type SSRSDemo, and in the Location box, type a
file path.
5. Click OK.
6. In the Solution Explorer, click the Add button and select Report.
An empty report model named Report1 is created.
7. In the Model Editor, right-click the Report1 node, and then click
Rename.
8. Type VendTrans_W1 as the name.
9. Expand the VendTrans_W1 node if it is not already expanded.
10. Right-click the Datasets node and then click Add Dataset.
11. Select the node for the dataset.
12. In the Properties window, specify the following values:
13. Set the Data Source property to Dynamics AX.
14. Set the Data Source Type property to Query.
15. Set the Name property to VendTransDS.
16. Set the Query property to Select * from VendTrans_W1.
17. In the Model Editor, select the VendTransDS node and drag it onto
the Designs node. An auto design named AutoDesign1 is created for
the report.
18. Optional: Right-click the AutoDesign1 node, and then click Preview
and select the Report tab. The report appears unformatted, because
you have not yet applied any layout or style templates to it. Close the
Preview window.

12-22
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Step by Step: Apply Layout Template

1. In the Model Editor, select the AutoDesign1 node.


2. In the Properties window, set the Layout Template property to
ReportLayoutStyleTemplate. Also, type Vendor Transaction List for
the Title property.
3. In the Model Editor, expand the AutoDesign1 node, and then select
the node for the VendTransDSTable data region.
4. In the Properties window, set the Style Template property to
TableStyleTemplate.
5. Optional: In the Model Editor, right-click the AutoDesign1 node,
and then click Preview and select the Report tab to view the new
style settings for the report. Close the Preview window.

Step by Step: Add Column Sorting

1. In the Model Editor, expand the AutoDesign1 node, and then select
the Sorting node under the VendTransDSTable data region.
2. Right-click the Sorting node and then click Add Sort.
3. Type AccountNum as the name.
4. In the Properties window, set the Sort By property to
=Fields!AccountNum.Value.
5. In the Model Editor, right-click the AutoDesign1 node, and then
click Preview to view the new style settings for the report.
6. Close the Preview window.
7. Save the report.
8. In the Model Editor, expand the AutoDesign1 node, and then select
the AccountNum field under the Data region.
9. In the Properties window, set the Interactive sorting property to
True.
10. Repeat steps 8 through 9 for the AmountCur, TransDate, and
TransType1 columns.
11. Optional: In the Model Editor, right-click the AutoDesign1 node,
and then click Preview to view the new style settings for the report.
Close the Preview window.
12. Save the report.

Step by Step: Grouping Report Data

1. In the Model Editor, expand the AutoDesign1 node.


2. Right-click the Groupings node under the VendTransDSTable data
region, and then click Add Grouping.
3. Type Group1 as the name.
4. In the Properties window, set the Label property to
=Fields!AccountNum.Value.

12-23
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Right-click the Group on node, and then click Add Group on


6. Type AccountNum as the name.
7. In the Properties window, set the Expression property to
=Fields!AccountNum.Value.
8. Right-click the Group1 node and then click Properties.
9. In the Properties window, expand Instance Aggregates, and set
Render Location to GroupFooter.
10. Select the AmountCur field under the Data node.
11. In the Properties window, expand the Aggregation item, and set
Aggregate Function to Sum.
12. Optional: In the Model Editor, right-click the AutoDesign1 node,
and then click Preview to view the new style settings for the report.
Close the Preview window.

Step by Step: Filtering Report Data

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Queries node, and then locate the
VendTrans_W1 query.
4. Expand the VendTrans_W1 nodes.
5. Right-click the Ranges node and then click New Range. A default
range by using the AccountNum field is created for you by
Microsoft Dynamics AX.
6. Save the query.
7. In the Model Editor, select the VendTransDS node.
8. Right-click the node and select Refresh to reflect changes that were
made to the Microsoft Dynamics AX query.
9. Expand the Parameters node to display the list of report parameters.
10. Right-click the node and select Add > Parameter.
11. Type AccountParam as the name.
12. In the Properties window, set the Prompt String property to
Account.
13. Optional: In the Model Editor, right-click the AutoDesign1 node,
and then click Preview to view the new style settings for the report.
Close the Preview window.
14. Save the report.
15. In the Model Editor, expand the AutoDesign1 node.
16. Right-click the Filters node and select Add Filter.
17. Type AccountFilter as the name.
18. In the Properties window.
a. Set the Expression property to =Fields!AccountNum.Value.
b. Set the Operator property to Like.
c. Set the Value property to =Parameters!AccountParam.Value.

12-24
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

19. Optional: In the Model Editor, right-click the AutoDesign1 node,


and then click. Preview to view the new style settings for the report.
Close the Preview window.
20. Save the report.

Step by Step: Add a Dynamic Parameter

1. Open Microsoft Dynamics AX.


2. Create a new query.
3. Rename the query to VendTable_W1.
4. Expand the VendTable_W1 node.
5. Locate the CustTable table and drag it onto the Data Sources node
for the VendTable_W1 query.
6. Include the AccountNum field in your dataset view.
7. Save the query.
8. In the Model Editor, right-click the Datasets node, and then click
Add Dataset.
9. Type VendorDS as the name.
10. Select the node for the dataset.
11. In the Properties window, specify the following values:
a. Set the Data Source property to Dynamics AX.
b. Set the Data Source Type property to Query.
c. Set the Default Layout property to Table.
d. Set the Name property to VendorDS.
e. Set the Query property to Select * from VendTable_W1.

12. In the Model Editor, select the AutoDesign1 node.


13. Expand the Parameters node to display the list of report parameters.
14. Select the AccountParam node.
15. In the Properties window, click the button in the Values property.
16. Select the From Dataset option and set the following:
a. Set the Dataset property to VendorDS.
b. Set the Value Field property to AccountNum.
c. Set the Label Field property to AccountNum.

17. Optional: In the Model Editor, right-click the AutoDesign1 node,


and then click Preview to view the new style settings for the report.
18. Optional: Close the Preview window.
19. Save the report.

12-25
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Step by Step: Save and Deploy the Report

1. Right-click the SSRSDemo project in the Solution Explorer, and


select Rebuild.
2. Verify that you have no build errors.
3. Right-click the SSRSDemo project in the Solution Explorer, and
select Add SSRSDemo to AOT.
4. Verify that you can add to the AOT.
5. Right-click the SSRSDemo project in the Solution Explorer, and
select Deploy.
6. Verify that you can add to the AOT.

Step by Step: View the Report in Microsoft Dynamics AX

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, expand Menu Items node and select the Output node.
4. Right-click the Output node and then click New Menu Item.
5. Type VendTrans_W1 as the name.
6. Right-click the VendTrans_W1 and select Properties to set the
following:
a. Set the ObjectType property to SSRSReport.
b. Set the Object property to VendTrans_W1.
c. Set the Label Field property to AutoDesign1.

7. Save the Microsoft Dynamics AX Menu Item.


8. Right-click the VendTransList_WS1 menu item and select Open.
9. In the AOT, expand Menu Items node and select the Output node.
10. Right click the Output node, and then select Open New Window.
11. In the original AOT window, expand Menus.
12. Expand AccountsPayable > Reports > Transactions > Vendor.
13. Select the VendTrans_W1 Menu Item in the new AOT window that
was opened in step 4.
14. Drag the Menu Item into the Menu.
15. Save the Menu.

12-26
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Create a Precision Design Report from a Report Data


Provider
Basic views of Microsoft Dynamics AX data can most frequently be
accomplished by using queries to retrieve and structure the report dataset.
Reports that illustrate more complex data analysis will most likely include
custom business logic to produce the desired output.

This lesson discusses the concepts in Microsoft Dynamics AX 2012 that


developers can use to take advantage X++ code to construct the report dataset.

Model-View-Controller
Model-view-controller (MVC) is a pattern used to isolate business logic from the
user interface. By using MVC, the model represents the information (the data) of
the application and the business rules used to manipulate the data, the view
corresponds to elements of the user interface such as text, checkbox items, and so
on, and the controller manages details involving the communication between the
model and view. The controller handles user actions such as keystrokes and
mouse movements and pipes them into the model or view as required.

• Model: Responsible for retrieving data and for business logic, this
can included queries, data methods, or other classes that are designed
to retrieve data.
• View: Responsible for the User Interface, this can also be thought of
as the design for the report.
• Controller: Orchestrates the flow between Model and View

12-27
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following figure illustrates an example of how the model-view-controller can


be used in an advanced report.

FIGURE 12.9 MODEL-VIEW-CONTROLLER

The Creating Basic Reports from a Query topic reviewed a simple example of a
report where all of these elements existed. However, the design and the control of
the report were not modified. Instead the base classes for the SSRS reporting
framework in Microsoft Dynamics AX 2012 rendered the report dialog and
handled the logic that was required to run the report.

The steps used to create a report data provider that will deliver data to a report
follow.

Define the Report Dataset


Tables are used to store the report dataset generated by the X++ data access class.

BEST PRACTICE: A temporary table is typically used for report data


providers. It is recommended to use DBTemp tables when the data set being
returned contains more than 1,000 records.

The steps that are involved include review and define the data structure for the
report, create a temporary table to store the report dataset, and add table fields
required to generate the report.

12-28
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

To review and define the data structure for the report dataset, follow these steps.

1. Take an inventory of the data that is used to make up your report.


2. Identify the elements of the report that are derived from the report
business logic.
3. Identify calculated columns that are based on Microsoft Dynamics
AX data.
4. Determine the extended data types that are used to format the data.

The following figure is a sample of a completed report that will be built during
the following demonstrations.

FIGURE 12.10 REPORT DEMONSTRATION SAMPLE

TIP: Before you begin development for a new report visualize the layout of the
report using by Microsoft Office® Excel or draw the report design on a piece of
paper.

Demonstration: Create a Temporary Table


To create a temporary table, follow these steps.

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Tables node and then click New Table.
4. Right-click the table node, click Properties.
5. Locate the Name property and then type a AOTObjectsTmp.

12-29
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

6. Locate the TableType property and then select InMemory.


7. Save the table.

To add a field to the table, follow these steps:

1. Expand the Fields node.


2. Right-click the fields node of the table and then click New > String.
3. Create a new field and name it Node and set the ExtendedDataType
property to Description.
4. Add a label for the field node.
5. Repeat steps 1 through 4 for two additional fields, for the
ParentNode and the Property. Make sure that you select the extended
data type that you want for each field when you click New.
6. Save the table.

NOTE: Some reports can require more than one temporary table to store the
information.

Manage Report Parameters


A data contract is an abstract description of a set of fields that have a name and
data type for each field. The data contract exists outside any single
implementation so that services on different platforms can interoperate. As long
as the data passed between the services complies with the same contract, all the
services can process the data.

Report parameters that are used by custom business logic are managed by a data
contract class in X++. The steps that are involved include evaluate report
parameters, create a class in Microsoft Dynamics AX to use to manage the report
parameters, and define access methods for the contract data elements.

To understand the report parameters, follow these steps.

1. Take an inventory of the parameters used to manage the report.


2. Identify the elements of the parameter list that are used by the report
business logic.
3. Determine the extended data typed (EDTs) that are used to format
the data.

Demonstration: Create a Contract Class


To create a data contract class, follow these steps.

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Classes node, and then click New Class.
4. Right-click the new class that is created and then click Properties.

12-30
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

5. Locate the Name property and then type AOTObjectsContract.


6. Enter the following code sample into the Class Definition.

/// <summary>
/// Data Contract class for the AOT Objects SSRS report
/// </summary>
/// <remarks>
/// This is the Data Contract class for the AOT Objects
SSRS report
/// </remarks>
[DataContractAttribute]
public class AOTObjectsContract
{
Name parentNode;
Name aotProperty;
Name propertyVal;
boolean incNoValue;
}

Demonstration: Define Access Methods


Each report parameter must have a new method created that is decorated with the
DataMemberAttribute. To create methods to manage each, parameter, follow
these steps.

1. Locate the AOTObjectsContract node in the AOT


2. Open the class and add a method (by clicking the new icon) to
manage the AOT Property input parameter.
3. Enter the following code sample into the new AOTProperty
window.

/// <summary>
/// Gets or sets the value of the datacontract parameter
AOTProperty.
/// </summary>
/// <param name="_aotProperty">
/// The new value of the datacontract parameter
AOTProperty; required.
/// </param>
/// <returns>
/// The current value of datacontract parameter
AOTProperty
/// </returns>
[ DataMemberAttribute('AOTProperty'),
SysOperationLabelAttribute(literalstr("@SYS682'")) ]

public Name parmAOTProperty(Name _aotProperty = aotProperty


)
{
aotProperty = _aotProperty;
return aotProperty;
}

12-31
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

TIP: Notice the use of the literalstr() function and the "@" symbol when defining
a label to be used for the SysOperationLabelAttribute.

4. Create a new method in the class by clicking the new icon.


5. Enter the following code sample for the Include no value parameter.

/// <summary>
/// Gets or sets the value of the datacontract parameter
IncludeNoValue. /// </summary>
/// <param name="_incNoValue">
/// The new value of the datacontract parameter
IncludeNoValue; required. /// </param>
/// <returns>
/// The current value of datacontract parameter
IncludeNoValue
/// </returns>
[ DataMemberAttribute('IncludeNoValue'),
SysOperationLabelAttribute(literalstr("@SYS53334")) ]

public boolean parmIncNoValue(boolean _incNoValue =


incNoValue )
{
incNoValue = _incNoValue;
return incNoValue;
}

5. Create a new method in the class by clicking the new icon.


6. Enter the following code sample for the Parent node parameter.

/// <summary>
/// Gets or sets the value of the datacontract parameter
ParentNode.
/// </summary>
/// <param name="_parentNode">
/// The new value of the datacontract parameter
ParentNode; required.
/// </param>
/// <returns>
/// The current value of datacontract parameter ParentNode
/// </returns>
[ DataMemberAttribute('ParentNode'),
SysOperationLabelAttribute(literalstr("@SYS58556")) ]

public Name parmParentNode(Name _parentNode = parentNode )


{
parentNode = _parentNode;
return parentNode;
}

7. Create a new method in the class by clicking the new icon.


8. Enter the following code sample for the Property value parameter.

12-32
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

/// <summary>
/// Gets or sets the value of the datacontract parameter
PropertyValue.
/// </summary>
/// <param name="_propertyVal">
/// The new value of the datacontract parameter
PropertyValue; required.
/// </param>
/// <returns>
/// The current value of datacontract parameter
PropertyValue /// </returns>
[ DataMemberAttribute('PropertyValue'),
SysOperationLabelAttribute(literalstr("@SYS23425")) ]

public Name parmPropertyValue(Name _propertyVal =


propertyVal )
{
propertyVal = _propertyVal;
return propertyVal;
}

Report Data Provider Classes


The Report Data Provider (RDP) class is the standardized interface that
represents the data access point for the SSRS Reporting framework when X++
custom business logic is used to produce the dataset. The steps that are involved
include the following:

1. Create a new class to manage custom business logic.


2. Add the two entry points for the RDP class.
a. ProcessReport: This method is the entry point for processing
the report dataset.
b. getAOTObjectsTmp: This method is used by the framework to
retrieve the report dataset from the temporary table cache.

3. Add all the custom business logic used to generate the report dataset.

Demonstration: Create a Report Data Provider Class


To create a RDP class, follow these steps.

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT, right-click the Classes node, and then click New Class.
4. Right-click the new class that is created and then click Properties.
5. Locate the Name property and then type AOTObjectsDP.
6. Enter the following code sample into the Class Declaration.

12-33
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

/// <summary>
/// The Report data provider class that supports the AOT
Objects report. /// </summary>
/// <remarks>
/// This class provides the methods that are used by the
AOT Objects report
/// </remarks>
[
SRSReportParameterAttribute(classstr(AOTObjectsContract)) ]

public class AOTObjectsDP extends SRSReportDataProviderBase


{
// temporary data store
AOTObjectsTmp aotObjectsTmp;

// contract information
Name aotProperty;
Name propertyVal;
boolean incNoValue;
}

Demonstration: Implement the Report Data Provider Class


To implement a RDP class, follow these steps.

1. Locate the AOTObjectsDP node in the AOT Classes node.


2. Open the class and add custom business logic.

In this demonstration, you will import the code from an XPO on the Hyper-V
image. To import the file, follow these steps.

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. In the AOT click the Import icon or press CTRL+SHIFT+I.
4. In the Import dialog box, click Browse.
5. Browse to the AX2012_ENUS_DEVIV_12_01_LAB.xpo file.
6. Click Open.
7. On the Import dialog box, click OK.

Create an SSRS Report from an RDP Class


The following demonstration explains how to create a RDP bound dataset that
exposes AOT Object information in a Precision design report. The steps involved
include:

1. Create a new report in Visual Studio 2010.


2. Create a new Data set for the report tied to the new RDP class.

12-34
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

3. Create a basic view of the report data grouped on the AOT Object
Property information.
4. Convert the basic design into a Precision Design to achieve the
desired report layout.

Demonstration: Create a Report in Visual Studio 2010


To create a reporting project, follow these steps:

1. Open Microsoft Dynamics AX.


2. Open the Development Workspace.
3. Locate the project that you created in the Create a New Report in
Visual Studio demonstration in the AOT under Visual Studio
Projects > Dynamics AX Model Projects node.
4. Right-click the project, and then click Edit. This opens the report
project in Visual Studio.
5. In the Solution Explorer, click the Add button and select Report. An
empty report model named Report1 is created.
6. Right-click the newly created report and rename it to
AOTObjects_WS2.

To create a RDP based dataset, follow these steps:

1. Expand the AOTObjects_WS2 node if it is not already expanded.


2. Right-click the Datasets node, and then click Add Dataset.
3. Select the node for the dataset.
4. In the Properties window, specify the following values:
a. Data Source = Dynamics AX
b. Data Source Type = Report Data Provider
c. Default Layout = Table
d. Name = AOTObjectsDS
e. Query = Select * from AOTObjectsDP.AOTObjectsTmp

To create a precision design to match desired layout, follow these steps:

1. In the Model Editor, select the AOTObjectsDS node and drag it


onto the Designs node. An auto design named AutoDesign1 is
created for the report.
2. Right-click the AutoDesign1 node, and then click Preview.
3. Set the LayoutTemplate & TableStyleTemplate properties to
define the report visual settings.
4. Group the report dataset on the =Fields!Property.Value.
5. Right-click the AutoDesign1 node, and then click Create Precision
Design.
6. Right-click the PrecisionDesign1 node, then click Rename, and set
the name to Report.

12-35
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Now you have created a Precision Design that produces the same output as the
Auto Design automatically created to match the report dataset. Notice that this
layout is inconsistent with the desired look for the final report. The next step is to
use the Visual Studio tools to manipulate the design match the expected report
output.

Manage Report Execution by Using X++


In Microsoft Dynamics AX, you can execute and manage Visual Studio
Reporting Tools for Microsoft Dynamics AX reports by using X++. This lesson
shows how to print a report, set the print settings, prevent the display of print
setup, set the query range, and set a report parameter value.

Procedure: Print a Report from X++


In Microsoft Dynamics AX, you can print reports that are created by using Visual
Studio Reporting Tools for Microsoft Dynamics AX. This topic provides the
prerequisite steps for how to print a report, how to print from a menu item, and
how to print a report programmatically.

The SrsReportRunInterface class is an interface class that provides a set of APIs


to integrate running a report programmatically. This interface should be used
when you want to run a report from your form or code. Application developers
who want to take complete control over the rendering and running of a report
should use these APIs. Some examples of how or why this class can be used
include the following.

• Custom form that needs to run the report.


• Custom implementation of the Controller class of the SysOperation
framework.
• Batch printing–an example is to iterate over each customer record
and print the invoice for the customer.
• Change the report design that is being used at runtime.
• Change the culture or company that is being used at runtime.

Prerequisites to Print a Report

The prerequisites to print a report include the following.

• The report must be saved and deployed to the report server.


• There must be a way to access the report either programmatically or
from a menu item.

12-36
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Print a Report from a Menu Item

To print a report from a menu item, follow these steps.

1. Open a menu item that corresponds to the report that you want to
print.
2. Set the parameters that exist.
a. If you have queries, click the Select button and set the range.
b. Click the Destinations button to set the print destination fields.
You can print to a screen, printer, file, or email recipient.

3. Click OK to print the report.

Print a Report Programmatically

1. In the AOT, find the code element that you want to print the report
from.
2. Right-click the code element and then click Edit.
3. Use the following code samples to print a report directly or to open
the report dialog from code.

///Declare a variable
SrsReportRunInterface reportRun;

//Create an instance of the report


//Pass in the report that you want to run by using the
format
// '<ReportName>.<DesignName>'
reportRun = new SrsReportRunImpl('CustBaseData.Report');

// Run the report.


reportRun.runReport();

NOTE: This example runs a simple report that does not have a modified
contract.

TIP: In a more complex example where the report uses a data contract class,
additional code will be required. For an example of how to implement this, refer
to the EPSendDocument class makeDocument() method. This class is designed to
print a different report based on the record that is passed in.

12-37
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Procedure: Define the Print Settings


In Microsoft Dynamics AX, you can programmatically change the print settings
for a report. Print settings are implemented as the various properties on the
SRSPrintDestinationSettings object. You can create your own
SRSPrintDestinationSettings object and assign it to the SrsReportRunInterface
object or you can use the default print setting values and modify specific settings.

The following example uses the default settings and updates specific settings.
The report will be printed to file together with the file name set to
ReportExample.

Args args;
SrsReportRunInterface reportRun;
SrsReportDataContract contract;
SRSPrintDestinationSettings printSettings;

//Instantiate args and pass in the record that you have


args = new Args();
args.record(record);

//Create an instance of the contract for the desired


report.
//This example used the sales order quotation report.
contract = SalesQuotationController::newDataContract(args);

if (contract != null && contract.parmReportName())


{
//Create an instance of the report
reportRun = new
SrsReportRunImpl(contract.parmReportName());

//Set the contract parameter in the report instance


reportRun.parmReportContract(contract);

//Set the desired printer options


printSettings =
reportRun.parmReportContract().parmPrintSettings();

printSettings.printMediumType(SRSPrintMediumType::File);
printSettings.fileFormat(SRSReportFileFormat::PDF);
printSettings.fileName(file);
printSettings.overwriteFile(true);

// Run the report.


reportRun.runReport();
}

12-38
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Demonstration: Set the Query Range on a Report


This topic describes how to set a data source range value for a report query in
Microsoft Dynamics AX X++ code. A query is one of several ways to retrieve
data for a report that is created with Visual Studio reporting tools for Microsoft
Dynamics AX. In this example the Customer base data report will be run for a
specific customer.

1. Create a new controller class for the CustBaseData report that


extends SrsReportRunController. Use the following code sample to
guide you.

class CustBaseDataController extends SrsReportRunController


{
}

2. Next, create a new method called setRanges that set the report ranges
based on a query that is passed in. Use the following code sample to
guide you.

/// <summary>
/// Sets the report query ranges based on caller.
/// </summary>
/// <param name="_query">
/// Report query object.
/// </param>
public void setRanges(Query _query)
{
QueryBuildDataSource queryBuildDataSource;
str range;
custTable custTable;
custTable = this.parmArgs().record();

queryBuildDataSource = _query.dataSourceTable(tableNum(custTable));
range = queryValue(custTable.AccountNum);
//Adding the account number to the range value
SysQuery::findOrCreateRange(queryBuildDataSource, fieldNum(custTable,
AccountNum)).value(range);
}

3. Next, create a new method that overrides the preRunModifyContract


method. Use the following code sample to guide you.

protected void preRunModifyContract()


{
Query q;
QueryBuildRange qbr;
QueryBuildDataSource qbds;

12-39
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

AccountNum accountnum;
CustTable custTable;

custTable = args.record();
accountnum = custTable.AccountNum;

q = this.getFirstQuery();
qbds = q.dataSourceTable(tableNum(custTable));

if (AccountNum)
{
qbr = qbds.addRange(fieldNum(CustTable, AccountNum));
qbr.value(queryValue(AccountNum));
}
}

4. Next, override the prePromptModifyContract method. Use the


following code sample to guide you.

protected void prePromptModifyContract()


{

this.setRanges(this.parmReportContract().parmQueryContracts().lookup(this.get
FirstQueryContractKey()));
}

5. Next override the main method. Use the following code sample to
guide you.

public static void main(Args _args)


{
CustBaseDataController controller = new CustBaseDataController();
controller.parmReportName(ssrsReportStr(CustBaseData, Report));
controller.parmArgs(_args);
controller.startOperation();
}

NOTE: The CustBaseData report already has a controller class called


smmReportsController that is designed to handle several reports. You could
modify that class to contain the logic required.

12-40
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

At this point you have created a controller for the report. Now you must create
some logic to programmatically run the report and override the query. In this
example a job is created to call the report. Use the following code sample to
guide you.

static void ReportWithQueryOverride_SampleJob()


{
// Create variables for setting the range for the
query.
Args args;
CustTable tCustTable;
// Create an instance of a report.
CustBaseDataController cbdController;
cbdController = new CustBaseDataController();
tCustTable = CustTable::find('4001');
// Create an instance of args and set the record to
the selected customer
args = new args();
args.record(tCustTable);
// Set the full name of the report.
cbdController.parmReportName('CustBaseData.Report');
// Set args parameter in the class to the args
instance you created
cbdController.parmArgs(args);
// Run the report
cbdController.startOperation();
}

12-41
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

When you are finished creating the job, save, compile, and then run the job. The
report dialog will open and you should notice that the customer account 4001 is
already entered into the report query selection. If you click OK and run the report
the report should only print data for customer 4001.

FIGURE 12.11 CUSTBASEDATA.REPORT DIALOG BOX

Demonstration: Prevent Display a Report Dialog


In some instances a report can contain sensitive information that requires it be
printed to a secure printer. In another example, you may not want the dialog to
appear because we are assuming the parameters are already set and no user
interaction is required. This topic shows how to print from a secure printer.

To hide the report dialog for a report with the library report that contains
sensitive data, add the following code in the Code Editor. This example uses the
same job that was used in the "Set the Query Range on a Report" demonstration.

static void ReportWithQueryOverride_SampleJob()


{
// Create variables for setting the range for the
query.
Args args;
CustTable tCustTable;
// Create an instance of a report.
CustBaseDataController cbdController;
cbdController = new CustBaseDataController();
tCustTable = CustTable::find('4001');
// Create an instance of args and set the record to
the selected customer
args = new args();
args.record(tCustTable);
// Set the full name of the report.
cbdController.parmReportName('CustBaseData.Report');
// Set args parameter in the class to the args
instance you created
cbdController.parmArgs(args);

12-42
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

// Hide the report dialog box


cbdController.parmShowDialog(false);
// Run the report
cbdController.startOperation();
}

TIP: Other methods are available to hide various objects within the reporting
framework. For example, if you want to hide the report dialog box you can call
the showDialog() method and pass in false to set the value. For a complete list of
methods and their functionality, refer to the developer help on MSDN.

Business Logic in Report Data Methods


When you create reports in a reporting project in Microsoft Visual Studio, you
can use data methods to retrieve and manipulate the data that displays in your
reports.

Each reporting project contains a nested business logic project. When you create
a data method within the Model Editor, a template for the data method is copied
into a code file within the nested business logic project.

To view the code for a data method, follow these steps.

1. Right-click the data method in the Model Editor.


2. Click View Code, or double-click the code file in Solution Explorer.
The name of the data method and all other properties in the Model
Editor are automatically updated as you change the code.

When you build a business logic project, the code is compiled into a business
logic assembly (.BusinessLogic.dll). During deployment, business logic
assemblies are built and deployed to the report server and the security policy file
for the report server is updated so that .NET Business Connector has secure
access to the assemblies.

Structure of a Data Method


A data method contains the [DataMethod()] attribute, and only methods with this
attribute are recognized as data methods by the reporting tools. A data method,
such as a query, can be used as a source of data for a report dataset, and within
report expressions to perform data manipulations or calculations for fields that
display in the report. You must build the business logic project that contains your
data methods before you can use the data methods in your report.

The return value for a data method can be any .NET type. The default return
value is a System.String instance. To use a data method as a source of data for a
report dataset, it must return an IEnumerable<DataRow> or
System.Data.DataTable instance.

12-43
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

The following C# code shows an example of a data method called


RetrieveItemData that returns a System.Data.DataTable instance. This example
returns the InventTable.

[DataMethod(), AxSessionPermission(SecurityAction.Assert)]
public static IEnumerable<DataRow> RetrieveItemData()
{
// Retrieve records from the InventTable table.
return AxQuery.ExecuteQueryStream("select * from
InventTable");
}

TIP: To use the code sample provided, create a new SSRS report in Visual
Studio. Next, create a data method with the code sample provided, and then
create a new Data Set. Make sure that you set the Data Source Type property to
Business Logic, and then in the Query property select the RetrieveItemData
method that you created. Then you must design the report. When you are finished
you can preview the report.

Data methods can have parameters. A parameter for a data method can be any
.NET type. When a data method is used in a dataset, a report parameter is
automatically generated for each parameter in the data method. Report
parameters display below the Parameters node in the Model Editor.

The following scenarios are not supported in data methods.

• Overloading data methods is not supported. You can have only one
data method of a particular name inside a model. If you overload a
data method, you will receive an error stating that multiple data
methods with the specified name exist, and you will be unable to use
the data method within the report.
• Sharing data methods between reporting projects.
• Accessing Microsoft Dynamics AX queries by using data. Use a
report data provider class to access a Microsoft Dynamics AX query
in a report.

Data Methods in Report Expressions


The code for an expression is embedded within the report and it is not compiled
into the business logic assembly. Data methods can be used inside an expression.
In this case, the expression references the data method in the business logic
assembly. The Expression Editor displays a list of data methods that are available
to the report.

12-44
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

For business logic that is more complex, the recommendation is to write the
business logic inside a data method, and then call the data method from an
expression. By doing this you can take advantage of the capabilities of a full
programming language when writing your business logic. You can reference
types that are defined in other assemblies. For example, you can reference a
.NET Framework assembly, and then use an existing .NET type inside your
business logic. You can call other methods from inside a data method, as shown
in the previous code example. Additionally, you can access X++ code that is
defined in Microsoft Dynamics AX by using the managed programming interface
for reports that are defined in the [N:Microsoft.Dynamics.Framework.Reports]
namespace.

A data method can be used in multiple expressions inside a report, so that the
business logic that you define inside a data method is reusable within the report.
Expressions are not reusable inside a report. When you create an expression, it
cannot be called from another expression within the report.

Modifying and Deleting Data Methods


You can delete a data method in the Model Editor or directly in the code. When
you delete a data method in the Model Editor, the [DataMethod()] attribute is
removed from the data method. The rest of the code for the data method remains
in the code file. You can manually remove the code if it is no longer needed. All
other changes to a data method must be made directly in the code. For example,
you cannot change the name of a data method in the Model Editor or in the
Properties window. Instead, you must change the name of the data method
directly in the code. As soon as you make a change in the code, the Model Editor
and the properties that display in the Properties window are automatically
updated to reflect what is in the code.

NOTE: Model refactoring is currently not supported for data methods. The
model refactoring options are disabled on the context menu that displays for a
data method in the Model Editor.

You must be careful when you modify data methods. Data methods can be
referenced from data sets and expressions throughout a report. If you make a
breaking change to a data method in the code, you must manually update all
references to the data method wherever it is used in the report. The following
actions can result in a breaking change and cause errors in your report.

• Deleting a data method


• Removing the [DataMethod()] attribute from the data method
• Changing the name of a data method
• Changing the return value of a data method
• Adding or removing parameters in a data method
• Changing the type of a parameter in a data method

12-45
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Model validation is used to help identify broken references and invalid


expressions. When you build a project, error messages for broken references and
invalid expressions display in the Error List window.

NOTE: For more information about how to use business logic in report data
methods to access report data refer to MSDN
(http://go.microsoft.com/fwlink/?LinkId=238177).

Print Management
Print management gives users control of print settings for selected Microsoft
Dynamics AX reports. Print settings include the number of copies, the printer
destination, and the multilanguage text that can be included on the report. Some
additional print management features that you can use include the following.

• Modify the print settings of a report that is based on the contents of


the data being printed. For example, send sales orders greater than
1000 U.S. dollars (USD) to Printer A and sales orders greater than
10,000 USD to Printer B.
• Specify print settings at various levels of the application. For
example, module-level print settings apply to all documents in a
given module, whereas customer-level print settings only apply to
specific customers and transaction-level print settings apply only to
specific transactions.
• Override or add to the settings from higher levels in the application.
For example, module-level settings can be overridden at the
customer or transaction level if not desirable. Moreover, additional
settings can be added to the existing settings for similar reasons.

Why Use Print Management?

You should consider by using the print management framework when the
following conditions are true:

• Your new or existing feature has reports that require specialized print
management.
• You are adding a new document type to the application that
resembles the document types currently supported by print
management.

12-46
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Architectural Overview
The print management subsystem is divided into three main parts: metadata,
setup, and retrieval. Metadata defines a series of classes that you can use to
describe how print management should work. You can describe how many levels
of defaulting are possible, what tables and columns should be involved in
queries, and other pertinent information. Setup defines a generic user experience
that can be opened throughout the application that is based on certain inputs. You
would call this in areas where print management information must be managed
by end-users. Retrieval defines an Application Programming Interface (API)
which you can use to retrieve and use the print management information set up
by the user.

FIGURE 12.12 PRINT MANAGEMENT FLOW

Defining Metadata
Print management metadata is defined completely in code and originates from
four main classes or concepts: PrintMgmtDocType (documents), PrintMgmtNode
(nodes), PrintMgmtHierarchy (hierarchies), and PrintMgmtReportFormat
(formats).

A document is the document or report to which specific print management


settings apply. Documents are the core of print management because all settings
are defined for documents of a particular type. When users set up this
information, it is used when that document is printed. The documents in the print
management system are defined in the PrintMgmtDocType class and are always
related to specific nodes in print management.

A node is a particular level of defaulting in a hierarchy. For example, in the


Accounts Receivable module print management settings can exist at the Sales
Order Transaction level, the Customer level and the Module level. Each of these
levels is considered a node and each node in print management must derive from
the abstract PrintMgmtNode class. While nodes define the level at which print
management settings can exist, they have no order by themselves which is where
hierarchies help.

12-47
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

A hierarchy is a group of related nodes. By using the previous example, the


nodes mentioned would all be a part of the Account Receivable hierarchy. The
ordering of nodes in a hierarchy defines the ordering of defaulting for print
management settings. Each hierarchy in print management must derive from the
abstract PrintMgmtHierarchy class.

A report format is the design or layout of the report. It is possible for each
report to have multiple designs.

The following diagram shows how documents, nodes and hierarchies all relate to
one another to define the print management metadata for a hypothetical Accounts
Receivable hierarchy.

FIGURE 12.13 PRINT MANAGEMENT DOCUMENT-NODE-HIERARCHY


SAMPLE

The Accounts Receivable node represents the module level settings and all
documents present in the module apply at this level. The Customer node
represents settings that apply to specific customers and all documents present in
the module apply. At the lowest level the nodes represent transaction level
settings and only certain documents apply to each specific transaction.

Sometimes to integrate with print management, you might have to modify


existing nodes or hierarchies to meet the needs of the documents that you want to
print. You might also be required to create new nodes, hierarchies or documents
to accomplish the same goal. The following sections outline the steps that are
required to accomplish these common integration tasks.

12-48
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Adding a New Document


Whether you are adding a new document to new or existing nodes the same steps
are required. To better understand the classes or methods mentioned in the steps,
refer to the XML documentation that is included in the source code.

1. Update the PrintMgmtDocumentType enumeration Add the


document type to the enumeration immediately following the last
element. Create and assign a label for the document type that follows
the pattern for existing document types.
2. Update the PrintMgmtDocType class to handle the new document
type.
o Modify the getQueryTableId method. Add the table ID of the
table that will be used when enabling users to enter conditional
queries for the document type. This is generally the "Jour"
(journal) table that is used when you post, but could be any table
that applies.
o Modify the getQueryRangeFields method. Add the default fields
that should be used when entering conditional queries for the
new document type. The order in which they are added will also
be the order in which they appear in the Query window.
Consider wrapping this logic with a call to
isConfigurationkeyEnabled, passing the appropriate
configuration key, to guarantee that the fields only appear when
the functionality is enabled in the system.
o Modify the getDefaultReportFormat method. Add a case for the
document type and return the name of the base SSRS report.
Remember to use the ssrsReportStr() intrinsic function to make
sure that the report name is validated at compile time.

3. Update the PrintMgmtDocTypeTest class to handle the new


document type.
o Modify the testGetDisplayName method. Add a test to guarantee
that the document type appears with the correct text.
o Modify the testGetQueryTableId method. Add a test to guarantee
that the document type has the correct query table id.
o Modify the testGetQueryRangeFields method. Add a test to
guarantee that the document type has the correct default query
fields.

4. Update all PrintMgmtNode derivatives to which the document type


applies.
o Modify the getDocumentTypes method. Add the document type
to the list of supported document types.
o Wrap this logic with a call to isConfigurationkeyEnabled,
passing the appropriate configuration key, to guarantee that the
documents only appear when the functionality is enabled in the
system.

12-49
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Update necessary PrintMgmtNode derivatives’ tests for the


document type.
o Modify the testNodeDocumentTypes method.
o Create or update this method to handle the document type.

6. Update necessary PrintMgmtHierarchy derivatives to which the


document type applies.
o Modify the getParentImplementation method. This method is
used to define the structure of the nodes in a hierarchy. In some
cases, the document type affects the logic to determine the parent
and in other cases it does not. For example, Sales order invoice
documents use the InvoiceAccount field of the SalesTable to
find their parent node, whereas Sales order confirmation
documents use the CustAccount field of the SalesTable. This is
all determined based on the document type.
o If your new document type requires special behavior such as
this, update the method.

7. Update necessary PrintMgmtHierarchy derivatives’ tests for the


document type.
o This step is only necessary if you were required to update the
getParentImplementation method.
o Update the testGetParent method. Add tests for the new
document type following the existing pattern.
o Update the testGetParentSkippingLevels method. Add tests for
the new document type following the existing pattern.

8. Update the PrintMgmtReportFormat table’s populate method.


o Add a call to AddAx(PrintMgmtDocumentType _type,
PrintMgmtReportFormatCountryRegionId _countryRegionId =
#NoCountryRegionId) for the new document type and optionally
the country or region with which the report is specifically
associated.

Create or Modify Nodes


New nodes are necessary when a new level of defaulting is necessary for the
documents you want to print. If you want a better understanding of the classes or
methods mentioned in the steps, see the XML documentation that is included in
the source code.

1. Make sure a node does not already exist that meets your needs. Look
at the classes that derive from the PrintMgmtNode class to determine
this information. Even if an existing node defines document types
that you are not interested in using, you can still use the node. If the
existing nodes do not meet your needs, continue to step 2.
2. Create a new enumeration value in the PrintMgmtNodeType
enumeration.

12-50
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

o Add the node type to the enumeration immediately following the


last element.
o The name of the element should match the table to which the
print management settings will be related. If the print
management settings do not relate to a table, choose a name
following the existing patterns present.
o Create and assign a label for the node type. If the node
references a table, use the table name label from the table it
references. If not, follow the existing patterns present.

3. Create a new class that derives from the PrintMgmtNode class. Make
sure that you reference the existing PrintMgmtNode derivatives for
examples. The class should be prefixed with 'PrintMgmtNode_' and
should follow the naming pattern of the existing nodes. If the node is
tied to a particular table, the table name should follow the prefix such
as PrintMgmtNode_CustTable, for example.

o Implement the getDisplayCaptionImplementation method.

o This method controls the caption that will appear for the
instance of the node in the Print Management window.
o Return the appropriate label for Module level settings.
Refer to existing examples in PrintMgmtNode_Purch or
PrintMgmtNode_Sales.
o Return strfmt("@SYS108943", _tableBuffer.caption())
for account level settings. Refer to the existing example
in PrintMgmtNode_CustTable or
PrintMgmtNode_VendTable.
o Return strfmt("@SYS108944", _tableBuffer.caption())
for transaction level settings. Refer to existing examples
in PrintMgmtNode_SalesTable or
PrintMgmtNode_PurchTable.
o Customize as necessary for unique situations.

o Implement the getDocumentTypes method.

o Return a list of document types the node supports.


o The document types should be wrapped in configuration
key checks so that they are only loaded if the
configuration key is enabled. For example,
isConfigurationkeyEnabled(configurationkeynum(Logist
icsBasic)).

12-51
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

o Implement the getIconImageResNum method.

o This method controls the icon that will appear for the
instance of the node in the Print Management window.
o Return the resource ID used to display the icon
representing this node. The resAppl macro contains the
resource ID definitions for icon images. This method
should return one of those resource IDs. If additional
resource IDs are used, they should also be added to the
build method of the ImageListAppl_PrintMgmt class.
o Module level nodes should use the same icon that is used
for the module, account level nodes should use
#ImagePrintManagementAccount, and transaction level
nodes should use #ImagePrintManagementTrans.

o Implement the getNodeType method.

o Return the appropriate PrintMgmtNodeType


enumeration value.

o Implement the getReferenceTableId method.

o Return the table to which the node will be related. For


example, if a node is tied to specific customers that you
would return tablenum(CustTable).
o If the node is not related to a specific table, return the
value of 0. Module level settings are examples of nodes
that are not tied to specific tables.

4. Modify the PrintMgmtNode::construct method. Add a case statement


to construct your new node.
5. Create appropriate unit tests.

o The name of the test class should be identical to the node


followed by the postfix 'Test'.
o About the contents of the tests, follow the example of existing
node tests that resemble your node type. For example, module-
level, account level, transaction level nodes, or other.
o To add data, follow the existing examples in the
PrintMgmtTestSuite class.
o Add a macro that defines the ID of the table in the
classDeclaration.
o Add a new method that retrieves the table following the
existing pattern. For example, getSalesTable,
getCustInvoiceTable, and so on.

12-52
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

o Create the data in the setUpReferenceData method and


make to trackInsertedRows for the table that you add. As
soon as you have finished, add the new test to the
PrintMgmtTestSuite by adding the appropriate entry in
the new method.

6. If the node relates to a table, update the appropriate relations and


cascading deletes.

o Create a relation on the PrintMgmtDocInstance table to the table


that you are referencing. For example, PrintMgmtDocInstance
> SalesTable.
o Add a cascading delete action on the table that you are
referencing to the PrintMgmtDocInstance table. For example,
SalesTable > PrintMgmtDocInstance.

7. Add the node to the appropriate hierarchy. See the Create or Modify
Hierarchies section for the steps that are required to perform this
action.
8. Add the node to the PrintMgmt shared project.

Create or Modify Hierarchies


Sometimes existing hierarchies can be modified to include or rearrange existing
nodes, and sometimes completely new hierarchies are necessary. Both scenarios
have similar steps that are described later in this training material. To better
understand the classes or methods mentioned in the steps, refer to the XML
documentation that is included in the source code.

1. Create a new enumeration value in the PrintMgmtHierarchyType


enumeration.
o Add the hierarchy type to the enumeration immediately
following the last element.
o Create and assign a label for the hierarchy type following the
existing patterns.
2. Create a new class that derives from the PrintMgmtHierarchy class.
Make sure that you reference the existing PrintMgmtHierarchy
derivatives for examples.

o The class should be prefixed with 'PrintMgmtHierarchy_' and


should follow the naming pattern of the existing hierarchies.
o Implement the getNodesImplementation method.
o Return the list of nodes the hierarchy supports.

12-53
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

o Implement the getParentImplementation method.

o This method is used to define the structure of the nodes


in a hierarchy. It provides an instance of a node and a
document type as input parameters and will be required
to return an instance of the PrintMgmtNodeInstance
class. This PrintMgmtNodeInstance class brings together
a PrintMgmtNode instance with the actual table buffer
record it relates with.
o If the parent node does not reference a table, only the
PrintMgmtNodeType enumeration value of the parent is
required to be returned through the parmNodeDefinition
property of the PrintMgmtNodeInstance class.
o If the parent node does reference a table, the specific
record of the parent node should be returned also. This is
returned through the parmReferencedTable property of
the PrintMgmtNodeInstance class. If the record cannot
be found, a null value should be returned.
o Refer to existing implementations for a better
understanding of what is necessary for this method.

3. Modify the PrintMgmtHierarchy::construct method. Add a case


statement to construct your new hierarchy.
4. Create appropriate unit tests.

o The name of the test class should be identical to the hierarchy


followed by the postfix 'Test'.
o About the contents of the tests, follow the example of existing
hierarchy tests.
o To add data, follow the existing examples in the
PrintMgmtTestSuite class.

oAdd a macro that defines the ID of the table in the


classDeclaration.
o Add a new method that retrieves the table following the
existing pattern. For example, getSalesTable or
getCustInvoiceTable.
o Create the data in the setUpReferenceData method and
make sure that you trackInsertedRows for the table that
you add. As soon as you are finished, add the new test to
the PrintMgmtTestSuite by adding the appropriate entry
in the new method.
5. If you are modifying an existing hierarchy, make sure that you
update the appropriate hierarchy tests. Modify the
testIsValidNodeType method. Update the count because the number
of nodes added will have changed.
6. Add the hierarchy to the PrintMgmt shared project.

12-54
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

A custom format is a modification of an existing SSRS report as managed by


Print Management that the user can select by using Print Management setup. The
basic steps for developing this include the following.

• Copy an existing SSRS report (the .RDL file) with a new name.
• Modify the new SSRS report layout by moving, deleting, or adding
report elements.
• Add a call in table PrintMgmtReport format’s populate method to the
addOther() method.
• Call the table method PrintMgmtReportFormat::populate to update
the table with the new report format so it is available to the user to
select in Print Management setup.

Summary
This chapter introduced the features of SSRS and demonstrated how to create a
simple report by using a query and an auto-design. Additionally, the chapter
showed how you can use the report data provider framework to deliver business
logic to a report in more complex business scenarios.

The MVC is a pattern used to separate the data (Model) from the user interface
(View) and the business logic (Controller) is used to communicate between the
Model and the View. You can implement this framework by decorating your
classes together with attributes such as the DataContractAttribute and the
DataMemberAttribute.

You can use the SRSReportRun framework to control how the printing and
output of a report will be handled. You can also use X++ to set parameter values
when running a report.

In addition to the query framework and the report data provider framework, you
can use business logic in Visual Studio to retrieve the data for a report. To use
business logic in a report you must create a data method that includes the
DataMethhod() attribute. A data method can also be used within report
expressions to perform data manipulations or calculations for fields that display
in the report.

Developers can implement print management for selected Microsoft Dynamics


AX reports. This gives users control of print settings. A developer must create or
modify the document, node, and hierarchy for each report that you want to enable
print management for.

12-55
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Test Your Knowledge


Test your knowledge with the following questions.

1. Put the following steps in the correct order to create a new SSRS report from
a Microsoft Dynamics AX query:

Step:

_____: Apply style templates.

_____: Create a new report model in Visual Studio.

_____: Add field data to the query.

_____: Create a new query in the AOT.

_____: Create a report design.

_____: Create a report dataset.

2. Which of the following is not a feature of reporting in Microsoft Dynamics


AX 2012?
( ) Deployment by using PowerShell scripts.
( ) Support to submit a report to the batch processor.
( ) MorphX report designer in the Application Object Tree.
( ) Support to use labels in a report design to provide support for multiple
languages for the same report.

3. What must you create to store the data when a report data provider class is
used for the data set?
( ) A persisted table in SQL
( ) An in-memory temporary table in the AOT
( ) A persisted table in the AOT
( ) A temporary table in SQL

4. Which of the following options is not a class that is used for implementing
print management on a new report?
( ) PrintMgmtDocType
( ) PrintMgmtHierarchy
( ) PrintMgmtReport
( ) PrintMgmtNode

12-56
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

5. Categorize the reporting dataset options with the data sources:

Categories (Data Source):

1. Dynamics AX
2. SQL
3. Dynamics AX OLAP

_____ Item 1: MDX Query

_____ Item 2: Queries in the AOT

_____ Item 3: TSQL

_____ Item 4: Report Data Provider class

_____ Item 5: Stored Procedure

_____ Item 6: Data methods

6. Which of the following is not a step in the process for saving and deploying a
report project?
( ) Rebuild the solution
( ) Save the report to the AOT
( ) Import the report into the AOT
( ) Deploy the report

12-57
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this
chapter

1.

2.

3.

12-58
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Chapter 12: Reporting

Solutions
Test Your Knowledge
1. Put the following steps in the correct order to create a new SSRS report from
a Microsoft Dynamics AX query:

Step:

6 : Apply style templates.

3 : Create a new report model in Visual Studio.

2 : Add field data to the query.

1 : Create a new query in the AOT.

5 : Create a report design.

4 : Create a report dataset.

2. Which of the following is not a feature of reporting in Microsoft Dynamics


AX 2012?
( ) Deployment by using PowerShell scripts.
( ) Support to submit a report to the batch processor.
(•) MorphX report designer in the Application Object Tree.
( ) Support to use labels in a report design to provide support for multiple
languages for the same report.

3. What must you create to store the data when a report data provider class is
used for the data set?
( ) A persisted table in SQL
(•) An in-memory temporary table in the AOT
( ) A persisted table in the AOT
( ) A temporary table in SQL

4. Which of the following options is not a class that is used for implementing
print management on a new report?
( ) PrintMgmtDocType
( ) PrintMgmtHierarchy
(•) PrintMgmtReport
( ) PrintMgmtNode

12-59
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics® AX 2012

5. Categorize the reporting dataset options with the data sources:

Categories (Data Source):

1. Dynamics AX
2. SQL
3. Dynamics AX OLAP

3 Item 1: MDX Query

1 Item 2: Queries in the AOT

2 Item 3: TSQL

1 Item 4: Report Data Provider class

2 Item 5: Stored Procedure

1 Item 6: Data methods

6. Which of the following is not a step in the process for saving and deploying a
report project?
( ) Rebuild the solution
( ) Save the report to the AOT
(•) Import the report into the AOT
( ) Deploy the report

12-60
Microsoft Official Training Materials for Microsoft Dynamics®
Your use of this content is subject to your current services agreement

You might also like