Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Microsoft Dynamics NAV 2009 Programming Cookbook
Microsoft Dynamics NAV 2009 Programming Cookbook

Microsoft Dynamics NAV 2009 Programming Cookbook: Build better business applications with NAV

eBook
€8.99 €39.99
Paperback
€48.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Microsoft Dynamics NAV 2009 Programming Cookbook

Chapter 1. Strings, Dates, and Other Data Types

In this chapter, we will cover:

  • Retrieving the system date and time

  • Retrieving the work date

  • Determining the day, month, and year from a given date

  • Converting a value to a formatted string

  • Creating an array

  • Creating an Option variable

  • Converting a string to another data type

  • Manipulating string contents

  • Using date formulas to calculate dates

Introduction


Simple data types are building blocks for everything you will program. C/AL contains the same data types that you will find in most other programming languages: Booleans, integers, decimals, dates, and strings. There are of course more than just these five, but majority of your programming will revolve around using these types of variables.

As a developer, your job is to build business logic that will manipulate the data that is input by users. This ensures that the data stored in tables is meaningful. Most of this data will be of one of the following data types. NAV is, after all, a financial system at heart. At its most basic level, it cares about three things: "How much money?" (decimal), "What was it for?" (string), and "When did it happen?" (date).

The recipes you will find in this section may not be the most interesting, but are valuable. The functionality described here is used throughout the system. As such, each example in this chapter is accompanied by actual code from base NAV objects in order to better illustrate how they can be used.

Retrieving the system date and time


There are many instances when it is necessary to obtain the current date and time from the user's system. This recipe will show you how to get that information.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Write the following code in the OnRun trigger of the codeunit:

    MESSAGE('Todays Date: %1\Current Time: %2', TODAY, TIME);
    
  3. Save and close the codeunit.

  4. When you run the codeunit you should see a window similar to the following screenshot:

How it works...

The TODAY keyword returns the date from the system clock on the client computer. In Windows, the current system time is usually located at the bottom-right corner of the task bar. The same holds true for the system time which is returned by the TIME keyword.

There's more...

The actual date and time returned depends on which version of the NAV client you are using. In the RoleTailored client, the date and time come from the NAV server. In the Classic client, the date and time come directly from the client computer and users will be able to manipulate the system clock to their advantage if they need to. An example could be a time clock application where a user can clock in, change the system time to eight hours later, clock out, and change it back to the original time.

You can also retrieve the system date and time, all at once, using the CURRENTDATETIME function. The date and time can be extracted using the DT2DATE and DT2TIME functions respectively.

Note

For a complete list of date functions, search the C/SIDE Reference Guide under the Help menu for date and time functions.

Logging changes and events

The ChangeLog is a base NAV module that allows you to track changes to specific fields in tables. The following code can be found in Codeunit 423, Change Log Management, in the InsertLogEntry() method.

ChangeLogEntry.INIT;
system timeevents, loggingChangeLogEntry."Date and Time" := CURRENTDATETIME;
ChangeLogEntry.Time := DT2TIME(ChangeLogEntry."Date and Time");

Here, instead of using the WORKDATE function, we use the CURRENTDATETIME function and then extract the time using the DT2TIME function. The system designers could have just done the following setup:

ChangeLogEntry.Date := TODAY;
ChangeLogEntry.Time := TIME;

The advantage of using CURRENTDATETIME over TODAY and TIME is minimal. CURRENTDATETIME makes one request to the system, while the second method makes two. It is possible that another operation or thread on the client machine could take over between retrieving the date and time from the computer, however, this is very unlikely. The operations could also take place right before and after midnight, generating some very strange data. The requirements for your modification will determine which method is suits best, but generally CURRENTDATETIME is the correct method to use.

See also

  • Retrieving the work date

  • Determining the day, month, and year from a date

  • Converting a value to a formatted string

  • Writing your own rollback routine

Retrieving the work date


The work date is an essential part of the NAV system. This recipe will show you how to determine what that date is, as well as when and where you should use it.

Getting ready

  1. Click on Tools | Workdate from the NAV client.

  2. Set the work date to 01/01/2010.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Write the following code in the OnRun trigger of the codeunit:

    MESSAGE('Work Date: %1\Todays Date: %2\Current Time: %3', WORKDATE, TODAY, TIME);
    
  3. Save and close the codeunit.

  4. When you run the codeunit you should see a window like the following screenshot:

How it works...

The work date is a date internal to the NAV system. This date is returned using the WORKDATE keyword. It can be changed at any time by going to Tools | Work Date.

