Landing page or Initial Page preference change in Dynamics 365 for Finance and operations

Scenario: Sometimes users dont want to see the dashboard or workspace whenever they login to dynamics 365 for finance and operations. They want to directly go to Employee self service(for employees) or system administration (for administrators) page.

Solution:  Below screenshots will show how you can set this option for any employee.

  1. Go to users options on the top right.
  2. Click on preference tab on the left side
  3. select the initial page for the user

Screen Shot 2019-09-12 at 12.01.18 PM.png

 

Screen Shot 2019-09-12 at 12.05.05 PM.png

 

 

Read Data from Excel file – Dynamics 365 for Finance and Operations – Excel Operations X++

Scenario : upload/Import the data using excel

Solution: Below is the code snippet to use for the data upload using excel

Note: SysExcel classes has been depreciated in the dynamics 365

Microsoft office interop reference is used in the dynamics 365. You can find that in the reference node of solution explorer.

 

Code :

 

using System.IO;

using OfficeOpenXml;

using OfficeOpenXml.ExcelPackage;

using OfficeOpenXml.ExcelRange;

class BEUploadExcelLeaveTransactions

{

    /// <summary>

    /// Runs the class with the specified arguments.

    /// </summary>

    /// <param name = “_args”>The specified arguments.</param>

    public static void main(Args _args)

    {

        

        System.IO.Stream            stream;

        

        FileUploadBuild             fileUploadBuild;

        DialogGroup                 dialogUploadGroup;

        FormBuildControl            formBuildControl;

        Dialog                      dialog = new Dialog(‘Import the data from the Excel’);

        dialogUploadGroup          = dialog.addGroup(‘@SYS54759’);

        formBuildControl        = dialog.formBuildDesign().control(dialogUploadGroup.name());

        fileUploadBuild         = formBuildControl.addControlEx(classstr(FileUpload), ‘Upload’);

        fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);

        fileUploadBuild.fileTypesAccepted(‘.xlsx’);

        if (dialog.run() && dialog.closedOk())

        {

            Fileupload fileUploadControl     = dialog.formRun().control(dialog.formRun().controlId(‘Upload’));

            FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();

            if (fileUploadResult != null && fileUploadResult.getUploadStatus())

            {

                stream = fileUploadResult.openResult();

                using (ExcelPackage ePackage = new ExcelPackage(stream))

                {

                    int                         rowCount, i;

                    ePackage.Load(stream);

                    ExcelWorksheet  eWorksheet   = ePackage.get_Workbook().get_Worksheets().get_Item(1);

                    OfficeOpenXml.ExcelRange    eRange       = eWorksheet.Cells;

                    rowCount                  = eWorksheet.Dimension.End.Row – eWorksheet.Dimension.Start.Row + 1;

                    for (i = 2; i<= rowCount; i++)

                    {

                        info(eRange.get_Item(i, 1).value);

                        info(eRange.get_Item(i, 2).value);

                    }

                }

            }

            else

            {

               throw error(‘Error here’);

            }

        }

    }

}

Models Export and Import: Dynamics 365 for Finace and Operations

Scenario:

Export model from one dev environment to another dev enviornment

Steps to perform:

  1. Export model from enviornment using command prompt
  2. Import Model in another enviornment using command prompt
  3. Resolve conflicts
  4. Complete build of models and Synchonization of Database

 

Export Model:

Export the model using utilily name ModelUtil.exe located in the below path

K:\AosService\PackagesLocalDirectory\Bin

K:\ Drive can be varrried for local VM C:\ or J:\ 

Command:

ModelUtil.exe -export -metadatastorepath= [path of the metadata 
store] -modelname=[name of the model to export] -outputpath=[path 
of folder where model file should be saved]

 

Example:

ModelUtil.exe -export -metadatastorepath= K:\AosService\PackagesLocalDirectory -modelname=D365FnOModel -outputpath=C:\Users\Userf3d496631\Desktop\US\devmodelsbackup

Screen Shot 2019-09-08 at 4.47.49 PM

 

