Convert to PDF, Development Tips, Email, How To, NAV 2017, Office 365, Office Integration, Report, Tip & Tricks, Word

Mail Sending Option in NAV 2017 with Cover Letter & Attachments –Part 2

Continuing from previous post, further in next step we will apply same feature discussed in earlier post to our custom documents and learn where all places we need to take care development to get it working.

If you have missed First Part you can find here. Mail Sending Option in NAV 2017 with Cover Letter & Attachments –Part 1

In my Example I am using Policy Module:

I am using my Custom Table Policy where Policy Holder is setup as Customer, also few general details related to policy is stored. In nutshell we are concentration on Sending mail to customer as we have done in previous post for sending Invoice details to customer.

Step-1:

In my Policy Table I have added 2 Function as below:

MSI-07

 

MSI-08

SendRecords()

IF DocumentSendingProfile.LookupProfile(“Policy Holder No.”,FALSE) THEN

SendProfile(DocumentSendingProfile);

 

SendProfile(VAR DocumentSendingProfile : Record “Document Sending Profile”)

DocumentSendingProfile.Send(

DummyReportSelections.Usage::”Policy Issue”,Rec,”Document No.”,”Policy Holder No.”,

DocTxt,FIELDNO(“Policy Holder No.”),FIELDNO(“Document No.”));

Step-2:

In Table 77 Report Selections add new option to usage field

MSI-09

Step-3:

In Table 60 Document Sending Profile add below customization.

Add Text Constants

MSI-10

Update below function as:

MSI-11

Step-4:

In Table 9657 Custom Report Selection add below customizations.

MSI-12

 

MSI-13

Step-5:

In Page 9657 Custom Report Selection add below customization.

MSI-14

 

MSI-15

 

MSI-16

Step-6:

Create 2 Reports one for Mail Body and one for Attachment. You can use same report as attachment too, it depends on your requirement.

Step-7:

In Page Policy add below customization.

MSI-17

 

MSI-18

Step-8:

Setup your report Selection as below:

MSI-19

Now you are good to go.

Test your solution/ customization.

This is just a small idea, many lots can be done depending upon your requirements.

 

 

 

Advertisement
Convert to PDF, Development Tips, Email, Functional Tips, How To, Information, Layouts, NAV 2017, Office Integration, Tip & Tricks, What's New, Word

Mail Sending Option in NAV 2017 with Cover Letter & Attachments –Part 1

Generally we get demand for customized mail body to send from Navision. Normally we use templates or html etc. coding to achieve this. In NAV 2017 this feature is now available in product itself. Today we will explore this feature available for Std. documents and learn to setup, further in next step we will apply same to our custom documents and learn where all places we need to take care development to get it working.

The cover letters are created using RDLC or Word layout customization features providing visual consistency with any attached pdf document.

Document Layout for a Customer

MSI-01

For Example say we want to setup different e-Mail body for specific customer. To achieve this we will assign a specific report by customer which will enable us to process multiple formats at the same time. We will use the Customer Layout from the customer card by Document Type to do this.

MSI-02

In above example I am setting up a customized cover letter designed using selected report.

The Send To Email The e-Mail will be sent to the e-Mail provided in the customer card or you can provide an extra e-Mail in this field or you can specify at the time of sending mail if not setup automatic.

Email Body Layout Description = Modern – Email Body (Choose from the Custom Report Layouts)

Use for E-mail Body select this if you wish to include output of selected report as Cover Letter to Email body.

Send and Receive E-Mail

We can now use the Send Email window to have a preview of what our layout will look like and the using the options we can send the e-Mail.

Let’s open a posted invoice for this customer.

MSI-03

On the Posted Sales Invoice click Send, which will open a window with some options, such as:

We can choose Email Prompt for Settings or use Default Settings

We can select how the attachment needs to be attached

We can also have Disk options as PDF or Electronic Documents if we use those.

Click OK. Before e-Mail is sent, we have the possibility to verify the e-Mail address, the subject line, the attachments and as per the Email Body Template, this is how the e-Mail will look like:

MSI-04

When we click OK, an e-Mail is sent to the Customer using the e-Mail Template.

