AL, Business Central, Development Tips, File, How To, Information, InStream, Modern Development Tool, OutStream, Tip & Tricks, V2, Visual Studio Code, XMLports

File Handling using Stream – Business Central

Today in this post we will discuss about using Stream to Export or Import Files or in other words File handling using Streams.

First Example I am discussing about is how to Import Image to Item Picture.

First part of the code checks for if any existing Picture in the records Picture field, here we use Count to check, because Picture field is defined as MediaSet can hold multiple picture, so giving warning for Overwrite.

In Second part we are Uploading the Selected Image to the InStream.

Finally we clear the Picture field and load Picture from InStream, here file name will be used as description for the image.  And save the record post importing of the Image.

Below code sequence is self explanatory.

StreamImpImage

In Second example we are Exporting the image from the record, any/all images stored in Picture field of the Item record.

Again we are testing with Count if any Image stored, else flag the Error nothing to Export as record don’t have any picture stored.

As told above since it is MediasSet type so possibility of more than one Image may have been stored, so we setup for loop to access all of them.

In TenantMedia table all Images are stored with unique GUID, so we get them each by Item(index).

Calcfields used to load the content in memory and final checking if it HASVALUE.

We build the filename as Item_Image1.ext, we will look into GetImgFileExt function below.

Next we load the Image in InStream.

Finally we save the Image on disk by specified filename.

StreamExpImg

This below function we use to find right extension of the file from TenantMedia field Mime Type.

StreamGetFileExt

In last and below function we are using TempBlob Table and Stream to handle file.

We create the OutStream of BlobTable Blob Field, set it as destination for my Export XML Port.

Further creating the InStream we are transferring the content of Blob to the File.

StreamExportContact

Hope you will start using this technique in your future projects, when working with File Handling.

We will discuss on other concepts in our upcoming posts.

Not sure if this is my Last post for this year, so wishing you Happy New Year 2019 in advance.

Keep practicing and learning, see you again in my next post.

Till then bye, take good care of your self and remain safe.

 

Advertisement
Development Tips

How to create a root CA and a private key file by using the makecert.exe utility

We will follow below step to create a certificate for Microsoft Dynamics Server. Then we will implement the same for login from WAN to access Navision using Windows and Web Clients.

  • On the computer running Microsoft Dynamics NAV Server, create a temporary folder to use when you work with certificates.
  • Open the command prompt as follows:
    • If you have Visual Studio installed on your computer, choose Start, choose All Programs, choose Microsoft Visual Studio 2012, choose Visual Studio Tools, and then right-click Visual Studio Command Prompt and choose Run as Administrator.
    • If you have the Windows SDK installed on your computer, choose Start, choose All Programs, choose Microsoft Windows SDK, and then right-click Windows SDK Command Prompt (2010) (or CMD Shell) and choose Run as Administrator.
  • At the command prompt, locate the temporary directory.
  • Type the following command.

makecert -n “CN=RootNavServiceCA” -r -sv RootNavServiceCA.pvk RootNavServiceCA.cer

Certificate-4

  • When you are prompted, enter a password.
    • You need this password to create the service certificate.
  • The RootNavServiceCA.cer certificate file and the RootNavServiceCA.pvk private key are saved in your temporary folder.

Certificate-5

Now we will use the Certificates snap-in to install the root CA on the computer running Microsoft Dynamics NAV Server

  • Start the Certificates snap-in for MMC on the computer running Microsoft Dynamics NAV Server, and then add the Certificates snap-in.
  • In the Certificates snap-in dialog box, choose Computer account, and then choose Next.
  • In the Select Computer pane, choose Local computer: (the computer this console is running on), and then choose Finish.
  • Choose OK to close the Add or Remove Snap-ins dialog box.
  • In the left pane of MMC, expand the Certificates (Local Computer) node.

Certificate-2

Certificate-3

  • Expand the Trusted Root Certification Authorities node, right-click the Certificates subfolder, select All Tasks, and then choose Import.

Certificate-6

  • In the Certificate Import Wizard, on the Welcome page, choose Next.
  • On the File to Import page, choose Browse.
  • Browse to the location of the RootNavServiceCA.cer certificate file, select the file, and then choose Open.
  • On the File to Import page, choose Next.
  • On the Certificate Store page, accept the default selection, and then choose Next.
  • On the Completing the Certificate Import Wizard page, choose Finish.

Certificate-7

The RootNavServiceCA certificate is now visible in the list of trusted root CAs.

Certificate-8

In next step we will now create a certificate revocation list for the root certification authority and then install the certificate revocation list on the computer running Microsoft Dynamics NAV Server.

A certificate revocation list is required because WCF applications check the revocation list when validating certificates.

Next Step Link- How to create a certificate revocation list for the root certification authority

Development Tips

AccessByPermission Property – in Navision 2015

Sets a value for a table field or UI element that determines the permission mask for an object that a user must have to see and access the related page fields or UI element in the client. The UI element will be removed at runtime if the user does not have permissions to a certain object as specified in the Access by Permission window.

AccessByPermission-1
AccessByPermission-2
AccessByPermission-3

Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only user interface (UI) elements on objects in the license or on objects that the user has permissions to will appear in the user interface.

AccessByPermission-4

To make full use of the LicenseFileAndUserPermissions option in the UI Elements Removal field, it is recommended that you assign the special permission set, FOUNDATION, along with the relevant permission sets that define which application objects the user will access.