There's more...

It is important to understand the difference between the NAV work date and the computer system date. They should be used in specific circumstances. When performing general work in the system, you should almost always use the WORKDATE keyword. In cases where you need to log information and the exact date or time when an action occurred, you should use TODAY and TIME or CURRENTDATETIME.

Populating date fields when a document is created

The following code can be found in table 36, Sales Header, in the InitRecord() method:

IF "Document Type" IN ["Document Type"::Order,"Document Type"::Invoice,"Document Type"::Quote] THEN BEGIN
methodInitRecord()"Shipment Date" := WORKDATE;
"Order Date" := WORKDATE;
END;
IF "Document Type" = "Document Type"::"Return Order" THEN
"Order Date" := WORKDATE;
IF NOT ("Document Type" IN ["Document Type"::"Blanket Order","Document Type"::Quote]) AND ("Posting Date" = 0D) THEN
"Posting Date" := WORKDATE;
IF SalesSetup."Default Posting Date" = SalesSetup."Default Posting Date"::"No Date" THEN
"Posting Date" := 0D;
"Document Date" := WORKDATE;

It is common to create and call an InitRecord() method from a table's OnInsert trigger especially for document-style tables. Unlike with the InitValue property for fields in a table, fields here are filled in based on conditional logic. More importantly, validation can be performed to ensure data integrity.

Looking at this snippet of code, we can see that every date is filled in using the WORKDATE keyword, and not using TODAY. This is so that a user can easily create records that are pre-dated or post-dated.

See also

  • Retrieving the system date and time

  • Determining the day, month, and year from a date

  • Converting a value to a formatted string

  • Checking for conditions using an IF statement

  • Using a CASE statement to test multiple conditions

Determining the day, month, and year from a given date


Sometimes it is necessary to retrieve only a part of a date. NAV has built-in functions to do just that. We will show you how to use it in this recipe.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add the following global variables:

    Name

    Type

    Day

    Integer

    Month

    Integer

    Year

    Integer

  3. Write the following code in the OnRun trigger of the codeunit:

    Day := Date2DMY(TODAY, 1);
    Month := Date2DMY(TODAY, 2);
    Year := Date2DMY(TODAY, 3);
    MESSAGE('Day: %1\Month: %2\Year: %3', Day, Month, Year);
    
  4. Save and close the codeunit.

  5. When you run the codeunit you should see a window like the following screenshot:

How it works...

The Date2DMY function is a basic feature of NAV. The first parameter is a date variable. This parameter can be retrieved from the system using TODAY or WORKDATE, a hard-coded date such as 01312010D, or a field from a table such as Sales Header or Order Date.

The second parameter is an integer that tells the function which part of the date to return. This number can be 1, 2, or 3 and corresponds to the day, month, and year (DMY) respectively.

There's more...

NAV has a similar function called Date2DWY. It will return the week of the year instead of the month if 2 is passed as the second parameter.

Determining depreciation

Codeunit 5616, Depreciation Calculation, contains functions to calculate depreciation based on start and end dates. In order to correctly calculate these values, you must know some details such as the number of days between two dates and whether or not any of those days is a leap day. It is with these types of operations that date functions like DATE2DMY are extremely useful. Have a look at the function DeprDays365 in this codeunit.

StartingYear := DATE2DMY(StartingDate,3);
EndingYear := DATE2DMY(EndingDate,3);
LeapDays := 0;
IF (DATE2DMY(StartingDate,1) = 29) AND (DATE2DMY(StartingDate,2) = 2) AND (DATE2DMY(EndingDate,1) = 29) AND (DATE2DMY(EndingDate,2) = 2) THEN LeapDays := -1;
ActualYear := StartingYear;
WHILE ActualYear <= EndingYear DO BEGIN LeapDate := (DMY2DATE(28,2,ActualYear) + 1);
IF DATE2DMY(LeapDate,1) = 29 THEN BEGIN
IF (LeapDate >= StartingDate) AND (LeapDate <= EndingDate) THEN
LeapDays := LeapDays + 1;
END;
ActualYear := ActualYear + 1;
END;
EXIT((EndingDate - StartingDate) + 1 - LeapDays);

See also

  • Retrieving the system date and time

  • Retrieving the work date

  • Converting a value to a formatted string

  • Repeating code using a loop

  • Checking for conditions using an IF statement

Converting a value to a formatted string


