Powered By Blogger

Sending Email with SSRS reports as attachment using X++ in Microsoft Dynamics 365 for Finance and Operations

 Public class EmailCustAccountStmnt

{
public void run(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;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    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);
 
    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);
 
    if (custParameters.EmailId && toEmail)
    {
 
        templateTokens.insert(#CustAccount, _custTable.name());
        templateTokens.insert(#EmailDate, date2StrXpp(systemDateGet()));
 
        [emailSubject, emailBody, emailSenderAddr, emailSenderName] =
            EmailCustAccountStmnt::getEmailTemplate(custParameters.EmailId, _custTable.languageId());
 
 
        messageBuilder.addTo(this.getCustEmail(_custTable.AccountNum))
                        .setSubject(strFmt("Customer account statement for %1", _custTable.AccountNum))
                        .setBody(SysEmailMessage::stringExpand(emailBody, SysEmailTable::htmlEncodeParameters(templateTokens)))
                        .addCC("");
 
        messageBuilder.setFrom(emailSenderAddr, emailSenderName);
        messageBuilder.addAttachment(fileStream, fileName);
 
        SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());
 
        info(strFmt("Email sent successfully to the customer account %1", _custTable.AccountNum));
    }
    else
    {
        info(strFmt("There is no email id mappiing for this customer %1 or check the Email template setup.", _custTable.AccountNum));
    }
}
 
protected static container getEmailTemplate(SysEmailId _emailId, LanguageId _languageId)
{
    var messageTable = SysEmailMessageTable::find(_emailId, _languageId);
    var emailTable = SysEmailTable::find(_emailId);
 
    if (!messageTable && emailTable)
    {
        // Try to find the email message using the default language from the email parameters
        messageTable = SysEmailMessageTable::find(_emailId, emailTable.DefaultLanguage);
    }
 
    if (messageTable)
    {
        return [messageTable.Subject, messageTable.Mail, emailTable.SenderAddr, emailTable.SenderName];
    }
    else
    {
        warning("@SYS135886"); // Let the user know we didn't find a template
        return ['', '', emailTable.SenderAddr, emailTable.SenderName];
    }
}
 
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;
}

No comments:

Post a Comment

DisableStandredButton

 My requirement is to disable the delete button for journals that were posted:- After Posting the button is enabled fig:- Line level also th...