By opening the e-Mail the recipient can see the contents of the invoice which has been sent using the template and the full invoice is also available as an attachment.

MSI-05

You can switch to a manual written message:

By using the Message Content field or

If you are using a client, you can open and edit the message in Outlook

MSI-06

In our next part of this post, we will see how we can enable this feature for our custom Pages & Documents.

 

 

Convert to PDF, Development Tips, Excel, How To, Information, Office Integration, Tip & Tricks, Word

Appending other information to Navision Reports

There is always requirement from many customers to Append information to the Navision Reports.

Recently one of my reader have requested me for any such functionality which can help him Append information from Word or Excel Files to Navision Reports.

While searching for solution for such requirement i came across this scope if we can do the same from outside Navision integrating the functionality with Navision.

Although i am not sure how much this post will answere to the requirement raised by my this reader but still this can be an work around to this requirement.

In my previous 2 posts i have answered this approach, Let us assemble all of them to provide solution to this requirement.

Please see my privious posts, i will not repeat already covered part in this post. Here is the link to those posts:

Converting Office Files into PDF from Navision

Merging PDF Files in Navision

In this post i will be using these functions discussed in above posts.

The Same Setup will be applicable to this post too.

PDFConvMerge-2-2

Since we are appending our other information to the Navision Report so we will be at First Step saving our Customer Sales Invoice to PDF.

Later some information which need to be appended to this report is in Word File the path of which is stored on Customer Card.

How to work with Converting Office file to PDF is already discussed in previous post Link shared above.

So Now we have Our Report in PDF and Additional information to be appended to Report is also in PDF. Now it will be easy for us to Merge both the File to have single PDF File.

How to Merge these files is also already discussed in my previous post. Link shared above.

Let us see how we can assemble above both functionality to get our required result.

Approach is very simple, i have created a button on Sales Invoice to Print the Report which performs above discussed process.

PDFConvMerge-5

On Sales Invoice Page I have added one Button which calls my Function to Print & Merge the document, it takes Invoice No & Sell-to Customer No. as a parameter.

PDFConvMerge-6

I have created a function to Save the output of Report to PDF, using standard functionality available in Navision.

PDFConvMerge-7

The PrintSalesInvoice function called from Sales Invoice Page with Invoice No & Sell-to Customer No.

This Function calls the SaveReportAsPDF explained above.

Converts the Office file that is attached on Custommer Card, discussed in previous post Link provided above.

Calls the MergePDFFiles, discussed in previous post Link provided above.

So Now at single click of Button entire task is done for us.

To keep it simple no additional checks and other routine tasks have been included like after task is completed clean up of all temporary files and moving the Result file to desired Location etc.

Now you know the logic so you can tweak the code accordingly to get the functionality working as per your requirement.

Thats all for this post. I will come up with more information in my up coming posts.

You keep you requirements posting to me, i will try my best to answer your queries in form of my future posts, at earliest possible from my end.

Till then kee exploring & Learning.

Convert to PDF, Development Tips, How To, Information, Office Integration, Tip & Tricks, Word

Converting Office Files into PDF from Navision

Today in this post i will walkthrough how we can convert any MS Office File into PDF.

It have been many time required to convert any attached file with the record in Navision to PDF format.

To perform this action we will require a tool which can be downloaded from:

OfficeToPDF download link :- http://officetopdf.codeplex.com/releases/view/118190

Extract and save the OfficeToPDF.exe file to some Folder.

For this Walkthrough i have created a Field in Customer Table to save the File Path of the Office File which we want to convert into PDF.

PDFConvMerge-1

You can add Dialog box to select the File from the specified Folder.

For this demo i have kept it simple Text Field where you can add your File Path and Office File Name. It is assumed that only Office File will be attached here.

For Setup purpose i have created one Setup Table & Page where we will store our other required Folder paths.

PDFConvMerge-2

Here we have given provision to save the Path of the Office to PDF Convertor Tool file Path & Temporay working Folder.

I have used the shared folder for all the paths so that it is not system specific, also make sure you give required permission on this folder for all the operating accounts.