There will be many occasions when you will need to display information in a certain way or display multiple variable types on a single line. The FORMAT function will help you change almost any data type into a string that can be manipulated in any way you see fit.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add the following global variables:

    Name

    Type

    Length

    FormattedDate

    Text

    30

  3. Add the following code to the OnRun trigger:

    FormattedDate := FORMAT(TODAY, 0, '<Month Text> <Day,2>, <Year4>');
    MESSAGE('Today is %1', FormattedDate);
    
  4. Save and close the codeunit.

  5. When you run the codeunit you should see a window similar to the following :

How it works...

The FORMAT function takes one to three parameters. The first parameter is required and can be of almost any type: date, time, integer, decimal, and so on. This parameter is returned as a string.

The second parameter is the length of the string to be returned. A default zero means that the entire string will be returned. A positive number tells the function to return a string of exactly that length, and a negative number returns a string no larger than that length.

There are two options for the third and final parameter. One is a number, representing a predefined format you want to use for the string and the other is a literal string. In the example, we used the actual format string. The text contained in brackets (< >) will be parsed and replaced with the data in the first parameter.

There's more...

There are many predefined formats for dates. The examples listed in the following table are taken from the C/SIDE Reference Guide in the Help menu of the NAV client. Search for "Format Property" to find more information.

Date

Format

Example

<Closing><Day,2>-<Month,2>-<Year>

0

05-04-03

<Closing><Day,2>-<Month,2>-<Year>

1

05-04-03

<Day,2><Month,2><Year><Closing>D

2

050403D

<Closing><Year>-<Month,2>-<Day,2>

3

03-04-05

<Closing><Day>. <Month Text> <Year4>

4

5. April 2003

<Closing><Day,2><Month,2><Year>

5

050403

<Closing><Year><Month,2><Day,2>

6

030405

<Day,2><Filler Character, >. <Month Text,3> <Year4>

7

5. Apr 2003

XML format

9

2003-04-05

Creating filters using other variable types

You will often need to create filters on dates or other simple data types. Usually these filters are not just for a single value. For example, a date filter for all values between January 1st, 2010 and January 31st, 2010 would look like 010110..013110. Because ".." is a string, and you cannot concatenate it with two date variables. Instead, you will have to convert those dates into strings and then place the filters together.

Take the CreateAccountingDateFilter function from codeunit 358, DateFilter-Calc. It creates date filters based on accounting periods for the exact scenario we are describing.

AccountingPeriod.RESET;
IF FiscalYear THEN
AccountingPeriod.SETRANGE("New Fiscal Year",TRUE);
AccountingPeriod."Starting Date" := Date;
AccountingPeriod.FIND('=<>');
IF AccountingPeriod."Starting Date" > Date THEN
NextStep := NextStep - 1;
IF NextStep <> 0 THEN
IF AccountingPeriod.NEXT(NextStep) <> NextStep THEN BEGIN
IF NextStep < 0 THEN
Filter := '..' + FORMAT( AccountingPeriod."Starting Date" - 1)
ELSE
Filter := FORMAT(AccountingPeriod."Starting Date") + '..' + FORMAT(12319999D);
Name := '...';
EXIT;
END;
StartDate := AccountingPeriod."Starting Date";
IF FiscalYear THEN
Name := STRSUBSTNO(Text000,FORMAT(DATE2DMY(StartDate,3)))
ELSE
Name := AccountingPeriod.Name;
IF AccountingPeriod.NEXT <> 0 THEN
Filter := FORMAT(StartDate) + '..' + FORMAT(AccountingPeriod."Starting Date" - 1)
ELSE BEGIN
Filter := FORMAT(StartDate) + '..' + FORMAT(12319999D);
Name := Name + '...';
END;

See also

  • Retrieving the system date and time

  • Retrieving the work date

  • Determining the day, month, and year from a given date

  • Converting a string to another data type

  • Checking for conditions using an IF statement

  • Using advanced filtering

  • Retrieving data using FIND

Creating an array


Creating multiple variables to store related information can be time consuming. It leads to more code and hence, more work. Using an array to store related and similar type of information can speed up development and lead to much more manageable code. This recipe will show you how to create and access array elements.

How to do it...

  1. Create a new codeunit in Object Designer.

  2. Add the following global variables:

    Name

    Type

    i

    Integer

    IntArray

    Integer

  3. With the cursor on that variable, click on View | Properties ( Shift +F4).

  4. Set the following property:

    Property

    Value

    Dimensions

    10

  5. In the OnRun trigger add the following code:

    FOR i := 1 TO ARRAYLEN(IntArray) DO BEGIN
    IntArray[i] := i;
    MESSAGE('IntArray[%1] = %2', i, IntArray[i]);
    END;
    
  6. When you run the codeunit you will see ten windows, one after the other, similar to the following screenshot:

