Showing posts with label 365. Show all posts
Showing posts with label 365. Show all posts

Wednesday, July 24, 2024

D365 Sending Email with Customer Account Statement SSRS report as attachment using X++

D365 Sending Email with Customer Account Statement SSRS report as attachment using X++




 custTable _custTable;
              

                SysOperationQueryDataContractInfo sysOperationQueryDataContractInfo;
                SrsReportRunController reportRunController;
                CustTransListContract custTransListContract;
                SRSReportExecutionInfo reportExecutionInfo;
                SRSPrintDestinationSettings printDestinationSettings;
                SRSReportRunService srsReportRunService;
                SRSProxy srsProxy;
                QueryBuildRange qbrCustAccount;
                QueryBuildDataSource queryBuildDataSource;
                Object dataContractInfoObject;
                Map reportParametersMap;
                Map mapCustAccount;
                MapEnumerator mapEnumerator;
                Array arrayFiles;
                System.Byte[] reportBytes;
                Filename fileName;
                Args args;
                System.IO.MemoryStream memoryStream;
                System.IO.MemoryStream fileStream;
                CustParameters custParameters;
                Email toEmail;


                Map                                 templateTokens;
                str                                 emailSenderName;
                str                                 emailSenderAddr;
                str                                 emailSubject;
                str                                 emailBody;
 
                Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[]  parameterValueArray;
 
                #define.Subject("Subject")
                #define.CustAccount("CustAccount")
                #define.EmailDate("Date");
 
                custParameters          = CustParameters::find();
 
                reportRunController     = new SrsReportRunController();
                custTransListContract   = new CustTransListContract();
                reportExecutionInfo     = new SRSReportExecutionInfo();
                srsReportRunService     = new SrsReportRunService();
                reportBytes             = new System.Byte[0]();
                args                    = new Args();
                templateTokens          = new Map(Types::String, Types::String);
                var messageBuilder      = new SysMailerMessageBuilder();
 
                // custTransListContract.parmNewPage(NoYes::Yes);
                str custAccount = "10000";
                _custTable = CustTable::find(custAccount);
                if(!_custTable)
                {
                    return "No Customer found";
                }
                if(!emailAddress)
                {
                    return "No emailAddress";
                }
                fileName    = strFmt("CustomerAccountStatement_%1.pdf", _custTable.AccountNum);
 
                reportRunController.parmArgs(args);
                reportRunController.parmReportName(ssrsReportStr(CustTransList, Report));
                reportRunController.parmShowDialog(false);
                reportRunController.parmLoadFromSysLastValue(false);
                reportRunController.parmReportContract().parmRdpContract(custTransListContract);
 
                // Modify query
                mapCustAccount = reportRunController.getDataContractInfoObjects();
                mapEnumerator = mapCustAccount.getEnumerator();
 
                while (mapEnumerator.moveNext())
                {
                    dataContractInfoObject = mapEnumerator.currentValue();
 
                    if (dataContractInfoObject is SysOperationQueryDataContractInfo)
                    {
                        sysOperationQueryDataContractInfo = dataContractInfoObject;
 
                        queryBuildDataSource    = SysQuery::findOrCreateDataSource(sysOperationQueryDataContractInfo.parmQuery()
                                                                    , tableNum(CustTable));
                        qbrCustAccount          = SysQuery::findOrCreateRange(queryBuildDataSource, fieldNum(CustTable, AccountNum));
                        qbrCustAccount.value(_custTable.AccountNum);
                    }
                }
 
                printDestinationSettings = reportRunController.parmReportContract().parmPrintSettings();
                printDestinationSettings.printMediumType(SRSPrintMediumType::File);
                printDestinationSettings.fileName(fileName);
                printDestinationSettings.fileFormat(SRSReportFileFormat::PDF);
 
                reportRunController.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());
                reportRunController.parmReportContract().parmReportExecutionInfo(reportExecutionInfo);
 
                srsReportRunService.getReportDataContract(reportRunController.parmreportcontract().parmReportName());
                srsReportRunService.preRunReport(reportRunController.parmreportcontract());
 
                reportParametersMap = srsReportRunService.createParamMapFromContract(reportRunController.parmReportContract());
                parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);
 
                srsProxy        = SRSProxy::constructWithConfiguration(reportRunController.parmReportContract().parmReportServerConfig());
                reportBytes     = srsproxy.renderReportToByteArray(reportRunController.parmreportcontract().parmreportpath()
                                                    , parameterValueArray
                                                    , printDestinationSettings.fileFormat()
                                                    , printDestinationSettings.deviceinfo());
 
                memoryStream    = new System.IO.MemoryStream(reportBytes);
                memoryStream.Position = 0;
 
                fileStream      = memoryStream;
                toEmail         =  this.getCustEmail(_custTable.AccountNum);
 
      

                    emailBody = "Dear Customr, Please find attached Customer account statement till today.";
                    emailSubject = strFmt("Customer account statement for %1", _custTable.AccountNum);
                    emailSenderAddr = "msd@test.com";
                    emailSenderName = strFmt("Customer account statement for %1", _custTable.AccountNum);


                    messageBuilder.addTo(toEmail)
                        .setSubject(emailSubject)
                        .setBody(SysEmailMessage::stringExpand(emailBody, SysEmailTable::htmlEncodeParameters(templateTokens))).addCC("");
 
                 
                    messageBuilder.setFrom(emailSenderAddr , emailSenderName );
           
                    messageBuilder.addAttachment(fileStream, fileName);
 
                    SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());