Now our Next task will be to write a function which will perform this conversion part.

PDFConvMerge-3

Above Function Takes the File Name from the Customer Card we stored above on Customer Card. Takes the Path of the Office To PDF Convertor Utility and Tmp working Folder.

Prepares the PDF file Name along with Path stored in Setup.

Prepares the command to invoke Convert Utility using WsShell and returns the PDF file File Name along with path as defined in the Setup.

Now you can use this File for futher purpose as required.

To keep it simple no additional code of test and other required routine task is not added.

Now you know the Logic you can tweak the functionality as per your requirement.

I will comeup with more information in my up comming posts, till then keep exploring and learning.

 

Corfu Navision 2016, Development Tips, Functional Tips, How To, Layouts, Office Integration, Report, Selection, Word

Modify, Assign and Process Email for Word Forms in Navision 2016

Microsoft Dynamics NAV 2016 offers new functionality with Microsoft Word forms and emailing documents for Customers and Vendors. You can now modify the customer statement report and the vendor remittance report using Microsoft Word. You can also select a specific report format by customer to ease the statement process.

To make this functionality work for you, you need to make sure you have setup the SMTP Mail Setup. You can see my earlier post OFFICE 365 INTEGRATION IN NAV 2015 – Exchange Online this is still valid for Navision 2016.

Recall from my earlier posts, how to work with Word Layouts which I have written for 2015 but those are still valid for 2016 links as below.

Word Document Reports and Custom Layouts

Using Report Selector to run Report

Managing Report Layouts

In Microsoft Dynamics NAV 2016, Microsoft have extended the functionality for Word forms and Email beyond the Sales documents. We now have default Microsoft Word forms for Customer Statements and the Vendor Remittance report.

You can now modify the Word form to meet your needs, assign a custom Word layout to a specified customer or vendor and print or email based on those customer specific selections.

In the Report Layout selection, there is a new report object for the Customer Statement with a default Word report created.

The Mini Statement report (1316) is based on the existing RDLC customer statement but includes a Word report with the same information. You can use Managing Report Layouts to know more details regarding customizing the Layouts.

In Report Selection – Sales, you can set the Customer Statement to use the new report, Mini-Statement – 1316.
Report2016-1

Now your system is setup to use the specified layout for all customers and the statement itself is going to use the new report.

Now that Microsoft Dynamics NAV is setup to use the new report, you can assign a specific report by customer. This will enable you to have multiple formats processed at the same time.

We assigned a custom layout to the customer in the customer card.

Here you set your selection by document type, for example, the sales quote or the customer statement.

You can also enter an email address for the document. So, if the statement goes to your customer’s accounts receivable clerk and the sales quote is sent to the sales manager, you define this information in the Document Layouts page.

The system uses the custom layout when you print the documents instead of emailing them.

Enter multiple email addresses with a semi-colon to separate them.
Report2016-2

You can do this for all customers.

When statements are processed, the report layout used is the one assigned to the customer. If the customer has no custom layouts assigned, the custom layout assigned in the Report Layout Selection is used.

If you go to Customer Statements, you can see that that Output Options are available. This will let you select how you wish to use the document layout settings.
Report2016-3
A checkbox will appear allowing you to print remaining statements. If you mark this checkbox, any statements with an email address in Customer Document Layouts is emailed, and any statements with a custom report layout but no email address will print with that report layout and any customers without any document layout settings will use the company default report from Report Layout Selections.

I will come up with more details in my upcoming posts.

Development Tips, Jet Reports, Office Integration, Report

Customize the Report layout using Jet Express for Word

Click Edit Layout to customize this layout
JetReportDesign-1

The Jet Express for Word action panel may automatically open when this word file is opened.

If not, select the Jet Ribbon

Click on the Design icon

This presents a tree hierarchy of the fields from the selected report. 
JetReportDesign-2

Click on the icons on the hierarchy to expand or contract the lists.

The Search field makes it easy to find the fields you need.

Labels – NAV reports which were created by Jet Reports include a section for Labels. These fields are the descriptions of the fields themselves.

