Tip & Tricks

Migration from BC-14 (On-Prem) to BC-21 (SAAS)

Assign, Business Central, Deploy, Extension, Package, Permission, XML

Package & Deploy the Extension

This is the Nineth post in the series. If you want to go to previous post click here.

From the series of steps this post is dedicated to Step-8:

As a Eighth Step we will Package & Deploy the Extension to Business Central

Now it’s time to Build and Deploy the Extension, but before that one more step required for creating Permission Set.

I have made some modification to the file generated in above process. Below is the complete file.

Sample Permission Set

<?xml version="1.0" encoding="utf-8"?>
<PermissionSets>
  <PermissionSet RoleID="BC_DV_DEMO" RoleName="BC_DV_Demo">
    <Permission>
      <ObjectID>50120</ObjectID>
      <ObjectType>0</ObjectType>
      <ReadPermission>1</ReadPermission>
      <InsertPermission>1</InsertPermission>
      <ModifyPermission>1</ModifyPermission>
      <DeletePermission>1</DeletePermission>
      <ExecutePermission>0</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50120</ObjectID>
      <ObjectType>1</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50126</ObjectID>
      <ObjectType>0</ObjectType>
      <ReadPermission>1</ReadPermission>
      <InsertPermission>1</InsertPermission>
      <ModifyPermission>1</ModifyPermission>
      <DeletePermission>1</DeletePermission>
      <ExecutePermission>0</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50126</ObjectID>
      <ObjectType>1</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50121</ObjectID>
      <ObjectType>8</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50120</ObjectID>
      <ObjectType>8</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50122</ObjectID>
      <ObjectType>8</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
    <Permission>
      <ObjectID>50120</ObjectID>
      <ObjectType>5</ObjectType>
      <ReadPermission>0</ReadPermission>
      <InsertPermission>0</InsertPermission>
      <ModifyPermission>0</ModifyPermission>
      <DeletePermission>0</DeletePermission>
      <ExecutePermission>1</ExecutePermission>
      <SecurityFilter />
    </Permission>
  </PermissionSet>
</PermissionSets>

Build the Package & Deploy.

Permission Set will also get deployed along with Extension.

You can Assign this Permission Set to respective Users.

Now you are good to proceed with Next Step.

You can jump to Next Step from here.

Advertisement
AL, AL Table Proxy Generator Tool, altpgen, Business Central, Dataverse, Extension, Generator, Integration, Page, Proxy, Table, Tool

Using AL Table Proxy Generator Tool to create Integration Table(s) in Business Central for the Dataverse table

This is the Sixth post in the series. If you want to go to previous post click here.

From the series of steps this post is dedicated to Step-5:

As a fifth Step we will Create Integration Table(s) in Business Central for the Dataverse table created in Step-4

When table(s) are present in Microsoft Dataverse, but not in Business Central, this tool can be run to generate integration or proxy table(s) for the specified table(s).

The AL Table Proxy Generator tool you can find in AL Language extension by name altpgen.exe in the equivalent folder [C:\Users\ashwi\.vscode\extensions\ms-dynamics-smb.al-7.4.502459\bin\]

Run PowerShell ISE as Administrator

Change to folder containing altpgen.exe

Above command should be single line, I have break for clarity of parameters. Below is the sample command.

.\altpgen -project:"C:\Userdata\AL Project\DataVerseIntegration" -packagecachepath:"C:\Userdata\AL Project\DataVerseIntegration\packagecachepath" -serviceuri:"https://xxxxxxxxxxx.crm8.dynamics.com/" -entities:cr95d_prospects -baseid:50125 -tabletype:CDS

When you run the command, it will ask for authentication, provide and continue.

Once you Accept the Permissions request, you can see the output of the command.

Don’t worry for warnings, Your AL file will be generated in specified folder.

Below is the sample of generated file, it is suggested to generate this file using the tool, don’t try to create manually.