Import model:

To install or import a model file use below code

ModelUtil.exe -import -metadatastorepath=[path of the metadata store 
where model should be imported] -file=[full path of the file to 
import]

Example:

ModelUtil.exe -Import -metadatastorepath= K:\AosService\PackagesLocalDirectory -file=C:\Users\Userf3d46296631\Desktop\US\devmodelsbackup\D365FnOModel

Screen Shot 2019-09-08 at 4.59.11 PM.png

 

Delete a Model:

If model already exists in the destination environment. Delete the model using modelutility.exe

ModelUtil.exe -delete -metadatastorepath=[path of the metadata store]
 -modelname=[name of the model to delete]

Example:

ModelUtil.exe -Delete -metadatastorepath= K:\AosService\PackagesLocalDirectory -modelName=D365FnOModel

Screen Shot 2019-09-08 at 5.02.35 PM.png

 

Resolve the conflicts after importing:

 

Screen Shot 2019-09-08 at 5.04.05 PM.png

 

Build and sycnhronize:

after resolving all the conlicts build the model(all models would be better but it will take long time) and synchronize the database

 

Single deployable package creation from customization and ISV package – Microsoft Dynamics 365 for Finance and operations

Upgrade Dynamics 365 Finance and operations environment – Third-Party ISVs(No Source code) and custom model(source code)

Scenario:

2 ISV packages(no source code)

2 Custom models(source)

Sandbox Environment is on Application release 8.0 and PU 24

Target version for sandbox environment Application release 10.0.4 and PU 28

The problem in the simple upgrade:

unable to merge 4 packages(2 ISVs, 1 custom model and 1 application release 10.0.4 ,PU28 package)

Maximum only 2 packages can be merged in the asset library.

Solution:

To create one package for ISVs and custom model, need build environment and code should be under source control

Then one package of latest application release and custom package can be merged into one package and apply to a sandbox environment to upgrade

 

Steps:

  1. Custom models source code add to source control
    1. After you install the custom model, follow these steps to add the new model to source control.
    2. Open Source Control Explorer by clicking View > Other Windows > Source Control Explorer.
    3. Navigate to the metadata folder that is mapped on this development VM, such as MyProject/Trunk/Main/Metadata.
    4. In the metadata folder, find the folder for the package that contains the new model. Right-click the package folder, and then click Add Items to Folder.
    5. In the Add to Source Control dialog box, select the Descriptor folder and the folder that has the name of the model. Some models may also contain referenced DLLs in the bin folder. If these exist you’ll need to also include the appropriate DLL files from the bin folder. Once all files have been selected, click Next.
    6. Review the items that will be added, and then, when you’re ready, click Finish.
    7. Open the Pending Changes window from the Team Explorer pane or by clicking View > Other Windows > Pending Changes.
    8. Review the changes, enter a check-in comment, and then click Check In.
  2. Add ISVs package to source control follow below steps
    1. After you install the deployable package on a development VM, follow these steps to add the package to the source control.
    2. Open Source Control Explorer by clicking View > Other Windows > Source Control Explorer.
    3. Navigate to the metadata folder that is mapped on this development VM, such as MyProject/Trunk/Main/Metadata.
    4. Right-click the Metadata folder, and then click Add Items to Folder.
    5. In the Add to Source Control dialog, double-click the folder that has the package name that you want to add to source control.
    6. Select all the folders except XppMetadata and Descriptor, if they exist, and then click Next.
    7. On the next page, on the Excluded items tab, select all files by clicking one of the files and then pressing Ctrl+A. At the bottom of the selection window, click Include item(s). When you’re ready, click Finish.
    8. Open the Pending Changes window from the Team Explorer pane or by clicking View > Other Windows > Pending Changes.
    9. Review the changes, enter a check-in comment, and then click Check-In.
  3. Deploy build environment
    1. During deployment, Build Agent Name keep the same as the build environment name
    2.  Branch Name should be a source control branch name of the project
  4. Use DevOps pipeline to create one package
    1. Click on Pipeline -> pipeline and then click on run pipelineScreen Shot 2019-09-05 at 10.52.56 AM.png
    2. Screen Shot 2019-09-05 at 10.54.29 AM.png
  5. Once pipeline is completed the one deployable package will be created on the build VM.
  6. Upload the build package on the Asset library, validate
  7. Apply on the UAT environment and production as well if all goes well.

 