If you have multiple languages in your NAV instance, these labels can be helpful for creating multi-language documents.

Other Groupings – NAV reports which were created by Jet Reports include sections for Company, Customer, etc. These fields include the values of the fields.

The user can select from fields including Header or Lines in the hierarchy and insert an item, typically into a table in the Word document.
JetReportDesign-3

To add a field select the desired location in the Word document and double-click on the field.

Alternatively, you can select the field and click on the Insert button in the Jet Express for Word action panel.

To Add a picture to a document, right-click on the item and select Insert Picture
JetReportDesign-4

The Lines fields are also inserted as text and can be replicated by a Right-click, and choosing “Insert Repeater”.

Repeating items (such as Sales lines on a Sales order) can be added to a document.
JetReportDesign-5

Best practice for this is to create a table in Word that is two rows high.

The first row contains the Labels of the fields that you wish to include.

The second row contains the values of the fields.

Select the entire second row- include the area just to the right of the last column.

Right-click on the item in the hierarchy that you want to repeat and select Insert

To delete an item, click on it, and then click on its Title.
JetReportDesign-6
When you click on the Title it will change color.

Then press the Delete Button on your keyboard.

Note: It’s important to select the Title when deleting to avoid any leftover data.

When you have completed your changes Save your Word document
JetReportDesign-7
This will return you to NAV and prompt you to import the report layout changes.
JetReportDesign-8
Click Yes

You can Run Report to review your changes.
JetReportDesign-9
Here is the output for the report below.
JetReportDesign-10
We are done with customization of the report using Jet Reports.

I will come up with more details in my upcoming posts.

Development Tips, Jet Reports, Office Integration, Report

What’s New in Jet Reports for Word, How it is different from Navision Word Reports

Before we compare both the way of creating report in word, the features I would be suggesting you to review the posts which I have posted earlier Word Document Reports and Custom Layouts to refresh the concept of creating reports in Word.

Let’s start with comparing how it is different from Navision Word Report.

Create a custom layout for the report you wish to use

In your NAV client navigate to Report Layout Selection (Administration/IT Administration/ Reports).

Microsoft Dynamics NAV 2015 includes several sample Word reports including:

14125500             Sales Order – Jet Ex. Word

14125501             Sales Invoice – Jet Ex. Word

14125502             Sales Cr. Memo – Jet Ex. Word

14125504             Sales Quote – Jet Ex. Word

I have filtered the above Reports.

Select the report that you wish to customize. (I am Using 14125500 for this example)
CustomiseJetReport-1
Click Custom Layouts.

 To create a new Report Layout, click New.

A pop-up window will appear and allow you to choose the layout type.

Check the Insert Word Layout box and click OK.

CustomiseJetReport-2

CustomiseJetReport-3

In the Report Layouts window, you can change the Description.

Click OK

In the NAV Custom Report Layouts window, highlight the layout you wish to use and click the Import Layout button from the ribbon.

Browse to the Jet Express for Word Sample Documents, choose the template you want and click Open
CustomiseJetReport-4
Click Edit Layout to customize this layout.

CustomiseJetReport-5

Above screenshot show how to Access the XML part of the Report.

Left side shows Jet->Design

Right side shows Developer->XML Mapping Pane

If you remember In Navision word Report we use to select the Custom XML Part from the dropdown to access the available fields, Labels etc.

Whereas if we see In Jet Report this is not required.

Also you may have observed that Jet Report Pane Have search option, which makes easy to find desired fields rather than scrolling through the XML Nodes to access the desired Fields.
CustomiseJetReport-6

You may observe in above picture that I have typed the part of the Field I am looking for and Jet Report Pane suggested that Similar to what I typed there is a Field “Salesperson” and it available under 2 heads Labels & Header data items.

If I require to insert the Labels or Fields, Place the cursor at desired place where you want that Field to be inserted and Double Click to the Field from Jet Report Pane.
CustomiseJetReport-7
Where as to perform same action in Navision Word Place the cursor where we wish to Insert the Field then we use to Scroll to the Field we wish to insert then we perform step Right Click->Insert Content Control->Plain Text
CustomiseJetReport-8
I will come up with more details in my next post. We will see how we can design the Report Using Jet Report fast and easily.

