Development Tips

Creating a Test Codeunit and Test Function

Let’s creates the test function, which tests the Purch-Calc.Discount functionality, to this test codeunit.

To create the test codeunit and test function

  • In the development environment, on the Tools menu, choose Object Designer.
  • In Object Designer, choose Codeunit, and then choose New.
  • On the View menu, choose Properties.
  • In the Properties window, in the Subtype field, select Test to specify that this is a test codeunit.
  • On the View menu, choose C/AL Globals.
  • In the C/AL Globals window, on the Functions tab, enter CalculateVendorDiscount. This is the name of the test function.

TestCU-1

Note
By default, functions that you add to test codeunits have the FunctionType property set to Test.
  • On the Functions tab, choose Locals.
  • In the C/AL Locals window, on the Variables tab, enter the following variables, which you will use in the CalculateVendorDiscount test function.

TestCU-2

Important

Be sure to create these variables on the Variables tab, not on the Parameters tab. If you create them on the Parameters tab, then you get an error when you compile that says the test method signature is invalid

  • In the C/AL Locals window, on the Text Constants tab, in the Name field, enter VendorDiscountError. In the ConstValue field, enter Vendor Discount Error – Line Amount: %1, Discount: %2, Discount Amount: %3.

TestCU-3

  • Close the C/AL Locals window and the C/AL Globals window.
  • In the C/AL Editor, in the CalculateVendorDiscount function, enter the following code.

TestCU-4

You can copy above code from below:

Discount := RANDOM(99) + 1; // Set Discount > 0, <= 100

// Find purchase line.

PurchaseLine.SETFILTER(“Line Amount”, ‘>0’);

PurchaseLine.SETFILTER(“Allow Invoice Disc.”, ‘=%1’, TRUE);

IF NOT (PurchaseLine.FINDFIRST) THEN

ERROR(‘No Purchase Line found for the Calculate Vendor Discount test’);

// Create vendor discount.

WITH PurchaseLine DO BEGIN

IF NOT (VendorDiscount.GET(“Buy-from Vendor No.”, “Currency Code”, “Line Amount”)) THEN BEGIN

VendorDiscount.INIT;

VendorDiscount.Code := “Buy-from Vendor No.”;

VendorDiscount.VALIDATE(“Currency Code”,”Currency Code”);

VendorDiscount.VALIDATE(“Minimum Amount”,”Line Amount”);

VendorDiscount.INSERT(TRUE);

END;

END;

VendorDiscount.VALIDATE(“Discount %”, Discount);

VendorDiscount.MODIFY(TRUE);

// Run codeunit “Purch.-Calc.Discount” for calculating discount.

PurchCalcDisc.RUN(PurchaseLine);

PurchaseLine.GET(PurchaseLine.”Document Type”,PurchaseLine.”Document No.”,PurchaseLine.”Line No.”);

// Validate purchase discount amount

WITH PurchaseLine DO BEGIN

IF NOT (ROUND(“Line Amount” * Discount / 100) = “Inv. Discount Amount”) THEN

ERROR(VendorDiscountError, “Line Amount”, Discount, “Inv. Discount Amount” );

END;

The code in this test function prepares the test data by setting a random discount amount, getting a record from the Purchase Line table that satisfies two filters, and creating a record in the Vendor Invoice Disc. table with the random discount amount.

Next, it runs the Purch-Calc.Discount codeunit, which contains the code that is being tested. Finally, it validates the results of running the Purch-Calc.Discount codeunit and raises an error if the results are not as expected.

Note

This test code does not guarantee that the state of the database after you run the test is the same as the state of the database before you run the test.

  • On the File menu, choose Save.
  • In the Save As window, in the ID field, enter ID. In the Name field, enter TestVendorDiscount. Verify that the Compiled check box is selected, and then choose the OK button.

Now create additional test functions in the TestVendorDiscount test codeunit to test other aspects of vendor discounts.

These test functions should include negative tests, which validate that the code being tested works as intended under failing conditions.

For more details See below posts:

Creating a Test Runner Codeunit
Adding a Test to a Test Runner Codeunit

Development Tips

Creating File Attachment to Mail for Report

We generally get requirements from clients to send report output as attachment to the mail.

In Microsoft Dynamics Navision 2015 this feature is available at most of the places, but we can design for other earlier versions too.

Long-time back I was having this requirement from one of my client, those days I scanned lots of website and tried lots of method. This one I found compact and easy to use. Their after whenever I get similar requirements I prefer using this.

Today I wish to share the same with others, as I have used it in my several implementations and found it working perfect and tested with several clients.

Let’s see this, it could help someone getting his work done in easy way and can save lots of time from hit and try with several methods.