Please comment if you need any clarification or you are facing some issue on any step.

Export to Excel thru code X++ – Dynamics 365 For Finance and Operations

Below code is used to export the data in the excel file using X++ code

 

using System.IO;

using OfficeOpenXml;

using OfficeOpenXml.Style;

using OfficeOpenXml.Table;

class ExportToExcel

{        

    /// <summary>

    /// Runs the class with the specified arguments.

    /// </summary>

    /// <param name = “_args”>The specified arguments.</param>

    public static void main(Args _args)

    {

       HcmWotker hcmWorker;

        MemoryStream memoryStream = new MemoryStream();

        using (var package = new ExcelPackage(memoryStream))

        {

            var currentRow = 1;

            Filename fileName = “Test.Xlsx”;

            var worksheets = package.get_Workbook().get_Worksheets();

            var CustTableWorksheet = worksheets.Add(“Export”);

            var cells = CustTableWorksheet.get_Cells();

            OfficeOpenXml.ExcelRange cell = cells.get_Item(currentRow, 1);

            System.String value = “Personnel Number”;

            cell.set_Value(value);

            cell = null;

            value = “Name”;

            cell = cells.get_Item(currentRow, 2);

            cell.set_Value(value);

            while select hcmWorker

            {

                currentRow ++;

                cell = null;

                cell = cells.get_Item(currentRow, 1);

                cell.set_Value(hcmworker.PersonnelNumber);

                cell = null;

                cell = cells.get_Item(currentRow, 2);

                cell.set_Value(hcmworker.Name());

            }

            package.Save();

            file::SendFileToUser(memoryStream, fileName);

           

        }

    }

}

Send email thru code with Report as attachment – Dynamics 365 Finance and Operations

Scenario: Send email thru X++ code with the report as attachment

Below is the code responsible for sending email thru code with the attachment

Guide lines to use below code

Just copy paste the code in the runnable class(job), perform below steps

Just replace the report contract name and paramters values

add send from and to email addresses,

Code:

//Set  variables

Filename fileName = “attFileName.pdf”; 

SrsReportRunController controller = new SrsReportRunController(); 

ReportContract contract = new ReportContract();

SRSPrintDestinationSettings settings;   

Array arrayFiles;   

System.Byte[] reportBytes = new System.Byte[0]();   

SRSProxy srsProxy;   

SRSReportRunService srsReportRunService = new SrsReportRunService();              

Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[] parameterValueArray;   

Map reportParametersMap;

SRSReportExecutionInfo executionInfo = new SRSReportExecutionInfo();

//set the report contract parameters

contract.parm1stParameter(“firstParameter value”);

contract.parm2ndtParameter(‘2ndParamter value’);

//3rd paramter

//4th paramter

//set the report controller paramters

controller.parmArgs(_args);

//set report name and desing name

controller.parmReportName(ssrsReportStr(ReportName, NewDesign));

controller.parmShowDialog(false);

controller.parmLoadFromSysLastValue(false);

controller.parmReportContract().parmRdpContract(contract);

 

// Provide printer settings

settings = controller.parmReportContract().parmPrintSettings();

settings.printMediumType(SRSPrintMediumType::File);

settings.fileName(fileName);

settings.fileFormat(SRSReportFileFormat::PDF);

 

// Below is a part of code responsible for rendering the report

        controller.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());       

controller.parmReportContract().parmReportExecutionInfo(executionInfo);

      srsReportRunService.getReportDataContract(controller.parmreportcontract().parmReportName());       

srsReportRunService.preRunReport(controller.parmreportcontract());       