Also some Best Practice, Tip & Tricks while using Jet Reports.

Development Tips, Instalation & Configuration, Jet Reports, Office Integration

Jet Express for Word – Objects for Navision 2015

Getting Started for Administrators

Overview

Microsoft introduced a new feature with Dynamics NAV 2015 which makes it easy and inexpensive for partners and end users to create and customize visually attractive document reports in NAV using Microsoft Word.

In collaboration with Microsoft, Jet Reports developed Jet Express for Word – an application that supports this process by providing users an easy-to-use interface inside Microsoft Word to create and modify these documents.

From where to download these objects

If you remember my previous post where I shared the link of download page. See here.

JetReportObjects-1
Refer to Step-3 in above screenshot.

Download the Objects from the Link.

Jet Express for Word includes four NAV reports and a set of sample sales documents.

These four NAV reports include:

 Report Number Name
14125500 Sales Order – Jet. Ex. Word
14125501 Sales Invoice – Jet. Ex. Word
14125502 Sales Cr. Memo – Jet. Ex. Word
14125503 Sales Quote – Jet. Ex. Word

Installing these reports in NAV

These four reports are included in a .FOB file which is available from the Jet Express for Word website.

To install this .FOB file you will need access and permissions to the Microsoft Dynamics NAV Development Environment.

In this application select File > Import… and browse to find the downloaded .fob file.
JetReportObjects-2

JetReportObjects-3

JetReportObjects-4

Uninstalling Jet Express for Word documents

If you need to uninstall the Jet components from the Microsoft Dynamics NAV Server-

  • Open the Microsoft Dynamics NAV Development Environment and then connect to the database
  • Open the Object Designer (on the Tools menu, choose Object Designer)
  • Select All to see all business objects.

Select the business objects which were inserted (listed above), right-click and select Delete. When asked if you want to delete the selected lines click Yes.
JetReportObjects-5

Development Tips, Instalation & Configuration, Jet Reports, Office Integration, Report

Jet Express for Word Overview & Installation – for Navision 2015

Jet Express for Word is a new feature available to Microsoft Dynamics users which makes it easy for end users to design documents in Microsoft Word. This feature is part of Jet Express for Microsoft Dynamics NAV and is available to Microsoft Dynamics NAV 2015 users.

Modify Reports in Microsoft Word

Need to change the layout of an invoice or credit memo? Just open the document in Microsoft Word to make changes in a program you already know—no programming required.

Provided you already have reports developed by the Navision professionals. You can only make Layout, Look & Feel changes. For any business logic or including/excluding fields in report will be handled from Navision only as we do.

Design with Flair

You can use document templates that provided by Jet Reports, templates from the Office Store, or create a document from scratch. Add company logos, change fonts, modify fields and customize for multiple regions easily.

Easy to Use

The simple interface allows you to customize or create document layouts using Microsoft Word. Your fields appear in clear text and the search feature makes it quick to add the fields you need.

New functionality in Microsoft Dynamics NAV 2015 allows you to import these document layouts into NAV and run them from within the NAV client.

Software Requirements

  • Microsoft Dynamics NAV 2015
  • Office 2013 Desktop Edition

Supported Languages

  • English, Danish, Dutch, French, German and Spanish
  • More languages will be added soon

Where to get Jet Report Installation Files

You can use this Link, Visit to Jet Reports site here.

JetReportInstallation-1

JetReportInstallation-2

– Download the Jet_Express_for_Word_Installer.zip file

– Right-click the zipped file and select “Extract All”

– Right-click the file “setup.exe” and choose “Run as administrator”

JetReportInstallation-3

JetReportInstallation-4

JetReportInstallation-5

Verifying the Installation

Open the Word and you will find one more TAB in Ribbon. [JET]

JetReportInstallation-6

Just in case you don’t find the Tab, Follow below set to enable the same, provided your Installation was successful in previous step without any error.

JetReportInstallation-7

Developer -> COM Add-Ins

Check if Jet Express for Word is enabled, if not select it and say OK.