How it works...

An array is a single variable that holds multiple values. The values are accessed using an integer index. The index is passed within square brackets ([]).

There's more...

NAV provides several functions to work with arrays. ARRAYLEN returns the number of dimensions of the array. COPYARRAY will copy all of the values from one array into a new array variable. For a complete list of functions, search the C/SIDE Reference Guide under the Help menu for "Array Functions".

Creating an address using the format address codeunit

Open codeunit 365, Format Address. Notice the first function, FormatAddr, has a parameter which is an array. This is the basic function that all of the address formats use. It is rather long, so we will discuss only a few parts of it here.

This first section determines how the address should be presented based on the country of the user. Variables are initialized depending on which line of the address should certain information appear. The variables will be the indexes of our array.

CASE Country."Contact Address Format" OF
arrayaddress creating, Format Address usedCountry."Contact Address Format"::First:
BEGIN
NameLineNo := 2;
Name2LineNo := 3;
ContLineNo := 1;
AddrLineNo := 4;
Addr2LineNo := 5;
PostCodeCityLineNo := 6;
CountyLineNo := 7;
CountryLineNo := 8;
END;

Then we will fill in the array values in the following manner:

AddrArray[NameLineNo] := Name;
AddrArray[Name2LineNo] := Name2;
AddrArray[AddrLineNo] := Addr;
AddrArray[Addr2LineNo] := Addr2;

Scroll down and take a look at all the other functions. You'll see that they all take in an array as the first parameter. It is always a text array of length 90 with 8 dimensions. These are the functions you will call when you want to format an address. To use this codeunit correctly, you will need to create an empty array with the specifications listed before and pass it to the correct function. Your array will be populated with the appropriately formatted address data.

See also

  • Manipulating string contents

  • Using a CASE statement to test multiple conditions

Creating an Option variable


If you need to force the user to select a value from a pre-defined list then an Option is the way to go. This recipe explains how to create an Option variable and access each of its values.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add the following global variables:

    Name

    Type

    ColorOption

    Option

  3. Set the following property on the variable:

    Property

    Value

    OptionString

    None,Red,Green,Blue

  4. Add the following code to the OnRun trigger of your codeunit:

    ColorOption := ColorOption::Red;
    CASE ColorOption OF
    ColorOption::None: MESSAGE('No Color Selected');
    ColorOption::Red: MESSAGE('Red');
    ColorOption::Green: MESSAGE('Green');
    ColorOption::Blue: MESSAGE('Blue');
    END;
    
  5. When you run the codeunit you should see a window similar to the following screenshot:

How it works...

An Option is a field or variable that stores one value from a selectable list. In a form, this list will appear as a drop-down from which the user can select a value. The list of options is stored as a comma-separated string in the OptionString property.

These values are accessed using the variable_name::option_name syntax. The first line of the example assigns one of the possible values (Red) to the variable. Then we use a CASE statement to determine which of the values was selected.

There's more...

You can also access possible options in other ways. In a database, an Option is stored as an integer. Each Option corresponds to a specific number, starting with the number 1. In this case None=1, Red=2, Green=3, and Blue=4. You could write this code to perform the safe actions:

ColorOption := ColorOption::"1";
option variableworkingCASE ColorOption OF
ColorOption::None: MESSAGE('No Color Selected');
ColorOption::Red: MESSAGE('Red');
ColorOption::Green: MESSAGE('Green');
ColorOption::Blue: MESSAGE('Blue');
END;

To reduce your development time, you can also use a shorthand notation to access the Option values. Again, the following code is exactly the same as that above:

ColorOption := ColorOption::R;
CASE ColorOption OF
ColorOption::None: MESSAGE('No Color Selected');
ColorOption::Red: MESSAGE('Red');
ColorOption::Green: MESSAGE('Green');
ColorOption::Blue: MESSAGE('Blue');
END;

When you close, save, and reopen the codeunit, the Option values will automatically be filled in for you. That is, both of these examples will look exactly like the first example once it has been saved and reopened. It is always best to write the code exactly as you want it to appear.

Using Options in documents

Option fields are prevalent throughout the NAV system, but most commonly on documents. In NAV, many documents share the same table. For example, sales quotes, orders, invoices, and return orders are all based on the Sales Header table. In order to distinguish between the types, there is an Option field called Document Type. Design table 36, Sales Header, to see the available options for this field.