table 50126 "CDS cr95d_Prospects"
{
  ExternalName = 'cr95d_prospects';
  TableType = CDS;
  Description = '';

  fields
  {
    field(1;cr95d_ProspectsId;GUID)
    {
      ExternalName = 'cr95d_prospectsid';
      ExternalType = 'Uniqueidentifier';
      ExternalAccess = Insert;
      Description = 'Unique identifier for entity instances';
      Caption = 'Prospects';
    }
    field(2;CreatedOn;Datetime)
    {
      ExternalName = 'createdon';
      ExternalType = 'DateTime';
      ExternalAccess = Read;
      Description = 'Date and time when the record was created.';
      Caption = 'Created On';
    }
    field(4;ModifiedOn;Datetime)
    {
      ExternalName = 'modifiedon';
      ExternalType = 'DateTime';
      ExternalAccess = Read;
      Description = 'Date and time when the record was modified.';
      Caption = 'Modified On';
    }
    field(24;statecode;Option)
    {
      ExternalName = 'statecode';
      ExternalType = 'State';
      ExternalAccess = Modify;
      Description = 'Status of the Prospects';
      Caption = 'Status';
      InitValue = " ";
      OptionMembers = " ", Active, Inactive;
      OptionOrdinalValues = -1, 0, 1;
    }
    field(26;statuscode;Option)
    {
      ExternalName = 'statuscode';
      ExternalType = 'Status';
      Description = 'Reason for the status of the Prospects';
      Caption = 'Status Reason';
      InitValue = " ";
      OptionMembers = " ", Active, Inactive;
      OptionOrdinalValues = -1, 1, 2;
    }
    field(28;VersionNumber;BigInteger)
    {
      ExternalName = 'versionnumber';
      ExternalType = 'BigInt';
      ExternalAccess = Read;
      Description = 'Version Number';
      Caption = 'Version Number';
    }
    field(29;ImportSequenceNumber;Integer)
    {
      ExternalName = 'importsequencenumber';
      ExternalType = 'Integer';
      ExternalAccess = Insert;
      Description = 'Sequence number of the import that created this record.';
      Caption = 'Import Sequence Number';
    }
    field(30;OverriddenCreatedOn;Date)
    {
      ExternalName = 'overriddencreatedon';
      ExternalType = 'DateTime';
      ExternalAccess = Insert;
      Description = 'Date and time that the record was migrated.';
      Caption = 'Record Created On';
    }
    field(31;TimeZoneRuleVersionNumber;Integer)
    {
      ExternalName = 'timezoneruleversionnumber';
      ExternalType = 'Integer';
      Description = 'For internal use only.';
      Caption = 'Time Zone Rule Version Number';
    }
    field(32;UTCConversionTimeZoneCode;Integer)
    {
      ExternalName = 'utcconversiontimezonecode';
      ExternalType = 'Integer';
      Description = 'Time zone code that was in use when the record was created.';
      Caption = 'UTC Conversion Time Zone Code';
    }
    field(33;cr95d_ProspectName;Text[100])
    {
      ExternalName = 'cr95d_prospectname';
      ExternalType = 'String';
      Description = 'Required name field';
      Caption = 'Prospect Name';
    }
    field(34;cr95d_ContractAmount;Decimal)
    {
      ExternalName = 'cr95d_contractamount';
      ExternalType = 'Money';
      Description = '';
      Caption = 'Contract Amount';
    }
    field(37;ExchangeRate;Decimal)
    {
      ExternalName = 'exchangerate';
      ExternalType = 'Decimal';
      ExternalAccess = Read;
      Description = 'Exchange rate for the currency associated with the entity with respect to the base currency.';
      Caption = 'Exchange Rate';
    }
    field(38;cr95d_contractamount_Base;Decimal)
    {
      ExternalName = 'cr95d_contractamount_base';
      ExternalType = 'Money';
      ExternalAccess = Read;
      Description = 'Value of the Contract Amount in base currency.';
      Caption = 'Contract Amount (Base)';
    }
    field(39;cr95d_Probability;Integer)
    {
      ExternalName = 'cr95d_probability';
      ExternalType = 'Integer';
      Description = '';
      Caption = 'Probability';
    }
    field(40;cr95d_Stage;Option)
    {
      ExternalName = 'cr95d_stage';
      ExternalType = 'Picklist';
      Description = '';
      Caption = 'Stage';
      InitValue = Lead;
      OptionMembers = Lead, Opportunity, Won, Lost;
      OptionOrdinalValues = 256080000, 256080001, 256080002, 256080003;
    }
    field(42;cr95d_ForcastedRevenue;Decimal)
    {
      ExternalName = 'cr95d_forcastedrevenue';
      ExternalType = 'Money';
      Description = '';
      Caption = 'Forcasted Revenue';
    }
    field(43;cr95d_forcastedrevenue_Base;Decimal)
    {
      ExternalName = 'cr95d_forcastedrevenue_base';
      ExternalType = 'Money';
      ExternalAccess = Read;
      Description = 'Value of the Forcasted Revenue in base currency.';
      Caption = 'Forcasted Revenue (Base)';
    }
  }
  keys
  {
    key(PK;cr95d_ProspectsId)
    {
      Clustered = true;
    }
    key(Name;cr95d_ProspectName)
    {
    }
  }
  fieldgroups
  {
    fieldgroup(DropDown;cr95d_ProspectName)
    {
    }
  }
}

Create a Page for above table

page 50122 "CDS Prospect List"
{
    Caption = 'CDS Prospect List';
    PageType = List;
    SourceTable = "CDS cr95d_Prospects";
    Editable = false;
    ApplicationArea = All;
    UsageCategory = Lists;
    RefreshOnActivate = true;

    layout
    {
        area(Content)
        {
            repeater(Group)
            {
                field("No."; Rec.cr95d_ProspectsId)
                {
                    Caption = 'No.';
                    ApplicationArea = All;
                }
                field(Name; Rec.cr95d_ProspectName)
                {
                    Caption = 'Name';
                    ApplicationArea = All;
                }
                field(Stage; Rec.cr95d_Stage)
                {
                    Caption = 'Stage';
                    ApplicationArea = All;
                }
                field("Probability"; Rec.cr95d_Probability)
                {
                    Caption = 'Probability';
                    ApplicationArea = All;
                }
                field("Contract Amount"; Rec.cr95d_ContractAmount)
                {
                    Caption = 'Contract Amount';
                    ApplicationArea = All;
                }
                field("Contract Amount (Base)"; Rec.cr95d_contractamount_Base)
                {
                    Caption = 'Contract Amount (Base)';
                    ApplicationArea = All;
                }
                field("Forecast Revenue"; Rec.cr95d_ForcastedRevenue)
                {
                    Caption = 'Forecast Revenue';
                    ApplicationArea = All;
                }
                field("Forecast Revenue (Base)"; Rec.cr95d_forcastedrevenue_Base)
                {
                    Caption = 'Forecast Revenue (Base)';
                    ApplicationArea = All;
                }
                field("Exchange Rate"; Rec.ExchangeRate)
                {
                    Caption = 'Exchange Rate';
                    ApplicationArea = All;
                }
            }
        }
    }
}