If already enabled but still you don’t see, disable and enable again. Restart your word now you will be able to see the JET TAB.

I will come up with more information in my upcoming posts.

Development Tips, Office Integration, Report

Using Automation to Write a Letter in Microsoft Office Word

Automation lets you use the capabilities and features of Microsoft Office products, such as Microsoft Word or Microsoft Excel, in your Microsoft Dynamics NAV application.

Today we will implement Word Automation from a customer card in the Microsoft Dynamics NAV Windows client.

Note: The Microsoft Dynamics NAV Web client does not support automation.

Most information that we need to transfer to Word for this example is in the Customer table. The Customer table contains a FlowField called Sales (LCY) that contains the aggregated sales for the customer.

In this example we are learning about Automation, so we will use the existing value. In a real customer installation, we would need to set up an appropriate date filter to get the sales for the past year only.

We also need to retrieve the information about our own company that we will use in the letterhead and in the greeting of the letter. This information is contained in the Company Information and User tables.

  • The Automation server must be installed on the computer that compiles an object that uses Automation. If you must recompile and modify an object on a computer that does not have the Automation server installed, then you must modify the code to compile it again. We recommend that you isolate code that uses Automation in separate codeunits.
  • Performance can be an issue if extra work is needed to create an Automation server with the CREATE system call. If the Automation server is to be used repeatedly, then you will gain better performance by designing your code so that the server is created only once instead of making multiple CREATE and CLEAR calls).

Performance can be improved by putting the code on the customer card because you do not have to open and close Word for each letter that is created in the session.

You can work around this problem. If Word is already open when it is called from the code, then the running instance is reused. You can manually open Word or do not close Word after creating the first letter.

We will extract and transfer data one customer at a time. We will also initiate this processing and the subsequent processing in Word from the customer card.

We will insert fields into the Word template and give these fields convenient mnemonic names that correspond to the names of the record fields that we are using.

To make this work, C/AL code must make two extra calls to Microsoft Office Word. You must call the ActiveDocument.Fields.Update method before using the fields. After you have transferred all the information, you must call the ActiveDocument.Fields.Unlink method. This ensures that you can successfully use the Word fields as placeholders.

In addition, while you can name the Customer or Address fields, you must reference them by indexing into the Fields collection of the document. This can make the C/AL code harder to understand.

Creating the Word Template for Use by Automation

First, task is to create a Word template that we will use to create letters to customers that qualify for a discount. To create the template, we will add mail merge fields for displaying data that is extracted from Microsoft Dynamics NAV that you want included in the customer letter, such as the customer’s name, contact, and total sales.

You will create and save the template on the computer running the Microsoft Dynamics NAV Windows client, because you will configure the automation object to run on the client.

  • On the computer running Microsoft Dynamics NAV Windows client, open Word and create a new document.

WordAutomation-1

  • Choose where you want to insert the fields. Then, on the Insert tab, in the Text group, choose Quick Parts, and then choose Field.

WordAutomation-2

  • In the Categories list, select Mail Merge.
  • In the Field names list, select MergeField.
  • In the Field Name box under Field Properties, type Contact. This field will display the name of your contact person at the customer site as taken from the Customer table.
  • Choose OK to add the field.

WordAutomation-3

  • Repeat steps as above to add the remaining fields as follows:
Field name Description Underlying table
Name The name of the customer. Customer
Address The address of the customer. Customer
Sales (LCY) The total amount that the customer has purchased from you. Customer
Company Name The name of your company. Company Information
  • Save the Word document as a template with the name Discount.dotx in folder of your choice.

WordAutomation-4

Creating the Codeunit and Declaring the Variables

The next step is to create the codeunit that calls Word and creates the letter.

To create the codeunit

  • In Object Designer, choose Codeunit, and then choose the New button to create a new codeunit.
  • On the View menu, choose Properties to open the Properties window of the codeunit.
  • In the TableNo field, choose the AssistEdit button to open the Table List window.
  • In the Table List window, select the Customer table, and then choose OK.

WordAutomation-5

  • Close the Properties window.