Now, design codeunit 80, Sales-Post. Examine the OnRun trigger. Early in the function, you will see the following code:

CASE "Document Type" OF
"Document Type"::Order:
Receive := FALSE;
"Document Type"::Invoice:
BEGIN
Ship := TRUE;
Invoice := TRUE;
Receive := FALSE;
END;
"Document Type"::"Return Order":
Ship := FALSE;
"Document Type"::"Credit Memo":
BEGIN
Ship := FALSE;
Invoice := TRUE;
Receive := TRUE;
END;
END;

This is a common example of how Options are used in NAV. You can scroll through the codeunit to find more examples.

See also

  • Using a CASE statement to test multiple conditions

Converting a string to another data type


Sometimes a string representation isn't enough. In order to perform certain actions, you need your data to be in a certain format. This recipe will show you how to change that data into a format that you can use.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add the following global variables:

    Name

    Type

    Length

    DateText

    Text

    30

    DateValue

    Date

     
  3. Write the following code in the OnRun trigger:

    DateText := '01/01/2010';
    EVALUATE(DateValue, DateText);
    MESSAGE('Date: %1', DateValue);
    
  4. Save and close the codeunit.

  5. When you run the codeunit you should see a window similar to the following screenshot:

How it works...

The EVALUATE() function takes in two parameters. The first is a variable of the type that you want your value to be converted into. This could be date, time, boolean, integer, or any other simple data type. This parameter is passed by reference, meaning that the result of the function is stored in that variable. There is no need to do a manual assign using the := syntax.

The second parameter is the string which you need to convert. This text is usually stored in a field or variable, but can also be hard coded.

For a list of all of the functions related to text variables, search for "Text Data Type" in the C/SIDE Reference Guide under the Help menu.

There's more...

EVALUATE() returns a boolean value when executed. If the conversion is successful, it returns TRUE or 1; otherwise, it returns FALSE or 0. If the function returns FALSE, an error will be generated. If you wish to display the standard system error, you can leave the code as it is, but if you want to handle the error yourself, you must make the following changes:

DateText := '01/01/2010';
IF NOT EVALUATE(DateValue, DateText) THEN
ERROR('Custom Error Message');
MESSAGE('Date: %1', DateValue);

Incrementing a number series

Number series are used throughout the NAV system. Every document has a unique identifier that is usually retrieved from the No. Series table. This table keeps a track of the last number used so that it knows what the next number should be.

However, this identifier is not just a number. A purchase order, for example, might have an identifier of PO123456, which means that it is actually a string. As you can't add a number to a string, you will have to figure out what the number part is, convert it to an actual number, and then increment it. This code from the IncrementNoText() function in codeunit 396, NoSeriesManagement, does exactly that. As this code calls several other functions, it may be beneficial for you to look through the entire codeunit.

GetIntegerPos(No,StartPos,EndPos);
stringnumber series, incrementingEVALUATE(DecimalNo,COPYSTR(No,StartPos,EndPos - StartPos + 1));
NewNo := FORMAT(DecimalNo + IncrementByNo,0,1);
ReplaceNoText(No,NewNo,0,StartPos,EndPos);

See also

  • Converting a value to a formatted string

  • Checking for conditions using an IF statement

  • Passing parameters by reference

Manipulating string contents


It can be very useful to parse a string and retrieve certain values. This recipe will show you how to examine the contents of a string and manipulate that data.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add a function called RemoveNonNumeric(). It should return a text variable named NewString.

  3. The function should take in the following parameter:

    Name

    Type

    Length

    String

    Text

    30

  4. Add the following global variable:

    Name

    Type

    I

    Integer

  5. Add the following global variables:

    Name

    Type

    Length

    OldPhoneNumber

    Text

    30

    NewPhoneNumber

    Text

    30

  6. Add the following code to the RemoveNonNumeric() function:

    FOR i := 1 TO STRLEN(String) DO BEGIN
    IF String[i] IN ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] THEN
    NewString := NewString + FORMAT(String[i]);
    END;
    
  7. Add the following code to the OnRun trigger:

    OldPhoneNumber := '(404) 555-1234';
    NewPhoneNumber := RemoveNonNumeric(OldPhoneNumber);
    MESSAGE('Old Phone Number: %1\New Phone Number: %2', OldPhoneNumber, NewPhoneNumber);
    
  8. When you run the codeunit you will see a window similar to the following screenshot:

How it works...

A string is actually an array of characters. The same array syntax will be used to access the individual characters of the string.