reportParametersMap = srsReportRunService.createParamMapFromContract(controller.parmReportContract());       

parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);       

srsProxy = SRSProxy::constructWithConfiguration(controller.parmReportContract().parmReportServerConfig());       

// Actual rendering to byte array       

reportBytes = srsproxy.renderReportToByteArray(controller.parmreportcontract().parmreportpath(),parameterValueArray,settings.fileFormat(),settings.deviceinfo());

// You can also convert the report Bytes into an xpp BinData object if needed       

container binData;       

Binary binaryData;       

System.IO.MemoryStream mstream = new System.IO.MemoryStream(reportBytes);       

binaryData = Binary::constructFromMemoryStream(mstream);       

if(binaryData)       

{

            binData = binaryData.getContainer();     

}       

System.Byte[] binData1;       

System.IO.Stream stream1;       

// Turn the Bytes into a stream       

for(int i = 0; i < conLen(binData); i++)        

{

            binData1 = conPeek(binData,i+1);

            stream1 = new System.IO.MemoryStream(binData1);       

} 

//email sending settings

var mail = SysMailerFactory::getNonInteractiveMailer(); 

var messageBuilder = new SysMailerMessageBuilder();        

messageBuilder.reset()

                .setFrom(‘example@Email.com’) // From email address

                .addTo(‘example@email.com’) // To Email address

                .setSubject(‘Email Subject’) // Email Subject

                .setBody(‘Email Body’);        //Email Body

if (stream1 != null)       

{

//add attachment to the email

            messageBuilder.addAttachment(stream1,filename+”.pdf”);       

}

//send email

mail.sendNonInteractive(messageBuilder.getMessage());

}

Data Entity Not available on Powerapps and Power BI ,Dynamics 365 for Finance and Operations

Issue: Data Entity of Dynamics 365 for Finance and Operations is not available on power apps and Power BI

 

Casue: Data Entity of Dynamics 365 for Finance and operation will not be available if Is Public  property of Data Entity is No

 

Screen Shot 2019-08-28 at 11.32.49 AM.png

 

Resolution: Just change the Data Entity Is Public property to Yes

Override form control lookup – Dynamics 365 Finance and Operations

To overrie the string control use SysTableLookup sysTableLookup;

To override the reference group control use SysReferenceTableLookup sysReferenceTableLookup;

Below is the example of reference control

[FormControlEventHandler(formControlStr(HcmDiscussionNewDialog, HcmDiscussion_PerfPeriod), FormControlEventType::Lookup)]
public static void HcmDiscussion_PerfPeriod_OnLookup(FormControl sender, FormControlEventArgs e)
{
SysReferenceTableLookup sysReferenceTableLookup;
Query query = new Query();

sysReferenceTableLookup =SysReferenceTableLookup::newParameters(tableNum(HcmPerfPeriod),sender);
sysReferenceTableLookup.addLookupfield(fieldNum(HcmPerfPeriod,PerfPeriodId));
sysReferenceTableLookup.addLookupfield(fieldNum(HcmPerfPeriod,StartDate));
sysReferenceTableLookup.addLookupfield(fieldNum(HcmPerfPeriod,EndDate));

sysReferenceTableLookup.parmQuery(query);
sysReferenceTableLookup.performFormLookup();

//Cancel the super

FormControlCancelableSuperEventArgs ce = e as FormControlCancelableSuperEventArgs;

ce.CancelSuperCall();

}

Validation on update/Insert/delete record – Dynamics 365 for Finance and Operations

These are four events on a table-level to validate the record. This method calls during the default insert/Update method calling.

OnfinaldeleteValidation,

OnFinalUpdateValidation,

OnfinalInsertValidation,

OnfinalReadValidation .

 

Examle:

 

/// <summary>
///
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
[DataEventHandler(tableStr(HcmTopicComment), DataEventType::FinalUpdateValidation)]
public static void HcmTopicComment_onFinalUpdateValidation(Common sender, DataEventArgs e)
{
//Custom condition to validat

throw Error(‘update not allowed’);

}