public Email getCustEmail(CustAccount _custAccount)
{
    CustTable                   custTable;
    DirPartyLocation            dirPartyLocation;
    LogisticsLocation           logisticsLocation;
    LogisticsElectronicAddress  logisticsElectronicAddress;
 
    custTable = CustTable::find(_custAccount);
 
    select firstonly Location, Party from dirPartyLocation
        where dirPartyLocation.Party                        == custTable.Party
            join RecId from logisticsLocation
                where logisticsLocation.RecId               == dirPartyLocation.Location
            join Locator from logisticsElectronicAddress
                where logisticsElectronicAddress.Location   == logisticsLocation.RecId
                    && logisticsElectronicAddress.Type      == LogisticsElectronicAddressMethodType::Email
                    && logisticsElectronicAddress.IsPrimary == NoYes::Yes;
 
    return logisticsElectronicAddress.Locator;
}

Monday, November 27, 2023

D365 FO Encryption And Decryption Using A Symmetric Key(AES) using X++

 

Encryption And Decryption Using A Symmetric Key(AES) using x++

 Encryption And Decryption Using A Symmetric Key(AES) using x++.


I received a requirement to generate an XML file with encrypted data using a symmetric key. The recipients on the other side will decrypt the text using the same symmetric key. To test this, I used a dummy value such as 'RRR'.

To achieve this, I wrote the code in C# and added the resulting DLL to my project references.


C# Code:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionDecryptionUsingSymmetricKey
{
    public class AesOperation
    {
        public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);// It will convert bytes to string
        }

        public static string DecryptString(string key, string cipherText)
        {
            byte[] iv = new byte[16];
            byte[] buffer = Convert.FromBase64String(cipherText); // It will convert string to bytes
using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream memoryStream = new MemoryStream(buffer)) { using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read)) { using (StreamReader streamReader = new StreamReader((Stream)cryptoStream)) { return streamReader.ReadToEnd(); } } } } } } }



X++ Code:

b14ca5898a4e4133bbce2ea2315a1916

Using EncryptionDecryptionUsingSymmetricKey;

internal final class TestRunnableClass1
{
    public static void main(Args _args)
    {
        str key = "b65ff7654brt8799fghj4ed7892b6798";
 
        str	text = 'RRR';
 
        str encryptedString = AesOperation::EncryptString(key, text);
 
        info(encryptedString);
 
        str decryptedString = AesOperation::DecryptString(key, encryptedString);
 
        info(decryptedString);
    }
}
References   Ref1  Ref2 


Get multiple selected rows using D365 X++

 

First You need to insure that Multi Select for Button is True 