We start with a FOR loop that begins at the first character, with index 1, and goes until we reach the end of our string. This is determined using the STRLEN() function which stands for STRing LENgth. As the first index is 1 the last index will be N, or the number of characters in the string.

Next, we access the character at that index using square brackets. If the character is a number, meaning we want to keep it because it is numeric, we add it to our resulting string.

Note

We can only add strings to other strings so we must convert this character using the FORMAT() function. If the character is not a number, we ignore it.

There's more...

NAV comes with plenty of built-in string manipulation functions to remove characters, return substrings, find characters within string, and many more. A search in the C/SIDE Reference Guide from the NAV client help menu for string functions will give you a complete list.

Parsing strings has several uses in NAV. Some easy-to-implement examples include checking/converting a phone number to a proper format based on country code, properly capitalizing names, and removing illegal characters.

Linking records with strings

Using the Object Designer run table 6508, Value Entry Relation. You should see a column named Source RowId that contains some strange looking text. A careful examination reveals that these are not as strange as they appear. It is simply a string containing six values, each separated by a semicolon and enclosed within quotes. For example: "123";"0";"123456";""; "0";"10000".

In a typical installation involving shipments and receipts, the value of the current inventory is adjusted every time an item comes in or goes out of stock. This amount is stored in the Value Entry table. In order to know which document created which value entry, a subsidiary table was created: Value Entry Relation. In this basic scenario, the first field refers to the table that the value entry came from. The most common are: 113 for shipments and 123 for receipts. The third value stores the document number and the sixth contains the line number. Take a look at the function DecomposeRowID() in codeunit 6500, Item Tracking Management.

FOR ArrayIndex := 1 TO 6 DO
Item Tracking ManagementStrArray[ArrayIndex] := '';
Len := STRLEN(IDtext);
Pos := 1;
ArrayIndex := 1;
WHILE NOT (Pos > Len) DO BEGIN
Char := COPYSTR(IDtext,Pos,1);
IF (Char = '"') THEN BEGIN
Write := FALSE;
Count += 1;
END ELSE BEGIN
IF Count = 0 THEN
Write := TRUE
ELSE BEGIN
IF Count MOD 2 = 1 THEN BEGIN
Next := (Char = ';');
Count -= 1;
END ELSE
IF NoWriteSinceLastNext AND (Char = ';') THEN BEGIN
Count -= 2;
Next := TRUE;
END;
Count /= 2;
WHILE Count > 0 DO BEGIN
StrArray[ArrayIndex] += '"';
Count -= 1;
END;
Write := NOT Next;
END;
NoWriteSinceLastNext := Next;
END;
IF Next THEN BEGIN
ArrayIndex += 1;
Next := FALSE;
END;
IF Write THEN
StrArray[ArrayIndex] += Char;
Pos += 1;
END;

This is an amazing example of how you can manipulate strings to your advantage. The code is fairly complex and may take some time to understand, but it can give you a basis to write your own code. You should be able to see the code that looks for semicolons, or field separators, as well as the code that finds quotes, or field identifiers. The code separates out those fields and stores them in a string array for later use.

See also

  • Converting a value to a formatted string

  • Creating an array

  • Repeating code using a loop

  • Checking for conditions using an IF statement

Using date formulas to calculate dates


Date formulas allow you to determine a new date based on a reference date. This recipe will show you how to use the built-in NAV function called CALCDATE to calculate them.

How to do it...

  1. Create a new codeunit from Object Designer.

  2. Add the following global variable:

    Name

    Type

    CalculatedDate

    Date

  3. In the OnRun trigger write the following code:

    CalculatedDate := CALCDATE('CM+1D', 01012010D);
    MESSAGE('Calculated Date: %1', CalculatedDate);
    
  4. Save and close the codeunit.

  5. When you run the codeunit you should see a window like the following screenshot:

How it works...

The CALCDATE() function takes in two parameters, a calculation formula and a starting date. The calculation formula is a string that tells the function how to calculate the new date. The second parameter tells the function which date it should start with. A new date is returned by this function, so the value must be assigned to a variable using standard := syntax.

There's more...

The following units can be used in the calculation formula:

Unit

Description

D

Day

WD

Weekday

W

Week

M

Month

Q

Quarter

Y

Year

These units may be different depending on what language your version of NAV is running under.

You have two options for the number to place before the unit. This can either be a standard number ranging between 1 and 9, or the letter C, which stands for Current. These units can be added and subtracted to determine a new date based on any starting date.

