13 Apr 2026

Running SSRS report through code and Sending that as email

 class MFL_SalesOrderOrderEmailBatchJob extends RunBaseBatch

{

  

    public static void main(Args _args)

    {

        MFL_SalesOrderOrderEmailBatchJob  SalesOrderOrderEmailBatchJob;

  


        SalesOrderOrderEmailBatchJob = new MFL_SalesOrderOrderEmailBatchJob();


        if (SalesOrderOrderEmailBatchJob.prompt())

        {

            SalesOrderOrderEmailBatchJob.run();

        }

    }


    /// <summary>

    ///

    /// </summary>

    /// <returns></returns>

    public ClassDescription caption()

    {

        ClassDescription ret;

    

        ret = super();

    

        ret = "OmniChannel SalesOrder Email Batch Job";

        return ret;

    }


    void run()

    {

        this.email();

    }


    public container pack()

    {

        return [#CurrentVersion];

    }


    public boolean unpack(container packedClass)

    {

        //Deserializes the packedClass parameter value to an instance of the RunBase class.

        boolean         isSuccessful;

        Version         version = RunBase::getVersion(packedClass);

        container       base;

        ;

        switch (version)

        {

            case #CurrentVersion:

            {

                [version, base] = packedClass;

                isSuccessful = true;

                break;

            }

        default :

            return false;

        }

        return isSuccessful;

    }


    public boolean runsImpersonated()

    {

        return true;

    }


    public boolean canGoBatch()

    {

        return true;

    }


    public System.IO.Stream   runAndSaveSSRSReport(Str Storeid)

    {

        SrsReportRunController          ssrsController = new SrsReportRunController();

        Pwc_OmniEmailContractClass      Contract = new Pwc_OmniEmailContractClass();


        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();


        SRSPrintDestinationSettings     printerSettings;

        str                             ReportPath;

        SRSReportRUN       srsReportRun;

        System.String[] files;

        int             filecount;

        int             i;

        System.IO.Stream            stream;

        //folder = WianAPI::getTempPath()+"\Report";

        //folder = "C:\\Pwc_Mail";


            

        


            ReportPath = Storeid + "Pending Omni Order"+".CSV";


           ssrsController.parmReportName(ssrsReportStr(Pwc_OmniEmail, Report));

            ssrsController.parmExecutionMode(SysOperationExecutionMode::Synchronous);

            ssrsController.parmShowDialog(false);

            Contract.parmStoreId(Storeid);

            ssrsController.parmReportContract().parmRdpContract(Contract);


            //link the printer settings to the controller

            printerSettings = ssrsController.parmReportContract().parmPrintSettings();

            //print to pdf and always overwrite if the file exists

            printerSettings.overridePrintContractSettings(true);

            printerSettings.printMediumType(SRSPrintMediumType::File);

        printerSettings.fileFormat(SRSReportFileFormat::Excel);

            printerSettings.overwriteFile(true);

            printerSettings.fileName(@ReportPath);

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

            ssrsController.parmReportContract().parmReportExecutionInfo(executionInfo);

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

            srsReportRunService.preRunReport(ssrsController.parmreportcontract());

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

            parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);


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

            // Actual rendering to byte array

            reportBytes = srsproxy.renderReportToByteArray(ssrsController.parmreportcontract().parmreportpath(),

            parameterValueArray,

            printerSettings.fileFormat(),

            printerSettings.deviceinfo());


            container binData;

            Binary binaryData;


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


            //binaryData = Binary::constructFromMemoryStream(mstream);

          //  this.SendEmailNotification(mstream,PackingSlipJour);

            return  mstream;

        

        

    }


    public void email()