You can read more about AL Table Proxy Generator Tool from Microsoft docs

AL Table Proxy Generator

Now you are good to proceed with Next Step.

You can jump to Next Step from here.

AL, Business Central, Dataverse, Enum, Extension, Integration, Page, Table

Create Custom table & page in Business Central

This is the Fourth post in the series. If you want to go to previous post click here.

From the series of steps this post is dedicated to Step-3:

As a third Step we will Create New Table(s) and Page(s) in Business Central

Below are the AL code for Prospect table, Prospect card page & Prospect list page that will be created in Business Central via Extension, used for Integration with Dataverse.

Table in BC to Integrate from Dataverse

table 50120 "Prospect"
{
    DataClassification = ToBeClassified;
    DrillDownPageID = "Prospects";
    fields
    {
        field(1; "No."; Code[20])
        {
            DataClassification = ToBeClassified;
        }
        field(2; "Name"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        field(5; "Probability"; Integer)
        {
            DataClassification = ToBeClassified;
        }
        field(6; "Contract Amount"; Decimal)
        {
            DataClassification = ToBeClassified;
        }
        field(7; "Contract Amount (Base)"; Decimal)
        {
            DataClassification = ToBeClassified;
        }
        field(8; "Stage"; Enum "Stage Type")
        {
            DataClassification = ToBeClassified;
        }
        field(11; "Forecast Revenue"; Decimal)
        {
            DataClassification = ToBeClassified;
        }
        field(12; "Forecast Revenue (Base)"; Decimal)
        {
            DataClassification = ToBeClassified;
        }
    }

    keys
    {
        key(key1; Name)
        {
            Clustered = true;
        }
    }
}

Card Page for above Table

page 50121 "Prospect Card"
{
    Caption = 'Prospect Card';
    PageType = Card;
    UsageCategory = Administration;
    SourceTable = "Prospect";

    layout
    {
        area(Content)
        {
            group(General)
            {
                field("Name"; Rec."Name")
                {
                    ApplicationArea = All;
                }
                field(Probability; Rec.Probability)
                {
                    ApplicationArea = All;
                }
                field(Stage; Rec.Stage)
                {
                    ApplicationArea = All;
                }
            }

            group(Details)
            {
                field("Contract Amount"; Rec."Contract Amount")
                {
                    ApplicationArea = All;
                }
                field("Contract Amount (Base)"; Rec."Contract Amount (Base)")
                {
                    ApplicationArea = All;
                }
                field("Forecast Revenue"; Rec."Forecast Revenue")
                {
                    ApplicationArea = All;
                }
                field("Forcast Revenu (Base)"; Rec."Forecast Revenue (Base)")
                {
                    ApplicationArea = All;
                }
            }
        }
    }
}

List Page for above Table

page 50120 Prospects
{
    PageType = List;
    ApplicationArea = All;
    UsageCategory = Lists;
    SourceTable = Prospect;
    Caption = 'Prospect List';
    CardPageId = "Prospect Card";
    Editable = false;

    layout
    {
        area(Content)
        {
            repeater(GroupName)
            {
                field(Name; Rec.Name)
                {
                    ApplicationArea = All;

                }
                field(Probability; Rec.Probability)
                {
                    ApplicationArea = All;

                }
                field("Contract Amount"; Rec."Contract Amount")
                {
                    ApplicationArea = All;

                }
                field("Contract Amount (Base)"; Rec."Contract Amount (Base)")
                {
                    ApplicationArea = All;

                }
                field(Stage; Rec.Stage)
                {
                    ApplicationArea = All;

                }
                field("Forcast Revenue"; Rec."Forecast Revenue")
                {
                    ApplicationArea = All;

                }
                field("Forcast Revenue (Base)"; Rec."Forecast Revenue (Base)")
                {
                    ApplicationArea = All;

                }
            }
        }
    }
}

Enum for field Stage

enum 50120 "Stage Type"
{
    Extensible = true;
    AssignmentCompatibility = true;

    value(0; "Lead") { Caption = 'Lead'; }
    value(1; "Opportunity") { Caption = 'Opportunity'; }
    value(2; "Won") { Caption = 'Won'; }
    value(3; "Lost") { Caption = 'Lost'; }
}

Now you are good to proceed with Next Step.

You can jump to Next Step from here.

AL Table Proxy Generator Tool, Assisted Setup, Business Central, CDS, Common Data Services, Coupling, Custom Tables, Dataverse, Deploy, Dynamics 365 Sales, Integration, Mappings, Package, Permissions, Power Apps, Scheduling, Synchronize, Testing

Integration in Business Central with Dataverse/ Common Data Services/ Dynamics 365 Sales/ Power Apps

In this post I will discuss about how we can Synchronize data to Custom Tables using Dataverse.

This post is divided in series of small posts, one post for each involved step.

You follow each post link in sequence and at end we will achieve the final Goal set in starting of this post. 

This post will walkthrough setting up an integration between a Custom table Prospects in Business Central and a Custom table Prospects in Microsoft Dataverse.

One thing important keep in mind while doing all the steps we need to use the Admin login you used to setup these environments.

Also, the Base Currency of Business Central & Dataverse Environment should be same else you will run into issue.

If the currencies of Business Central and Dataverse do not match, similar message will be displayed.

LCY Code XXX does not match ISO Currency Code XXX of the Dataverse base currency.

The Base Currency defined for Dataverse after setup is not possible to change however you can match it in Business Central by changing LCY Code in General Ledger Setup.

Let’s start with introduction to environment we are going to use, throughout the process and steps described below.

Introduction to Environment:

Before we start with the Steps Involved, let me introduce with the environment which I am going to use in this walkthrough. 

Business Central Environment:

Dynamics 365 Sale Environment:

Setup required to Connect with external system:

You can find below options in Business Central Assisted Setup.

The following are the Steps we will follow:

Follow each step above in same sequence.

For more detailed insight refer to below Microsoft Documents:

Customizing an Integration with Microsoft Dataverse

AL Table Proxy Generator

Scheduling a Synchronization between Business Central and Dataverse

Hope you enjoyed the learning by example. Wait for next post, will be back soon.

See you in next post soon with similar kind of stuffs.

Till then keep Exploring, learning and sharing with others.

AL, BC18, Business Central, Code, Codeunit, Combinations, Development Tips, Dimension, Dynamics 365, Environment, Events, Extension, Extension Package, How To, Online, Page, Sandbox, Subscription, Table, Tip & Tricks, VS Code

Walkthrough Extension Development in Online Sandbox – Business Central

I have my Sandbox environment as below:

Details of the Sandbox as below:

Connecting VS code to above environment.

When you try to Publish the extension, it will ask you to authenticate.

Copy the Link and open in the browser and paste the code in the box as shown below.

Next it will ask for your Online Instance User Id & Password provide it and on confirmation close the page. It will start deploying the extension.

In this walkthrough I am using below scenario:

Requirement is we need to be able to define some code for dimension combinations. Let me say it will be Sales Code, you can choose name of your choice, this is not Salesperson code.

I am assuming these dimensions will follow the sequence as defined on my General Ledger Setup as below:

On Sales Order & Invoice user should be able to select this Sales Code and dimensions should be populated on order accordingly.

For tracking purpose this Sales Code should flow to Posted Sales Invoice and Customer Ledger.

So, Let’s Start with the development process:

Step-1 We will Create the Table

Here is the code for LookupDimValue Function, it will set filter for Dimension Code on Dimension Value table, as per the Dimension No passed. (1 is for Shortcut Dimension defined on General Ledger Setup, similarly for other 8 dimensions)

Step-2 Next, we will create the Page for this Setup

Step-3 Next, we will add the Sales Code field to all required Tables & Pages

Here is the code for AddDim Function. It is assumed that only combination provided in Sales Code Setup will be used. If you have defined Default dimensions or Combinations, those need to be preserved else this code will overwrite them. You will have to find the Data Set Entry, store them in temporary table used in below code and then add all the dimensions from the setup.

When you Select Sales Code on the Order or Invoice it will populate all the dimensions defined in the Setup.

Code for other Tables & Pages

Step-4 Next, we need to take care to flow the Sales Code to the Ledger and Posted documents.

For posted documents we need not to worry it will flow automatically provided we have defined the fields on same Id.

However, for ledger we will require to use Events to pass the data to their destinations. In this case we are only passing to Customer Ledger Entry. For this we will create a Codeunit.

To Add Event Subscriptions, Use the new Shift+Alt+E shortcut in the AL code editor to invoke a list of all events.

Search for the even you are looking for.

When pressing Enter to select an event entry, an event subscriber for the event will be inserted at the cursor position in the active AL code editor window.

Here is the Codeunit Code:

This is not the final code; much more can be done or need to be done before it can be delivered to customer for their use. Purpose of this walkthrough was to demo the way we can customize the solution using extensions and publishing to Online tenant in Sandbox.

Hope you enjoyed the information. Will come with more similar information in my next posts. Till then keep exploring, learning and sharing your knowledge with others.

Remain safe, take care of your loved ones, put your mask, maintain safe distance and don’t forget to get vaccinated.

AL, BC14, BC15, BC16, BC17, Business Central, Codeunit, Development Tips, Enum, Extension, How To, Install, JSON, SOAP, Tip & Tricks, V1, V2, Visual Studio Code, Wave 1, Wave 2, Web Client, Web Services, XML

Update Tracking Line, Post Shipment using Web Services in Business Central

Hi, today I will discuss Web Service with below requirement. You can check other earlier post on this topic using search on right side of this blog page.

I got one request on topic from one of my customer cum blog follower, case study is as follows:

a) Will update Qty to Ship on document using Web Service from other application