Create your extension class and add follow code below 


  [FormControlEventHandler(formControlStr(CustFreeInvoice, MultipleSelect), FormControlEventType::Clicked)]
    public static void  MultipleSelect_OnClicked(FormControl sender, FormControlEventArgs e)
    {
        MultiSelectionHelper          selectionHelper = MultiSelectionHelper::construct();
        Set                           selectedRecords = new Set(Types::Record);
        FormRun formrun                         = sender.formRun();
        CustInvoiceTable _CustInvoiceTable   = formrun.dataSource().cursor();
        CustInvoiceTable                       myTable;
     //   super();
    
        FormDataSource     _CustInvoiceTable_ds = sender.formRun().dataSource(formDataSourceStr(CustFreeInvoice,CustInvoiceTable)) as FormDataSource;
      
        selectionHelper.parmDataSource(_CustInvoiceTable_ds);
        myTable  = selectionHelper.getFirst();
 
        if (myTable.RecId)
        {
            while (myTable)
            {
                selectedRecords.add(myTable);
                info(strFmt("Selected record is %1",myTable.RecId));//Display selected record
                myTable = selectionHelper.getNext();
            }
        }
    }





Monday, November 20, 2023

D365 Solution for Cloud Dev machine show error ' The remote certificate is invalid according to the validation procedure. '

 

You are getting 'The remote certificate is invalid according to the validation procedure.'Error show with all reports and  tired Rotate SSL Certificate but not complete.




will require applying the below steps and if still the same issue after this so you will need to redeploy this environment.
  1. Navigate to Lifecycle Services.

  2. In the Shared Asset library, click the Model

  3. Download the Renew WinRM certificate folder

  4. RDP to the environment

  5. Extract the zip file to a local folder

  6. Open mmc.exe and add Certificate snap-in (Computer)

  7. Open Personal\Certificates and locate the certificate with your VMs name which should have the expiration date passed

  8. Browse to the RenewWinRMCertificate folder that was previously created from extracting the zip file

  9. Select File > Open Windows PowerShell with elevated privileges (Run as Administrator)

  10. Run .\VirtualMachine-RegenerateWinRMCertificate.ps1 from the folder

  11. Refresh the Certificates console and confirm the Certificate has been created and the expiration date is now valid. (Optional: Delete expired certificate to avoid confusion)

  12. Restart the Environment from LCS (Stop \ Start)

  13. In LCS select Maintain > Rotate secrets

  14. Select 'Rotate the SSL certificates'

How to update the WinRM SSL certificate on environments deployed in your subscription - Microsoft Dynamics 365 Blog

Rotate the expired or nearly expired SSL certificate on your subscription's one-box environments - Microsoft Dynamics 365 Blog



in case when running step number 10  (Run .\VirtualMachine-RegenerateWinRMCertificate.ps1 from the folder ) and show below error 


1: Configure Network Security Rules>Go to Network Security Group of the Azure VM and change 'powershell-remote-rule' from Deny to Allow (this is just temporary; we will change it back after completing the rotation). 

Then run script It should work fine.




Sunday, March 19, 2023

D365 F&O LCS Generate SAS link to Download FASTER large bacpac file

 

We face problem that our backup .bacpac is become more than 26 GB and get bigger 

And when we download it takes more than 4-5 hours for normal download from LCS 

So I searched for a solution to download faster 

Below find example to use SAS Link to download much faster 



1- Click on Generate SAS link 

The end result is that you have a full URL/URI for the file that you want to transfer. The URL/URI will contain a valid SAS token












2- Download AzCopy to the environment


How to Transfer the file into your own Storage Account

3- Open Power shell as administrator 


4- Use command: .\azcopy copy "LCS SAS Link" "LocalPath"


Here you can find it toke 17 minutes only  to download almost 26 GB data file 















Sunday, January 22, 2023

D365FO - SQL get security details (such as Security roles, duties and privileges)

 SQL Query to get security details (such as Security roles, duties and privileges)

 Today, I will sharing out the list of queries which can used to get the security details.


It will cover following combinations of data.





Security roles

Security roles to duties

Security roles with privileges

Security role and duty combination along with privileges

Following list of tables are used in it.

SECURITYROLES

SECURITYOBJECTCHILDREREFERENCES

SECURITYDUTY

SECURITYPRIVILEGE

-- Get the list  of all security roles 

Select Name as SecurityRoleName FROM SecurityRole;


-- Get the list of all security roles to duties

SELECT T2.Name as SecurityRole, T3.NAME as Duty 

FROM SECURITYOBJECTCHILDREREFERENCES T1 

JOIN SECURITYROLE T2 ON T1.IDENTIFIER = T2.AOTNAME 

JOIN SECURITYDUTY T3 ON T1.CHILDIDENTIFIER = T3.IDENTIFIER