Calculation formulas can become very complex. The best way to fully understand them is to write your own formulas to see the results. Start out with basic formulas like 1M+2W-1D and move on to more complex ones like — CY+2Q-1W.

Calculating reminder terms using date formulas

NAV has the ability to issue a reminder whenever a customer goes past due on their balance. These reminders are issued at specific times based on date formulas entered by the user during setup.

Look at the MakeReminder() method in codeunit 392, Reminder-Make. This function has a large amount of code so only a small section is shown here. The date formula is stored in a field called Grace Period and is used to determine if those many days have passed since the due date of the document.

IF (CALCDATE(ReminderLevel."Grace Period",ReminderDueDate) <
ReminderHeaderReq."Document Date") AND ((LineLevel <= ReminderTerms."Max. No. of Reminders") OR (ReminderTerms."Max. No. of Reminders" = 0))
THEN BEGIN

See also

  • Retrieving the system date and time

  • Retrieving the work date

  • Determining the day, month, and year from a given date

  • Checking for conditions using an IF statement

Left arrow icon Right arrow icon

Key benefits

  • Write NAV programs to do everything from finding data in a table to integration with an instant messenger client
  • Develop your own .NET code to perform tasks that NAV cannot handle on its own
  • Work with SQL Server to create better integration between NAV and other systems
  • Learn to use the new features of the NAV 2009 Role Tailored Client
  • Easy-to-read recipes with detailed explanations and images
  • Maximize your learning with short tutorials that tell you exactly what you need to know without all of the fluff

Description

Microsoft Dynamics NAV 2009 is a business management solution that helps simplify and streamline highly specialized business processes such as finance, manufacturing, customer relationship management, supply chains, analytics, and electronic commerce for small and medium-sized enterprises. ERP systems like NAV thus become the center of a company's day-to-day operations. When you learn to program in an environment like this it opens up doors to many other exciting areas like .NET programming, SQL Server, and Web Services.Microsoft Dynamics NAV 2009 Programming Cookbook will take you through interesting topics that span a wide range of areas such as integrating the NAV system with other software applications like Microsoft Office, creating reports to present information from multiple areas of the system, and so on. You will not only learn the basics of NAV programming, but you will also be exposed to the technologies that surround the NAV system such as .NET programming, SQL Server, and Web Services.The first half of the cookbook will help programmers coming to NAV for the first time by walking them through the building blocks of writing code and creating objects like tables, forms, and reports. The second half focuses on using the technologies surrounding NAV to build better solutions. You will learn how to write .NET code that works with the NAV system and how to integrate the system with other software applications like Microsoft Office or even custom programs. You will also discover some of the features of the Role Tailored Client including creating Pages and custom add-ins.

Who is this book for?

If you are a junior / entry-level NAV developer then the first half of the book is designed primarily for you. You may or may not have any experience programming. It focuses on the basics of NAV programming. It would be best if you have gone through a brief introduction to the NAV client. If you are a mid-level NAV developer, you will find the second half more useful. These chapters explain how to think outside of the NAV box when building solutions. There are also recipes here and there that senior developers will find useful.