b) Update Tracking Line for the Shipment using Web Service from other application

c) Post the Shipment using Web Service from other application

To get this we will create an Extension using VS Code which will have:

a) Codeunit with some functions which will be called using Web Service

b) A XML file to automatically expose above codeunit upon publishing this extension

Let us start how to achieve above requirement:

I have created this in BC16, will be same for other versions too.

Creating a AL Project:

Update your app.json & launch.json as per your environment, authentication, dependencies, port etc.

Creating a Codeunit: (TrackingCodeWS.al)

This function will be used to update “Qty. to Ship” on Sales Line

InitLot function as name suggests.

GetNextEntryNo function as name suggests.

It will depend on how you design your codeunit, you may require or not depends on logic how you use them.

AssignLotSalesLine is function which fills the lot details to temp Reservation Entry Table.

CreateReservationEntrySalesLine is the main function which actually makes your Tracking Lines and assign to Sales Line as per information filled in TempReservationEntry table in above function.

PostSalesOrder function is used for posting your Shipment.

Creating XML file to Publish Web Service

This XML file will ensure publishing of Web Service on Install of the Extension. You can directly make entry to Web Service table but benefit of using XML is when to Uninstall your extension the Web Service too will be removed, else if entry made to table you will have to take care to same yourself.

After Install of Extension, your Web Service is automatically Published.