To declare the variables

  • Choose the OnRun Trigger and on the View menu, choose C/AL Locals, and then choose the Variables tab.
  • On a blank line, type wdApp in the Name field and set the Data Type field to Automation.

Note

When you create an Automation variable, some hidden events are also created for it. If you want to delete the variable, be aware that the events are also not deleted. This can cause issues if you then create a variable with the same name.

  • In the Subtype field, choose the AssistEdit button. The Automation Object List window is displayed.
  • In the Automation Server field, choose the AssistEdit button.
  • In the Automation Server List, select Microsoft Word 15.0 Object Library if you are running Word 2013, or select Microsoft Word 14.0 Object Library if you are running Word 2010, and then choose OK.
  • From the list of classes in the Automation Object List, select the Application class, and then choose OK.

WordAutomation-6

  • Repeat steps above to add the following two Automation variables:
Name Data type Subtype Class
wdDoc Automation Microsoft Word 14.0/15.0 Object Library Document
wdRange Automation Microsoft Word 14.0/15.0 Object Library Range
  • Add the following variables.
Name Data type Subtype Length
CompanyInfo Record Company Information
TemplateName Text 250
  • Close the C/AL Locals window.

Writing the C/AL Code

Before you start writing the C/AL code that uses Automation, you must do some initial processing. You start by calculating the Sales (LCY) FlowField. Then, you check whether the customer qualifies for a discount. Finally, you retrieve the information from the Company Information and User tables that you use to fill in some of the fields in the letter.

To write the C/AL code

  • In the C/AL Editor, add the following lines of code to the OnRun section.
  CALCFIELDS(“Sales (LCY)”);CompanyInfo.GET;
  • To create an instance of Word before using it, enter the following line of code.
 CREATE(wdApp, FALSE, TRUE);
  • This statement creates the Automation object with the wdApp variable.
    1. The first Boolean parameter in the statement (FALSE) tells the CREATE function to try to reuse an already running instance of the Automation server that is referenced by Automation before creating a new instance. If you change this to TRUE, then the CREATE function always creates a new instance of the Automation server.
    2. The second Boolean parameter in the statement creates the Automation object on the client. This is necessary to use this codeunit on a page in the Microsoft Dynamics NAV Windows client.
  • Enter the following lines of code to add a new document to Word that uses the template that you designed earlier. If required, replace C:\Users\atripathi5283\Desktop\Nav-2015\Word Letter with the correct folder path to the template that you defined in the procedure.
 TemplateName := C:\Users\atripathi5283\Desktop\Nav-2015\Word Letter\Discount.dotx’;wdDoc := wdApp.Documents.Add(TemplateName);wdApp.ActiveDocument.Fields.Update;
  • Because the Add method of the Documents collection requires that you pass the path to the template by reference, you must set up the TemplateName variable to hold this information. You will get a compilation error if you put the path into the call as a literal string.
  • The Documents property returns a Documents collection that represents all open documents. You can also see that the Documents collection object has an Add method, and that the Add method has the following syntax.
  • expression.Add(Template, NewTemplate, Document Type, Visible)
  • expression is a required argument, and it must be an expression that returns a Documents object. All the arguments are optional. You will use Template to open a new document that is based on your template.
  • For the syntax in the C/AL Symbol Menu, note that the Documents property returns an object of type DOCUMENTS, which is a user-defined type. The property returns a Documents class or IDispatch interface. This information helps the compiler perform a better type check during compilation. The following statement can also pass both the compile-time and the run-time type checks.
  • wdDoc := wdApp.Documents.Add(TemplateName);
  • Finally, the Add method returns a Document class. While you did not need to declare a C/AL variable for the interim Documents class, you have declared a variable for the wdDoc return value,.
  • The third line contains a call that must be made to ensure that the template works as intended.
  • wdApp.ActiveDocument.Fields.Update;

Transferring Data to Word

Now you can transfer the actual data from the Customer record to the placeholder fields in the Word document.

You have set up the first three fields in the template so that they can contain the contact, name, and address of the customer and you can transfer the data.