AccessByPermission-5

The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks.

If you only use the LicenseFile option in the UI Elements Removal field, then you do not have to edit any permission sets as they will not affect which UI elements are removed.

To specify when UI elements are removed
  1. Open the Microsoft Dynamics NAV Server Administration
  2. In the UI Elements Removal field, choose the relevant option as described in the following table.
Option Description
None All UI elements are displayed, even if the license file does not include the related object and the user does not have permissions to the related object.
LicenseFile A UI element is removed if the related object is not included in the license file.
LicenseFileAndUserPermissions A UI element is removed if the related object is not included in the license file and the user does not have permissions to the object as defined in the AccessByPermission property for the related UI element.

By default, this option is selected.

AccessByPermission-6

When you configure user interfaces in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, LicenseFileAndUserPermissions, so that you only see the relevant UI elements in the Customize window.

When you develop in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, None, to make sure that all UI elements are visible when you review your development in the UI.

All types of UI elements will be removed if they relate to objects that are not included in the license or the user does not have the required permission to the objects:

  • Fields
  • Actions
  • Page parts

UI elements that are directly related to an object through the TableRelation or the CalcFormula property can be removed automatically according to the license file and/or user permissions.

For UI elements that are not directly related to an object, you can use the AccessByPermission property to remove the element according to the user’s permission to a related object

All types of UI elements will be removed if they relate to an object to which the user does not have the required permissions:

Fields on pages, including FactBoxes

Actions on pages, including toolbars and navigation panes

Page parts, such as Lines FastTabs

Note

To use this property, the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool must be set to LicenseFile or LicenseFileAndUserPermissions.

This Property Applies To

Fields in tables (affecting all related fields on pages)

Fields on pages

Actions on pages

MenuSuite items

Page parts, such as a Lines FastTab

Property Value

When you choose the AssistEdit button, the Access By Permission window opens. Fill the fields as described in the following table.

Field Description
Object Type Specify the type of object to which permission is required to display the UI element.
Object ID Specify the object to which permission is required to display the UI element.
Read Specify if Read permission is required to display the UI element.
or Insert Specify if Insert permission is required to display the UI element.
or Modify Specify if Modify permission is required to display the UI element.
or Delete Specify if Delete permission is required to display the UI element.
or Execute Specify if Execute permission is required to display the UI element.

AccessByPermission-7

Note

If multiple permissions are selected, then one or the other applies.

Example: Remove the Unit Price field if the user does not have permission to the Sales Price table

Open table 27, Item Card, with the Table Designer.

View the properties of field 18, Unit Price.

For the AccessByPermission property, choose the AssistEdit button in the Value field.

In the Access By Permission window, fill the fields as described in the following table.

Field Description
Object Type TableData
Object ID Sales Price
Read Select
Insert Select
Modify Leave blank
Delete Leave blank
Execute Leave blank

Close the Access By Permission window and save the changes on table 27.

All instances of the Unit Price field on pages are now removed if the user does have Read or Insert permission to the Sales Price table.

AccessByPermission-8

Important

If you defined the property for a table field, then all instances of the field on pages are removed. To override the property on an individual page field, delete the permission value after the = sign in the Value field. Do NOT delete the whole string as that will be replicated on the property of the table field.

Note

To use the LicenseFileAndUserPermissions option in the UI Elements Removal field, you must assign the special FOUNDATION permission set to the user along with the relevant application permission sets that define which application objects the user will access. Unlike the BASIC permission set, the FOUNDATION permission set only grants access to application setup and system tables and requires that other assigned permission sets define which specific application objects can be accessed.

Not all of the 167 default permission sets that are provided with Microsoft Dynamics NAV are ready to support the FOUNDATION permission set to remove UI elements according to user permissions. You must therefore edit the relevant permission sets as explained in the following procedures.

To experience how UI elements are removed for a user performing the task to create and edit a new customer, you can create a sample user interface based on default permission sets provided with Microsoft Dynamics NAV.

Special Permission Sets

The following permission sets have special definitions that you should be aware of as you implement permissions and security for Microsoft Dynamics NAV users.

Permission set Definition
SUPER Can read, use, update, and delete all data and all application objects in the scope of your license. Microsoft Dynamics NAV requires that at least one user be assigned this permission set in each database.

You cannot modify permissions for the SUPER permission set.

SUPER (DATA) Can read, use, update, and delete all data. You typically assign this permission set to an accounting manager who needs to work with all data but does not need to change Microsoft Dynamics NAV.

This permission set does not give access to the Object Designer.

SECURITY Can create new users and assign them the same permission sets. Must be able to access the User, User Property, Permission Set, and Access Control tables.

For example, you can create a SECURITY permission set that includes the four required tables and any additional permissions that you want to include. You can then assign this permission set to a user who is a department administrator. This user can then administer permissions for other users in their department.

Only a user who has the SUPER permission set can create and modify a SECURITY permission set. Users who have this permission set can assign the same permissions to other users, but they cannot assign themselves the SUPER permission set.

BASIC Grants Read access to almost all application tables and all system tables.

The main purpose of this permission set is to enable the client to open and show all pages.

When you create a new database, you must import the BASIC permission set from an XML file.

FOUNDATION A prerequisite for all other permission sets. The FOUNDATION permission set grants access to system tables and application setup tables that are required for most application features to work.

Note

This permission set is recommended when using the UI Elements Removal feature to automatically remove UI elements according to user permissions.

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.