Consume Web Service from Visual Studio

Below is the C# code to consume Web Service created above, you can modify code as per your requirement.

In above code we added Service Reference to Web Service and called functions created in Codeunit.

You can see earlier posts for step wise instruction how to add Web Reference to the Web Service in Visual Studio.

UpdateQtyToShipSalesLine:

Here “1” is used for Document Type = Order,”1008″ is my order no, 10000 is the Line No., 2 is the Quantity to Ship.

AssignLotSalesLine:

“L0001” & “L0002” is my Lot No, Serial No. is blank in this case, 1 is the Quantity, last three parameter is same as in above function call.

PostSalesOrder:

First 2 Parameter is same as above function call Document Type & Order No, third parameter is Ship = TRUE, Fourth Parameter is Invoice = FALSE.

Conclusion

This post gives you overall Idea how you can use Web Service to handle Sales Document from Web Service, you can make required modification to achieve exactly as per your requirement.

AL, Array, BC14, BC17, Business Central, Collection, Development Tips, Dictionary, Dynamics 365, How To, Information, List, Modern Development Tool, on-premises, Tip & Tricks, Visual Studio Code, Wave 1, Wave 2, Web Client

Working with Collections

Today we will learn three types of collections supported by AL.

A collection is a complex type that contains multiple values in one variable.

You can’t have values with different types in the same collection. For example, you can’t add date values in a collection that only allows integer values.

The three types of collections that AL supports are:

  • Array
  • List
  • Dictionary

We will discuss about each type of collections in this post with examples.

Let’s start with most familiar collection we have used with old versions of Navision too, yes you are right, I am talking about Arrays.

Arrays

Arrays are complex variables that contain a group of values with the same data type.

An array holds multiple values, and these values are stored in the elements of the array. You can access these values by using the index, which can also be a value that is stored in another variable. With this design, you can create a loop where you increment a certain variable to loop through every element in an array.

By using the Dimension property, you can define how many dimensions that the array will hold.

When creating a variable of an array data type, you first need to define how many elements that you’ll have in the array. The most commonly used array is the one-dimensional array, which is a list of elements with the same data type.

You can represent an array as a row of values.

To create an array, use the following code:

SalesAmount: array[10] of Integer;

To access an element in an array, use the array element syntax:

SalesAmount[5] := 0;

Unlike other programming languages array index don’t starts with 0 rather with 1. In above example first element will be 1 and last 10.

Having only one element between the square brackets indicates that you are using a one-dimensional array. If you want to have a multi-dimensional array, use a comma-separated list between the brackets, as follows:

SalesAmount: array[6,9] of Integer;

To access an element in an array, use the array element syntax:

SalesAmount[5,3] := 0;

Lists

The List data type can be compared with an array. The List type can only be used with fundamental types and represents a strongly typed list of values that can be accessed by index.

Therefore, you can have a List type of [Integer], but you cannot have a List type of [Blob].

List data type doesn’t require you to define how many elements you want to store up front (while an Array data type does).

The List data type has some methods that are used frequently. The methods that are available for a List data type will discuss in a later post.

To create a list, use the following code:

CustomerNames: List of [Text];

To access an element in a list, use the following methods:

To store/add values to list

CustomerNames.Add(‘KSD Consultancy’);

CustomerNames.Add(‘Microsoft India’);

CustomerNames.Add(‘Ashwini Tripathi’);

To retrive values from list

CustomerNames.Get(1);

Dictionary

The Dictionary data type represents a collection of keys and values.

Every key that you create in this dictionary must be unique. The main benefit is that you can immediately get the value for a specific key.

The value can be a type, but it can also be a List or another Dictionary data type.

Blow code sequence will give you idea how to use dictionary data type:

//Declaring List