First step, I will create a function which will help us generating the file on Service tier and down load to local temporary folder, so that we can easily access and attach to our mail.

Let’s give it a meaningful name like: DownloadToClientFileName

I will define two parameters for this Function as below:

Var Name DataType Subtype Length
No ServerFileName Text 250
No ToFile Text 250

I will define Return Value of Function as: Text of Length 250

I will define Local Variables for Function as below:

Name DataType Subtype Length
ClientFileName Text 250
objScript Automation ‘Microsoft Script Control 1.0’.ScriptControl
CR Text 1

Now we will write Code for the Function as below:

ClientFileName := ToFile;

IF NOT DOWNLOAD(ServerFileName, ”, ‘<TEMP>’,”, ClientFileName) THEN

EXIT(”);

IF CREATE(objScript,TRUE,TRUE) THEN

BEGIN

CR := ‘ ‘; CR[1] := 13;

objScript.Language := ‘VBScript’;

objScript.AddCode(

‘function RenameTempFile(fromFile, toFile)’+CR+

‘set fso = createobject(“Scripting.FileSystemObject”)’+CR+

‘set x = createobject(“Scriptlet.TypeLib”)’+CR+

‘path = fso.getparentfoldername(fromFile)’+CR+

‘toPath = path+”\”+left(x.GUID,38)’+CR+

‘fso.CreateFolder toPath’+CR+

‘fso.MoveFile fromFile, toPath+”\”+toFile’+CR+

‘RenameTempFile = toPath’+CR+

‘end function’);

ClientFileName := objScript.Eval(‘RenameTempFile(“‘+ClientFileName+'”,”‘+ToFile+'”)’);

ClientFileName := ClientFileName+’\’+ToFile;

END;

EXIT(ClientFileName);

Second Step, I will write code to call this function to attach the file to Mail and send using SMTP as below:

//SMTP is an Variable of Codeunit SMTP Mail

SMTP.CreateMessage(SenderName,SenderAddress,Recipient,Subject,Body,TRUE);

//SenderName,SenderAddress,Recipent is an email addresses

SMTP.AppendBody(Body);

CLEAR(MailReport);

//MailReport is Variable for Report of which output we want to use as attachment.

//Name & ToFile is Text type variable of Length 250

Name := STRSUBSTNO(‘Estimate No. %1.pdf’, SalesHeader.”No.”);

//Creating File Name

ToFile := Name;

FileName := TEMPORARYPATH + ToFile;

//We are using temporarypath OS Variable to get the path for file

MailReport.SetMailFilters(SalesHeader);

MailReport.SAVEASPDF(FileName);

ToFile := DownloadToClientFileName(FileName, ToFile);

SMTP.AddAttachment(ToFile);

FILE.ERASE(FileName);

SMTP.Send;

Now you can create a template function and use where ever require.

Report

Creating Custom Word Layout for Document Reports in Navision 2015

Open the MS Office Word.

File -> New and type Invoice in search and press enter to list available Invoice Templates.

Document Reports -1

In my example I am using [Sales Invoice (Blue Border Design)]

Document Reports -2

Select Create to download the template and create a document for you.

Your new document created from this template will look as below:

Document Reports -3

Prepare the Layout by removing extralines as we will be using repeating lines for Lines.

Save your Template.

I have made a copy of Report 206 – Sales – Invoice on new ID say (50005 as Sales – Invoice Word).

This report dosen’t have Word Layout. We will be creating one Customize Layout form above saved Invoice above. [Sales Invoice (Blue Border Design)]

Open Report Layout as shown in below Screen:

Document Reports -4

Document Reports -5

Slect the Report and choose Custom Layout as shown in above screen.

Document Reports -6

In Custom Report Layout Window Click on New.

From window Insert Build-in Layout for Report Select Insert Window Layout and click OK button.

Document Reports -7

From Custom Report Layout window Select Import Layout, Select your word file prepared above and Respond Open to Import.

Document Reports -8

Then, press Edit Layout and prepare layout on Developer tab, find XML Mapping Pane and find your document in Custom XML Part.

Now, you can find all fields from Dataset.

Document Reports -9

Please see below links to complete your report:

Adding image fields

Add fields from a report dataset to a word report layout

Creating my first word list report in Navision 2015

How to specify the default built in report layout

Create a word report layout for a report

Once you are done with your field assignment close the word layout.

Document Reports -10

Select Yes to import changes to the report.

Document Reports -11

Select Run Report to view the output of your report.

Now you are done with your Custom Report Layout.

Please see sections which will be more helpful to complete your task:

Reports

Report

Creating Word Mail Merge Report in Microsoft Dynamics Navision 2015

Today we will see Mail Merge feature in Word Report.