    { 

        MFL_OrderCancellation_Status              OrderCancellation;

        RETAIL_STOREEXTRAFIELDSTABLE              STOREEXTRAFIELDSTABLE;

        MFL_SalesOrderCreation                    SalesOrderCreation;

        MFL_StrelinOutboundStatus                 StrelinOutboundStatus;

        MFL_SalesOrderCancellationConformation    SalesOrderCancellationConformation ;

        MFL_SalesOrderStatus                      SalesOrderStatus;

        SalesTable                                salestabe;

        int                                       orderstatus;

        string20                                      salesnumber;

        SysEmailParameters      parameters = SysEmailParameters::find();

        SMTPRelayServerName     relayServer;

        SMTPPortNumber          portNumber;

        SMTPUserName            userName;

        SMTPPassword            password;

        Str1260                 subject,body;

        InteropPermission       interopPermission;

        SysMailerSMTP           smtp    = new SysMailerSMTP();

        SysMailerMessageBuilder mailer = new SysMailerMessageBuilder();

        str                     emailBody1,emailBody2,emailBody3;

        int                     i;

        LogisticsElectronicAddressLocator   resourceEmailAddress,fromEmailAddress = '';

        str tomailaddress;

        RetailStoreTable StoreTable;



        //while select SalesOrderReleaseNumber,storecode from  SalesOrderCreation notexists join

        //    StrelinOutboundStatus where StrelinOutboundStatus.SalesOrderReleaseNumber == SalesOrderCreation.SalesOrderReleaseNumber && StrelinOutboundStatus.MFL_SalesRecordStatus != MFL_SalesRecordStatus::S &&  StrelinOutboundStatus.MFL_SalesRecordStatus != MFL_SalesRecordStatus::C && StrelinOutboundStatus.SalesOrderReleaseNumber == '13053605'


        while select crosscompany StoreTable where StoreTable.StoreNumber == '59705'

        {

            try

            {

                //select  crosscompany  STOREEXTRAFIELDSTABLE where STOREEXTRAFIELDSTABLE.STOREID ==SalesOrderCreation.storecode;

                //if(STOREEXTRAFIELDSTABLE.Retail_storeemailid != '')

                //{


                System.IO.MemoryStream reportstream =  this.runAndSaveSSRSReport(StoreTable.StoreNumber);


                        if (parameters.SMTPRelayServerName)

                        relayServer = parameters.SMTPRelayServerName;

    

                        portNumber  = parameters.SMTPPortNumber;

                        userName    = parameters.SMTPUserName;

                        fromEmailAddress = parameters.SMTPUserName;

                        password    = SysEmailParameters::password();

    

                        if ((relayServer == '') || (userName == '') || (fromEmailAddress == '') || (password == ''))

                        {

                            throw error('Email parameters are missing');

                        }

 


                        subject     = "Omni Pending order report";

                        resourceEmailAddress = 'manindra.kaku@pwc.com';

  

                            if (resourceEmailAddress == '')

                             throw   error(strFmt('Resource Email address is blank'));

                            try

                            {

                                new InteropPermission(InteropKind::ClrInterop).assert();


                                System.Net.Mail.AttachmentCollection    mailAttachementCollection;

                                System.Net.Mail.Attachment              mailAttachment;

                                System.Net.Mail.MailMessage             mailMessage;

                                System.Net.Mail.SmtpClient              myMail;

                                System.Net.Mail.MailAddressCollection   mailToCollection;

                                System.Net.Mail.MailAddressCollection   mailCCCollection;

                                System.Net.Mail.MailAddress             mailFrom;

                                System.Net.Mail.MailAddress             mailTo;

                                System.Net.Mail.MailAddress             mailCC;

                

                                str                                     CcMailAddress,pwd,mailfrom_check,smtpServer;

                                int                                     SMTPPort;

                                ListEnumerator                        le;

                                List                                  ccList,toList;

                

                                System.IO.Stream            stream,fileStream;

                                ccList = strSplit(tomailaddress, ';');


                                mailFrom            = new  System.Net.Mail.MailAddress(fromEmailAddress);

                                mailTo  = new System.Net.Mail.MailAddress(resourceEmailAddress);

                                // mailCC  = new System.Net.Mail.MailAddress(tomailaddress);

                                mailMessage         = new System.Net.Mail.MailMessage(mailFrom,mailTo);

                

                                //le = ccList.getEnumerator();

                                //mailCCCollection = mailMessage.get_CC();

                                //while (le.moveNext())

                                //{

                                //    mailCCCollection.Add(strLTrim(strRTrim(le.current())));

                                //}


                                smtpServer          = SysEmaiLParameters::find(false).SMTPRelayServerName;

                                mailmessage.set_Subject(strFmt(subject));

                                mailmessage.set_Body("Dear Store Team,\n Please find enclosed Open ECOM orders report for store");

                                mailAttachementCollection = mailMessage.get_Attachments();

                              mailAttachment = new System.Net.Mail.Attachment(reportstream, "OmniPendingOrder.CSV");

                                mailAttachementCollection.Add(mailAttachment);


                                SMTPPort            = SysEmaiLParameters::find(false).SMTPPortNumber;

                                myMail              = new System.Net.Mail.SmtpClient(smtpServer, SMTPPort);

                                myMail.set_EnableSsl(true);

                                pwd = SysEmaiLParameters::password();


                                myMail.set_EnableSsl(true);


                                pwd = SysEmaiLParameters::password();


                                mymail.set_Credentials(New System.Net.NetworkCredential(parameters.SMTPUserName, pwd));


                                mymail.Send(mailmessage);

                                CodeAccessPermission::revertAssert();

                            }

                            catch(Exception::CLRError)

                            {

                                System.Exception ex = ClrInterop::getLastException();

                                if (ex != null)

                                {

                                    ex = ex.get_InnerException();

                                    if (ex != null)

                                    {

                   

                                    }

                                }

                            }

                        }

        catch(Exception::CLRError)

        {

            System.Exception ex = ClrInterop::getLastException();

            if (ex != null)

            {

                ex = ex.get_InnerException();

                if (ex != null)

                {

                   

                }

            }

        }

        

    }

  }


}