CustomerNamesIN: List of [Text];

CustomerNamesUS: List of [Text];

CustomerNamesCA: List of [Text];

//Declaring Dictionary

CountryWiseCustomer: Dictionary of [Code[20], List of [Text]];

//Assigning values to List

CustomerNamesIN.Add(‘KSD Consultancy’);

CustomerNamesIN.Add(‘Microsoft India’);

CustomerNamesIn.Add(‘Ashwini Tripathi’);

CustomerNamesUS.Add(‘Paul’);

CustomerNamesUS.Add(‘Linda’);

CustomerNamesCA.Add(‘Eddy’);

CustomerNamesCA.Add(‘Mark’);

//Assigning values to Dictionary

CountryWiseCustomer.Add(‘IN’,CustomerNamesIN);

CountryWiseCustomer.Add(‘US’,CustomerNamesUS);

CountryWiseCustomer.Add(‘CA’,CustomerNamesCA);

//Retrieving value from Dictionary

CountryWiseCustomer.Get(‘IN’).Get(1);

Here is the complete code:

Created new codeunit and declared variables & procedures to manipulate values in Collections.

Added Code to call procedures defined in codeunit, to assign and retrieve values from collections.

Now its time to check output of above code.

Hope you get idea how to work with Collections, you may find more posts in coming days where we may discuss about methods available for collection.

AL, Automated Testing, Business Central, Development Tips, Dynamics 365, Extension Package, How To, Information, Modern Development Tool, Test Codeunit, Tip & Tricks, V2, Visual Studio Code

Automated Testing in Business Central

Testing is the essential part of the software development process and Cover User Scenarios.

Developers take care of their unit tests and perhaps, some wider coverage when they deliver a finished module. When developer tests the software he only tests scenarios for which he have done development.

In manual testing, since there are usually only humans involved, there will without doubt be discrepancies in the burden that test are conducted. There’s is always the trade-off between whether or not to conduct a full test scenarios for every delivery. In most scenarios tests are performed to areas of application, those are relevant for the current release. Like why should you repeat the purchasing scenarios if you only made a change to the sales process for example?

Automated testing brings a level of insistency and repeatability to testing that is impossible to achieve with just humans. By using a tool that facilitates automated testing, you can run as many test, as many times, as you want with a guarantee that each and every test will run exactly the same way as the first time. You can actually prove that a change in the sales process will not affect the purchasing process.

The key to successful automated testing is that you can link test scenarios to user scenarios. To make your development process itself test-based, by writing proper test at the start of the development process will give you clear and concrete requirements that the software has to meet.

Repeatability of running test scenarios is another key ingredient of automated testing. Manual testing can be very tedious task that can cause a human tester to lose focus. Added project pressure can add to the temptation for tester to skip the unimportant pieces of the test scenarios. How many times do you have to make sure that you can’t enter text string in an amount field for example?

Automated testing is a predefined set of Instructions that always run, no matter what time, no matter how eager the project manager wants the results, no matter how hungry you are, the test scenario is defined and it will execute every instruction every time that the test runs.

It will run exactly the same manner each and every time. You can spin as many sessions you need and simulate real load test. You can potentially scale this up to hundreds or even thousands of users at the same time and really test the limits of your software’s capabilities. Even in larger organizations it will never be possible in a manual test situation.

Manual testing is great to prove that a new piece of software meets the requirements. But what is not always clear is whether a new change in the software has had any adverse effects on existing functionality in other areas. Whereas in case of automated testing provides the capability to prove that all test scenarios can still give you the same test results over time, whenever you make any changes to any part of the software. Since you can schedule automated tests, you can run a full system test overnight or weekend, when you come back at your desk in the next morning you can look at the outcome of the latest test run and focus on just the ones that failed.

Test that are included in the standard business central test toolkit, cover the entire application. You can run the full length of thousands of those test in a matter of hours. So, combined with a build script, you can automate the creation of a new tenant, implement your compiled app, run selected tests and then, evaluate the results in a fraction of the time, which it would take a team of manual testers to do the same thing in hours. Automated testing provides the capability to run a full test set every single day or multiple times a day. If you have that capability, why not use it?

You can organize your development process to include daily build process and include a full sweep of the entire set of tests, and almost guarantee a 100 percent success when you are ready to deliver your software.

Those working on AppSource apps, will not have a choice on matter. Automated testing is mandatory for your app source submission.

Conclusion best way to do testing will be take a fresh demo database of BC, install your app and test the user scenario. If you need to prepare any data is necessary to successfully complete the user scenarios or the test scenarios, the creation of that data should be part of the installation process of your app, and or your test app. Most important feature should be included is the ability to run them in a non-super role, it should not be mandatory to have super rights in order to use your app. Make sure you include the test for non-super users as well.

Oh!! Today lots of lecture. Let’s see how we can implement this, although writing test scripts is not a easy task, require lots of efforts to cover all scenarios and knowing the system well in advance, with clear set of inputs and outputs, else even you pass test scenario chances to fail in real word cannot be avoided.

Below are the steps we follow to create an automated test script. Below is not the full and final, it is just an idea how we can implement this, rest you have to use your experience and skills to complete as per your requirement and project need.