To transfer data to Word

  • Transfer the data by adding the following lines of code.
 wdRange := wdAPP.ActiveDocument.Fields.Item(1).Result; wdRange.Text := Contact; wdRange.Bold := 1; wdRange := wdAPP.ActiveDocument.Fields.Item(2).Result; wdRange.Text := Name; wdRange.Bold := 1; wdRange := wdAPP.ActiveDocument.Fields.Item(3).Result; wdRange.Text := Address; wdRange.Bold := 1;
  • You cannot use the fields directly as variables and make an assignment such as Fields.Item(3) := Address. Instead, you use the Result property of the field. This property returns the result of the field as a range. You place this range in the wdRange Automation variable that you declared.
  • You then set the Text property of the range to the desired values, which is the name of your contact person and the name and address of the customer. Finally, you add bold formatting.
  • The data you are transferring must be in text format. If it is not in text format, then you get a compilation error. wdRange.Text expects arguments to be of type BSTR, which maps to either Text or Code. This means that any data that is not Text or Code must be converted before it is passed to Word. To convert a field to Text, you use the FORMAT function. All the fields that are transferred in this step are in text format, so no conversion is needed and the FORMAT function is not used. However, in this example, you also need to transfer the Sales (LCY) field, which is a Decimal field. To see how to convert the Sales (LCY) field, go to the next step.
  • To transfer and format the data from the Sales (LCY) field, add the following code.
 wdRange := wdAPP.ActiveDocument.Fields.Item(4).Result;wdRange.Text := FORMAT(“Sales (LCY)”);wdRange.Bold := 0;
  • To transfer the information from the Company Information table, add the following code.
 wdRange := wdApp.ActiveDocument.Fields.Item(5).Result;wdRange.Text := CompanyInfo.Name;
  • To complete the processing in Word, add the following code.
 wdApp.Visible := TRUE;wdApp.ActiveDocument.Fields.Unlink;
  • The first statement opens Word and shows you the letter that was created. The second statement makes the fields work as placeholders.

WordAutomation-7

  • Save and compile the codeunit

To-Do List

Although this code will work, you must add a few things to make it complete:

  • We recommend that you do not use a hardcoded template name. You should keep the template name in a table, and the user should select it from a page. You can then have different templates for different types of letters that you want to send to your customers.
  • You should add some error-handling code. For example, the CREATE call fails if the user does not have Word installed or if the installation has been corrupted. You should check the return value of CREATE and give an appropriate message if it fails.
  • The user should get a message if the customer does not qualify for the discount. In the example, the codeunit closes without any message.

Calling the Codeunit from the Customer Card

The final task is to ensure that you can call the codeunit from the Customer Card page in the Microsoft Dynamics NAV Windows client.

To call the codeunit from the Customer card page in the Microsoft Dynamics NAV Windows client

  • Open Object Designer, and then choose Page.
  • Select the Customer Card page and then choose Design.
  • On the View menu, choose Page Actions.
  • To add a new action, locate the action container with the subtype set to ActionItems.
  • Right-click the next line after the ActionItems container, and then choose New.
  • In the Caption field of the new line, type Word Letter.
  • Set the Type field to Action.
  • With the new action selected, on the View menu, choose Properties.
  • In the RunObject field, type codeunit Discount Letter.

Note

If you saved the codeunit that you created in the previous procedure under a different name, then substitute Discount Letter with the name that you used.

  • Use the arrow buttons to make sure that the new action is indented only once from the ActionItems container above it

WordAutomation-8

  • Save and compile the Customer Card page.

To run the Customer Card and view the Word letter

  1. In Object Designer, choose the Page
  2. Select the Customer Card page, and then choose Run.
  3. In the ribbon, on the Actions tab, choose the Word Letter

The letter document opens in Word.

WordAutomation-9

Next Steps

The letter that you have just created only contains five fields and sample body text. Before you can use this letter in an actual situation, you will need to add some more fields, such as the name and address of your own company, the date, and the currency code, and the main text of the letter. It will also need some formatting to make it look more attractive. If you alter the order in which the fields appear in the template, you must change the numbering of the fields in the codeunit to ensure that the correct data is inserted into the appropriate fields.