WHERE T1.OBJECTTYPE = 0 AND T1.CHILDOBJECTTYPE = 1 ;


-- Get the ;ist of all security roles with privileges 

SELECT T2.Name as SecurityRole, T3.NAME as Privileges

FROM SECURITYOBJECTCHILDREREFERENCES T1 

JOIN SECURITYROLE T2 ON T1.IDENTIFIER = T2.AOTNAME 

JOIN SECURITYPRIVILEGE T3 ON T1.CHILDIDENTIFIER = T3.IDENTIFIER

WHERE T1.OBJECTTYPE = 0 AND T1.CHILDOBJECTTYPE = 2 ;



-- Get the list of all role-duty combination with privilege 

SELECT T2.Name as SecurityRole, T2.AOTNAME as RoleSystemName,  T3.NAME AS Duty, T3.IDENTIFIER as DutySystemName, T5.NAME as Privilege, T5.IDENTIFIER as PrivilegeSystemName

FROM SECURITYOBJECTCHILDREREFERENCES T1 

JOIN SECURITYROLE T2 ON T1.IDENTIFIER = T2.AOTNAME 

JOIN SECURITYDUTY T3 ON T1.CHILDIDENTIFIER = T3.IDENTIFIER

JOIN SECURITYOBJECTCHILDREREFERENCES T4 on T4.IDENTIFIER = T3.IDENTIFIER

JOIN SECURITYPRIVILEGE T5 on T4.CHILDIDENTIFIER = T5.IDENTIFIER

WHERE T1.OBJECTTYPE = 0 AND T1.CHILDOBJECTTYPE = 1 

AND T4.OBJECTTYPE = 1 AND T4.CHILDOBJECTTYPE = 2;



Ref

D365 FO - X++ Join multiples tables with same table using query build data source

Join multiples tables with same table using query build data source

Today, I will be discussing about one of the common issue related to query creation using  query build data source. 


Let's suppose we have following tables.

 - Leave Assignment  table - (Base Table) - Namely Parent for demo purpose

 - HcmEmployment table   - Namely Child 1 for demo purpose

 - Leave Plan table    - Namely Child 2 for demo purpose


We want to link base table with both hcm employment (child1) and leave plan table (child2)  using query build data source. Below is the code used for performing this operation.


public QueryRun   fetchMultipleTableQueryDemo()

{

    QueryBuildDataSource   hcmEmploymentds;

    QueryBuildDataSource   qbds;

    Query query = new Query();

       

    // Adding parent  as a datasource

    QueryBuildDataSource qbds = query.addDataSource(tableNum(Parent));


    // Adding child 1 as a datasource

    hcmEmploymentds= qbds.addDataSource(tableNum(Child1));

    hcmEmploymentds.joinMode(JoinMode::InnerJoin);

    hcmEmploymentds.addLink(fieldNum(Parent, Worker),fieldNum(Child1, Worker));

    hcmEmploymentds.fetchMode(QueryFetchMode::One2One);


   // Adding child 2 as a datasource

   qbds = qbds.addDataSource(tableNum(Child2));

   qbds.joinMode(JoinMode::InnerJoin);

   qbds.addLink(fieldNum(Parent, LeaveDetail), fieldNum(Child1, RecId));

   qbds.fetchmode(QueryFetchMode::One2One);

       

    return new QueryRun(query);

} 


Few of the common methods related to query and dates.

Date  related methods 

 -  Year(date  _date) : Method will be used to get year from specified date.

-   mkdate(int _day, int _month, int _year) : Method will be used to make and return a new date

-   mthOfYr(date _date) : Method will be used to get month from the the specified date parameter.

-   dayOfMth(date _date) : Method will be used to get day of the month from the specified date parameter.


Query  related methods 

QueryBuildRange         startAndEndDateRange ;

startAndEndDateRange = this.query().dataSourceTable(tableNum(EmplSickLeaveEncashment)).addRange(FieldNum(EmplSickLeaveEncashment, NextEncashDate));

startAndEndDateRange.value(SysQueryRangeUtil::dateRange(startDate,toDate));

startAndEndDateRange.status(RangeStatus::Hidden);

Here for adding date range we can using dateRange method from SysQueryRangeUtil class.

In order to hide range we can set its status to Hidden by using method of status.

Ref

Ref2