Not compulsory but it will be better if we can use fresh database for this task. We will have only our Extension on which we are going to run this Automated Test and the Extension which we are creating in this post for Auto Test.

Step – 1 : Nav/BC Preparation

If not already imported you need to import Set of objects to enable automated testing. You can find them on installation disk under TestToolKit folder.

tcu001

If creating a Docker Container use option –includeTestToolkit in the new NavContainer Cmdlet.

Once you are done now you can run your Test Tool

tcu002

tcu003

Hold on, we will come to this later in below post.

Step – 2 : VS Code Project Preparation

Create a New project, and add Folder Structure to arrange your files.

You can find steps in this post : Bare Minimum Steps to Start with fresh Extension Project for Business Central

We need to Specify test target as a dependency. For this it is compulsory to have the apps symbols file to make this work. Install your Extension on this database if not already deployed.

We need to import symbols for the Test Framework as well. So need to specify ‘test’ settings to the app.json file of this project. Specify minimum supported value e.g. 12.0.0.0

Once these two settings are done, now when you hit Download Symbols it will include the Symbols for your Extension and Test Toolkit Objects.

tcu004

Now you can see 2 additional package symbol files are downloaded.

  1. KSD Consultancy_MyFirstExtensionProject_1.0.0.0.app
  2. Microsoft_Test_13.0.24209.0.app

And 2 std. symbol file that gets included when you create any new Extension Project.

Step – 3 : Writing Test Codeunits

We will create a codeunit of Subtype = ‘Test

Test procedures are decorated with [Test] attribute

Your OnRun will execute first, followed by other all test procedures.

You can use [TransactionModel] attribute to specify each test procedure is in a separate database transaction.

The output will be Success or Failure.

Failure is any error that is raised by the test code or from the code which is being tested. In either case Other Test procedures will still continue.

Other Features are Test Pages and UI Handlers, we will discuss on same in some other similar post.

AssertError statement is like if I do this error should come, it happens then your test is Success. In this case Failure is actually Success as you knowingly created error.

As I told earlier also this is very complicated area, to write Test Scripts, but if you start practicing from small stuffs eventually you will learn and will able to write a good Test Scripts. You can check out other standard Test Codeunits and update your knowledge how you can write your own Test Scripts.

My sample Test Codeunit looks something like below, it is just for idea in real scenario there should be lots more.

tcu005

Step – 4 : Deploy & Run the Test App

Publish your Test App.

Go to Extension Management

tcu006

You will find 2 Extension, The Initial Extension which we created in earlier posts and the Extension we just deployed.

Now open the Test Toolkit Page – 130401

Click on Get Test Codeunits function then Select Test Codeunits

tcu007

Now Select the Codeunit we just created.

tcu008

You can select other Codeunits as per the requirement, in my case I am just going to select my Codeunit which we created in this post.

tcu009

This will list all the functions available in the Test Codeunit.

Now you can select Run all or Run Selected. To test your App, I will select Run All.

tcu010

Here is the final output of test result

tcu011

Hope you will agree the test we performed, same if done manually no one can test the same in 6 seconds as this did. And we can perform as many times, and any time.

Once your Test Codeunit in place whenever you make changes to app, you can just run the test and verify that any changes you made have not impacted the existing functionality in any manner.

To save the time in testing, you have to pay in other way in creating the test codeunit as it is not that easy to cover every user scenario in your test codeunit and will require lots of efforts.

But when you are working for App Source you have no choice, you will have to do it.

Today the post got bit longer, but this topic is very complicated and require explanation. Hope you got the starting point from this and will put your efforts to reach to your required conclusion, take help of existing codeunit, nothing will be better than those to learn how Microsoft themselves implements it.

See you again with some more topics, and if get some extra time will try to add more to this post as a second part to this post. Fact is one post is not sufficient for such a huge topic.

Till then keep exploring and learning and take care of yourself.

AL, API, Business Central, Control Add-In, Development Tips, Extension Package, How To, Information, Java Script, jQuery, JSON, Modern Development Tool, Style Sheet, Tip & Tricks, V2, Visual Studio Code, Web Client

Control Add-In in Business Central

Today I will discuss about how we can create control add-in using VS Code & Extensions in Business Central.

We can create a control add-in the same way we created pages or code units.  In Visual Studio we can use the code snippet T control add-in to generate a new control add-in.

It will better to create a fresh Extension Project in VS Code for control add in.

Step – 1 : Preparation

Create a New project, and add Folder Structure to arrange your files.

You can find steps in this post : Bare Minimum Steps to Start with fresh Extension Project for Business Central

I will create below Folder:

  1. ControlAddIn
  2. Images
  3. JsScript
  4. Page
  5. StyleSheet

Step – 2 : Create Control Add-In

In control add-in folder I’m going to create a new control add-in.  So new file.

addin-1

Use the snippet, T control add-in, to create a control add-in.

addin-2

Give the name to your control add-in in my example I have used “WeatherControlAddIn

A control add-in works with JavaScript files that can execute some code.  The scripts property is used to reference these JavaScript files.  They can be local files or references to external files over http or HTTPS.  A very commonly used JavaScript library is jQuery.  JQuery makes it a lot easier to write JavaScript code and it reduces the lines of code significantly. In our case any such files will be saved in JsScripts folder under Extension-> Objects Folder as setup above. One file we will create for StartupScript as Start.js.