I would suggest to please go through my earlier post for creating simple List Report for better understanding as some parts I will be skipping in this post assuming you have already learned from my previous post.

Here is the Quick Link : [ Creating My First List Report in Navision 2015 ]

Lets assume ever month we require to send a Reminder Letter to our Customers for Due Payments.

Now we can design such report at customer ease.

Lets Start with creating a new Report.

Add the Data Items and desired columns as one shown below.

Add appropriate filters on Data Items, I have added [ Open = Yes, Document Type = Invoice, Remaining Amount > 0, Due Date <> ‘ ‘] you select your own as desired.

Set the Report Properties as shown in below screen.

Define Global Variables as shown in below screen.

We have Included WordMergeDataItem as Cust. Ledger Entry. This will set the table to loop for records.

Each records will be considered as New Page for the Report.

Word Mail Merge -1

In this report we are using Include Caption which will include caption for each required columns from one defined in respective table.

Add this property for each required column.

Add the code to the Data Item Trigger to fetch Customer Information for each record.

Word Mail Merge -2

Insert New Blank Word Layout to the Report.

Word Mail Merge -3

Export the Layout Template and Save.

Word Mail Merge -4

Open saved Layout Template in Word.

In below screen each component is shown, refer to earlier post Creating List Word Report, Link provided above for better understanding.

In this report Label is included as we have set property for each column to include caption.

Word Mail Merge -5

Design the sample Letter as one shown below.

I have highlighted all the Dataset Columns/Fields in yellow.

How to add fields please refer to earlier post Creating Word List Report, Link provided above.

Word Mail Merge -6

Now Save the Template and Import into the Report.

Word Mail Merge -7

Here is the out put from the report as below.

Each page will contain data as per in Customer Ledger Entry Due Payment Records.

Word Mail Merge -8

We are done !!!

You can use formatting feature of Word to add more better look to your Report as desired.

Stay tuned for more in upcoming posts.

Don’t forget to follow the Blog Site for future posts.

Report

Creating my first Word List Report in Navision 2015

Today we will learn creating Word List Report in Navision 2015.

Prepare the Dataset for Report as below, to keep it simple I am creating List report for Item Inventory.

I am adding one additional field for Company Logo from Company information.

Make sure you add calcfields code for Picture from Company information.

—————————————————

I have added below piece of code in [ Item – OnPreDataItem() ]

CompInf.GET;
CompInf.CALCFIELDS(Picture);

—————————————————

Word Report Design 1

Place the cursor on Blank Line and open Report Properties and add DefaultLayout Property.

Word Report Design 2

Next we will Add a Blank Word Layout to the Report, Step as below.

Word Report Design 3

Confirm the action by responding OK to the Dialog Box.

Word Report Design 4

Now Export this Blank Template

Word Report Design 5

and save as docx file (MS Word File)

Word Report Design 6

Open the Exported Template in Word.

Click on DEVELOPER Menu.

From Ribbon click on XML Mapping Pane.

Word Report Design 7

You will now be able to see XML Mapping Pan which contains your Dataset for the Report.

Click to the Dropdown List and select entry containing your Report Name & ID.

Word Report Design 8

Now you will be able to access your Dataset with Table & Fields details. As shown in below screen.

Word Report Design 9

Place the cursor on top (or wherever desired) of the document to add Logo to the Report.

Select the Picture Filed from the Dataset -> Right Click -> Insert Content Control -> Picture.

See below screen for details:

Word Report Design 10

You will see the Place holder for the Picture.

Now add Table with 2 Rows ( 1 for Header & 1 for Data) and 6 columns.

We have six columns in our dataset excluding Logo.

Word Report Design 11

Add your Header for the table, We are using fixed Text Heading as of now but you can add captions from your dataset.

In current report I have not included we can check same in some other report posts.

Word Report Design 12

Select Entire 2nd Row and Add Repeating Content Control for Item (Table).

As this will show records from the table Item we included in our Dataset.

Word Report Design 13

Now in each column add your columns from Dataset as shown below.

Place your cursor in each column and choose Insert Content Control -> Plain Text.

Word Report Design 14

Now our Report is almost ready.

May be the Report have data which may continue on several pages, in this case our Heading Row must Repeat on every new Page. To do this we will Select the entire 1st Row -> Right Click -> Table Properties.

Go to Row Tab of Property window and put a checkmark on option “Repeat as header row at the top of each page

Word Report Design 15

Save your Word Template an Import back in your report as shown below.

Word Report Design 17

Now Save the Report and Execute it.

Here is the Output below of the Report.

Word Report Design 16

We are done !!!

You can use formatting feature of Word to add more better look to your Report as desired.

Stay tuned for more in upcoming posts.

Don’t forget to follow the Blog Site for future posts.