What you will learn

  • Learn basic programming concepts like variables, loops, and conditionals
  • Build tables and perform complex actions on their data
  • Design different types of forms to display and interact with business data
  • Create reports to present information from multiple areas of the system
  • Write C# .NET code that will work inside the NAV client
  • Learn advanced security techniques including integrating your code with Active Directory
  • Build solutions that work with the entire Microsoft Office suite of products
  • Write code to interact with the Windows file system and registry
  • Create objects to send your data to other applications and read data from other databases
  • Learn to work with SQL Server and execute basic queries against the NAV database
  • Design solutions for the Role Tailored Client

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 20, 2010
Length: 356 pages
Edition : 1st
Language : English
ISBN-13 : 9781849680950
Vendor :
Microsoft

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 20, 2010
Length: 356 pages
Edition : 1st
Language : English
ISBN-13 : 9781849680950
Vendor :
Microsoft

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 134.97
Microsoft Dynamics NAV 2009 Programming Cookbook
€48.99
Microsoft Dynamics NAV 2009: Professional Reporting
€48.99
Microsoft Dynamics NAV 2009 Application Design
€36.99
Total 134.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Strings, Dates, and Other Data Types Chevron down icon Chevron up icon
General Development Chevron down icon Chevron up icon
Working with Tables and Records Chevron down icon Chevron up icon
Designing Forms Chevron down icon Chevron up icon
Report Design Chevron down icon Chevron up icon
Diagnosing Code Problems Chevron down icon Chevron up icon
Roles and Security Chevron down icon Chevron up icon
Leveraging Microsoft Office Chevron down icon Chevron up icon
OS Interaction Chevron down icon Chevron up icon
Integration Chevron down icon Chevron up icon
Working with SQL Server Chevron down icon Chevron up icon
The RoleTailored Client Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(7 Ratings)
5 star 57.1%
4 star 42.9%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Ricardo Nunes Jan 30, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are a person who wants to start programming in Microsoft Dynamics Nav or want to extend the knowledge then you should buy this book. Nice book with plenty of examples that really helps.
Amazon Verified review Amazon
David Roys Nov 27, 2010
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is packed full of useful stuff. I've been doing NAV programming for quite a while now and I know a thing or two, but I found plenty in the book that I could use straight away in my day to day work. The book is divided into 112 recipes that go from the noddy stuff (like basic building blocks of programming NAV) to pretty advanced topics that require creating .NET controls and automations using Visual Studio. It seems like there is no problem too big for Matt. If NAV can't do it, he rolls up his sleeves, cranks up Visual Studio and finds a solution. That was the thing I loved about this book. Matt has a great attitude to working with NAV and shows what can be done if you're prepared to think outside the box.I loved this book. There's something in it for everyone. The recipes are fun-sized morsels of knowledge and you can dib in and out when you need to solve a particular problem, or you can start from the beginning and work your way through if you just want to learn as much as you can.There are plenty of sources of knowledge on NAV now including various books, blogs, and online articles; if you're a completely stingy git, you may prefer to spend your time trawling through forums and trying lots of things rather than shelling out for Matt's book. I know I'd rather save my time and go straight to one reference where I can get an easy step-by-step guide on how to get past my current problem and then move on.If you program NAV, you need this book. Well done Matt!
Amazon Verified review Amazon
Joseph Dewey Dec 29, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an awesome book. It's so helpful, and I reference it probably once per week. There isn't a ton written about NAV, so if you're serious about NAV, you'll probably want to buy every book available on the current version of NAV. But, I guarantee that you'll reference this book more often than all of the others.This book is written in a "programming cookbook" format, where the book is divided up into about 50 different tasks (recipes) you'd want to do with NAV. And, it's often right on the mark for what you'd actually want to do with NAV.The examples are perfect, too, because you can actually do each one of them with only a few minutes of setup, yet they're substantial enough that they're good to reference even when you're familiar with the subject.And, even though I mainly use this for a reference book now, when I first got it, I went through the first few chapters and did example by example. That was a great way to get familiar with NAV programming very quickly.Pros:+Extremely useful book, I reference it at least once a week+Almost all examples also work for NAV 2013+Very easy to implement examples, which is impressive, since NAV's IDE is kind of clunky.+Long lasting. You'll keep this on your shelf even after you've thrown out your other NAV booksCons:-There isn't a NAV Programming Cookbook 2 yet
Amazon Verified review Amazon
Krupesh Feb 06, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Microsoft Dynamics NAV 2009 Programming Cookbook is an excellent book where each recipe has been explained in an easy to understand language. This book is highly recommended for those NAV programmers who are looking for tips and tricks for handling real life scenarios. Each code snippet has been explained in detail in simple, easy to understand language and why a particular line of code has been written. This book is a good accompaniment with other basic programming books and the reader needs to have at least basic NAV programming knowledge. After learning basic NAV programming syntax this book will explain how the concepts can be applied.This book is a must-have for all NAV programmers who, at times, face problems and do not know how to go about resolving them. They can then apply the tricks and tricks learnt in this book to resolve real life situations.The book starts with some simple code such as displaying system date and time and gets in to more complex scenarios such as session killer, field level security, interaction with OS, integration, etc. Use of .Net with NAV has been well documented and explained. Matt has demonstrated that sky's the limit for NAV with application of C# code to specific situations.
Amazon Verified review Amazon
Philippe Torres Feb 06, 2011
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Hello,This book is available for all Dynamics NAV 2009 Developper (from the newbies to the senior developper). This book is very helpfull and well organized with tips and tricks. Its a very good choice. I'll recommend it with the purchase of Dynamics NAV 2009 AdminsitrationBonjour,Ce livre est aussi bien utilisable par les néophytes que par les développeurs seniors. Très bien organisé, avec des trucs et astuces, je ne peux que recommander celui-ci. Si vous êtes aussi administrateur, n'oubliez pas Dynamics NAV 2009 Administration.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.