1 Aug 2025

DMFPackageExporter will help to export the data as package in D365F&O

/// <summary>

/// Extension Class for DMFPackageExporter

/// </summary>


[ExtensionOf(classStr(DMFPackageExporter))]

final public class RBODMFPackageExporterCls_Extension

{

    /// <summary>

    /// Setting global cache to fetch execution id

    /// </summary>

    /// <param name = "packageName">packageName</param>

    /// <param name = "packageUrl">packageUrl</param>

    /// <param name = "definitionGroupId">definitionGroupId</param>

    /// <param name = "executionId">executionId</param>

    /// <param name = "reExecute">reExecute</param>

    /// <param name = "legalEntityId">legalEntityId</param>

    /// <param name = "createPackage">createPackage</param>

    /// <param name = "entitySyncVersion">entitySyncVersion</param>

    /// <param name = "previewCount">previewCount</param>

    /// <param name = "_messageId">_messageId</param>

    /// <returns>ExecutionId</returns>

    public DMFExecutionId exportToPackageV2(DMFPackageName              packageName, 

                                            SharedServiceUnitURL        packageUrl, 

                                            DMFDefinitionGroupName      definitionGroupId, 

                                            DMFExecutionId              executionId, 

                                            boolean                     reExecute, 

                                            DataAreaName                legalEntityId, 

                                            boolean                     createPackage, 

                                            Map                         entitySyncVersion, 

                                            int                         previewCount, 

                                            str                         _messageId)

    {

        SysGlobalCache          globalCache         = ClassFactory.globalCache();

        String255               cacheKey            = strFmt("@SYS111722", curUserId());

        RBOHQCParameters        hqcParamters        = RBHQCParameters::find();

        RBOPriceBookParameters  priceBookParameters = RBPriceBookParameters::find(); 

        RBOParameters           rboParameters       = RBParameters::find();

        RBOGLParameters         rboGLParameters     = RBGLParameters::find();

        

        executionId = next exportToPackageV2(packageName,

                                             packageUrl,

                                             definitionGroupId,

                                             executionId,

                                             reExecute,

                                             legalEntityId,

                                             createPackage,

                                             entitySyncVersion,

                                             previewCount,

                                             _messageId);


        if (definitionGroupId   ==  priceBookParameters.DefaultDefinition               ||

            definitionGroupId   ==  priceBookParameters.RLDefaultDefinition             ||

            definitionGroupId   ==  hqcParamters.GTDefaultProcessingGroup               ||

            definitionGroupId   ==  hqcParamters.ITDefaultProcessingGroup               ||

            definitionGroupId   ==  rboParameters.OPEDefinationGroupName                ||

            definitionGroupId   ==  rboParameters.LegacyListingExportDefaultDefinition  ||

            definitionGroupId   ==  rboParameters.GS1DelistStagingDefaultDefination     ||

            definitionGroupId   ==  rboParameters.DefaultDefinationPeriodOpenCloseJob   ||

            definitionGroupId   ==  rboGLParameters.DefaultDefinationMonthEndLog)

        {

            globalCache.set(cacheKey, cacheKey, executionId);

        }


        return executionId;

    }


}

 

13 Oct 2014

Code to Take -- RecId Count


Code To Get Rec Id Count:

Create a  Job :

static void Reccount(Args _args)
{
    ReadingEntryTmp  ReadingEntry;
    int  RecIdCount;
    ;
   
   
    Select count(RecId) from ReadingEntry where ReadingEntry.bookno== "1000";

    RecIdCount = ReadingEntry.RecId;

    info(strfmt( "Total recId %1", RecIdCount));
}

7 Oct 2014

Scheduling autobackup using SQL Server Agent

Scheduling autobackup using SQL Server Agent

Steps

Open sql server management studio from start menu or type ssms in run.
Expand management folder and right click maintenance plans folder and select maintenance plan wizard

  

 Click  ->next



give name for the plan and select single schedule radio button and click next




choose backup database(full) and click next



click next



In the following window choose the list of databases and click ok 



In the same window choose where the backup files will be stored (refer the highlighted screenshot below)
then click next.



In following window choose the location where the report file has to be stored and click next



click next 



if everything went fine you should see the following screen 



Now to schedule the job navigate to SQL server Agent expand jobs folder select the job that has the name same asmaintenance plan in our case its going to be TestDailybackup , right click the job and select properties



in properties window switch to schedule tab and click new button



In the schedule window choose a schedule according to your requirement (in my case i have scheduled the job to run daily at 5:30PM) then click ok



Note 
Before testing the job ensure SQL server agent service is running.if not start the service either from SQL server management studio or got to service.msc and start the service.


To test the job right click the job and select start job at step







 To view the backup go to the file path specified earlier (In my case its E:\ drive)