Now let’s include jQuery.  We have to download jQuery from the Internet.  So if we open our Web browser and we go to the jQuery website, we can click the download jQuery button over here.  But instead of really downloading the jQuery files, we are going to reference them online.

Open the site: https://jquery.com/

addin-3

Click on Download jQuery v3.3.1 large button as shown above.
Scroll down to find: – Microsoft CDN (Content Delivery Network)
Microsoft also has a CDN for jQuery. We take that one.
Copy the link to the latest one. Add this to our Scripts property in our control add-in.

https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js”

Use the URL of jQuery file. There’s also a property start-up script which you can use to call a special script that runs when the page where you have implemented your control add-in is loaded.  Now let’s add our start.js script over here.  So because it’s in the folder script, we have to “Objects/JsScripts/Start.js”.  Now, there’s also a recreate and a refresh script.  We are not going to use them in this demo project, so remove them. And with the images and the style sheets properties you can specify additional style to the control add-in.

Scripts = ‘https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js&#8217;;

StyleSheets = ‘Objects/StyleSheet/StyleSheet.css’;
StartupScript = ‘Objects/JsScripts/Start.js’;
Images = ‘Objects/Images/Weather.jpg” />

I am using dummy image to display on my control add-in, select your image accordingly and place it in Images folder.
We will look into StyleSheet.css and Start.js later in below post.

addin-4

This is how your WeatherControlAddIn.al should look like.

Step – 3 : Create Style Sheet

I will be adding a CSS file to this with the name StyleSheet.css.  In this CSS file I can apply some layout styles to give my control add-in a color or let it choose a certain font and so on and so on.  But remember there are some guidelines on which styles to apply.  I’m going to set my image to a width 200 pixels.  So in CSS, this is image.  Width, 200 pixels, and a margin top of 25 pixels.  And then I need to reference it in my style sheet properties.  This is ‘Objects/StyleSheet/StyleSheet.css’ and of course in the folder StyleSheet.

addin-5

You can apply your knowledge about stylesheets to decorate your add-in accordingly, for demo purpose I have just set the width and top margin of the image.

Similarly I have downloaded an image from internet related to weather and copied to Images Folder.

Now set the path of both the files in your control add-in as shown above.

Step – 4 : Create CardPart Page

Now, our control add-in will run in a CardPart.  So we have to create a page.  Let’s create a new file and call this WeatherCardPart.al.  This is a page.  So T page.  Let’s give it an ID and a name.  WeatherCardPart.  Now the source table will be customer.  And the page type is CardPart.

Your Page should look similar to below:

addin-6

We have added our ControlAddIn on the CardPart.

Next we will pass data from our Navision to the JQuery Script to process, to do so we have added a local procedure GetCustomer, remember above in control add-in we added signature of this procedure. Now it’s time to implement that function.

We have created a JsonObject to store our data and pass to Control Add-In.

This function gets called from OnAfterGetRecord trigger of the Page.

You may be wondering about function call QueryTempOfCity, this is the same function which we used in our earlier post to call API and get temperature of specified city then updated the Headline of the RC Page.

If you missed you can find that post here: Working with Headline Role Center Page and HTTP Call – Business Central

I have copied some functions from that post and changed a little bit and added to this page, it should be like below:

addin-7

This function will take City as parameter and query from API and return the current temperature of that city. This function is explained in referenced post above.

Step – 5 : Create Page Extension

CardPart runs in a factbox on a page.  So let’s create a page extension on the customer card.  So new page.  Let’s call this customercardextension.al. which extends the customer card.  Add a factbox in the factboxes, and this is a part — let’s give it a name.  WeatherCardPart.  And this is of type WeatherCardPart.  When adding a part or a factbox, then need to set the sub page link.  So don’t forget to set the sub page link and this is equal to the number equals field number.

addin-8

It should be similar to above.

Step – 6 : Create jQuery Script

Here comes the most interesting and difficult part as we are not regular Java Script programmer, but thanks to google, who is always there to help.

We will create our Start.js

You can apply your Java Scripts skill to enhance this, let us keep it simple for learning purpose.

We will extract the information send via GetCustomer function in JsonObject and display in our Control Add-In.

addin-9

You can say controlAddIn here as main outer container.

We have defined 4 sub containers and with unique id to reference further.

Now we add all this 4 sub-containers to the main container controlAddIn.

Get the values from the Navision CardPard GetCustomer function and decode the JsonObject Customer and extract value from it and assign to these 3 containers.

For 4th we have assigned the image path from Extension using special function Microsoft.Dynamics.NAV.GetImageResource

Step – 7 : Deploy and Test the Control Add-In

So now we are done with Creating of Control Add-In, deploy your extension by using command pallet, Publish you Extension.

Open the Customer Card and you should see your Control Add-In in action.

addin-10

addin-11

Tested successful. Here we come to the end of our today’s post.

Hope you liked and enjoyed learning the concept in this post.

Will come up with more such interesting concepts in my future posts.

Till then keep exploring and learning. Take Care of yourself.