Friday 22 March 2019

Having query in dialog form get the query values by using contract class

I am using query for dialog
need to get the values of that query

Create a query.
action type menu item
add to controller class
form controller class getting the service class
here in service class we are getting contract class.
here in attribute of contact class we are passing our query


contract class:

/// <summary>
/// Contract class for releasing sales order
/// </summary>
[DataContractAttribute]
class FBHSalesReleaseOrderContract
{
    str         packedQuery;

    [DataMemberAttribute,
    AifQueryTypeAttribute('_packedQuery', querystr(FBHSalesAgreementFollowUp))]
    /// <summary>
    ///    Parm method to return and set parameters.
    /// </summary>
    /// <param name="_packedQuery">
    /// </param>
    /// <returns>
    ///    Returnd the parameter passed.
    /// </returns>
    public str parmQuery(str _packedQuery = packedQuery)
    {
        packedQuery = _packedQuery;
        return packedQuery;
    }

    /// <summary>
    ///    Method to return query.
    /// </summary>
    /// <returns>
    ///    Returnd the query.
    /// </returns>
    public Query getQuery()
    {
        return new Query(SysOperationHelper::base64Decode(packedQuery));
    }

    /// <summary>
    ///    Method to set the query.
    /// </summary>
    /// <param name="_query">
    /// </param>
    public void setQuery(Query _query)
    {
        packedQuery = SysOperationHelper::base64Encode(_query.pack());
    }

}


Controller class:

/// <summary>
/// Controller class for release order
/// </summary>
class FBHSalesReleaseOrderController extends SysOperationServiceController
{
    /// <summary>
    /// Construct for calling service class
    /// </summary>
    /// <param name = "_args">Argument</param>
    /// <returns></returns>
    public static FBHSalesReleaseOrderController construct(SysOperationExecutionMode _executionMode=SysOperationExecutionMode::Synchronous)
    {
        FBHSalesReleaseOrderController FBHSalesReleaseOrderController = new FBHSalesReleaseOrderController(classStr(FBHSalesReleaseOrderService),methodStr(FBHSalesReleaseOrderService,process),_executionMode);
        return FBHSalesReleaseOrderController;
    }

    /// <summary>
    /// Main method for controller class
    /// </summary>
    /// <param name = "_args"></param>
    public static void main(Args _args)
    {
        FBHSalesReleaseOrderController   FBHSalesReleaseOrderController;
        FBHSalesReleaseOrderController = FBHSalesReleaseOrderController::construct();
        FBHSalesReleaseOrderController.startOperation();
    }

    /// <summary>
    /// To set the dialog caption
    /// </summary>
    /// <param name = "_dialogCaption"></param>
    /// <returns></returns>
    public LabelType parmDialogCaption(LabelType _dialogCaption = "")
    {
        return "@FBH:FBH50718";
    }

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    protected boolean canRunInNewSession()
    {
        boolean ret;
   
        ret = super();
        ret = true;
        return ret;
    }


}


Service class:


/// <summary>
/// Service class for releasing sales order
/// </summary>
class FBHSalesReleaseOrderService
{
 
    /// <summary>
    /// Method to run the query and apply validations.
    /// </summary>
    /// <param name="_FBHSalesReleaseOrderContract">
    /// FBHSalesReleaseOrderContract contract class parameter
    /// </param>
    public void process(FBHSalesReleaseOrderContract _FBHSalesReleaseOrderContract)
    {
        Query                query;
        QueryRun             queryRun;
        query                = _FBHSalesReleaseOrderContract.getQuery();
        queryRun             = new QueryRun(query);
        query                = queryRun.query();

        QueryBuildDataSource qbds = query.dataSourceTable(tableNum(AgreementLine));
        QueryFilter filter = query.findQueryFilter(qbds, fieldId2Name(tableNum(AgreementLine), fieldNum(AgreementLine, FBHReleaseDate)));
        if (filter == null)
        {
            filter = query.addQueryFilter(qbds, fieldId2Name(tableNum(AgreementLine), fieldNum(AgreementLine, FBHReleaseDate)));
        }
       
        if (filter && filter.value() == "")
        {
            filter.value(queryValue(DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone())));
        }

        SalesAgreementHeader salesAgreementHeader;
       
        while(queryRun.next())
        {
            if (queryRun.changed(tableNum(SalesAgreementHeader)) )
            {
                salesAgreementHeader          = queryRun.get(TableNum(SalesAgreementHeader)) as SalesAgreementHeader;
                salesAgreementHeader          = SalesAgreementHeader::findAgreementId(SalesAgreementHeader.SalesNumberSequence);

                if((   SalesAgreementHeader.LatestLineExpirationDate
&& SalesAgreementHeader.LatestLineExpirationDate
<=  DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone()))
||!SalesAgreementHeader::hasdeliverySchedule(SalesAgreementHeader))
                {
                    continue;
                }
                try
                {
                    ttsbegin;
                    FBHSalesReleaseOrderService::releaseOrderFromAgreement(SalesAgreementHeader,query);
                    ttscommit;
                }
                catch(Exception::Error)
                {
                    continue;
                }
            }
        }
    }

    /// <summary>
    ///  Release order from agreement
    /// </summary>
    /// <param name = "salesAgreementHeader">sales agreement from which order is to be released</param>
    /// <param name = "_query">passing selected query from dialog</param>
    public static void releaseOrderFromAgreement(SalesAgreementHeader salesAgreementHeader,Query _query = new Query())
    {
        salesCreateReleaseOrderTableTmp salesCreateReleaseOrderTabletmp;
        salesCreateReleaseOrderLineTmp  salesCreateReleaseOrderLineTmp;
        SalesAgreementHeader.Currency = Ledger::accountingCurrency(CompanyInfo::current());
        FBHSalesAgreementGenerateReleaseOrder salesAgreementGenerateReleaseOrder
                                          = FBHSalesAgreementGenerateReleaseOrder::construct();

        salesAgreementGenerateReleaseOrder.parmSalesAgreementHeader(salesAgreementHeader);
        salesAgreementGenerateReleaseOrder.parmisBatch(NoYes::Yes);
        salesAgreementGenerateReleaseOrder.parmQuery(_query);
        salesAgreementGenerateReleaseOrder.createReleaseOrderTable(salesCreateReleaseOrderTableTmp);
        salesAgreementGenerateReleaseOrder.createReleaseOrderLine(salesCreateReleaseOrderLineTmp);
        salesAgreementGenerateReleaseOrder.parmReleaseOrderTable(salesCreateReleaseOrderTableTmp);
        salesAgreementGenerateReleaseOrder.parmReleaseOrderLine(SalesCreateReleaseOrderLineTmp);

        if (salesAgreementGenerateReleaseOrder.check())
        {
            ttsbegin;

            SalesAutoCreate salesAutoCreate = SalesAutoCreate::construct(salesAgreementGenerateReleaseOrder.getreleaseorderline(), null,salesAgreementGenerateReleaseOrder.getreleaseordertable());
            salesAutoCreate.create();

            ttscommit;
        }
    }


}

Loop the temp table and update the temp table based on conditions

Loop the temp table and update the temp table based on conditions : 


 SalesCreateReleaseOrderLineTmp  lineTmp = sender.datasource().cursor();   // get the record
SalesCreateReleaseOrderLineTmp  localTmpTable; // local table for looping
 localTmpTable.setTmpData(lineTmp);  // assigning our tempt table to local table

       
ttsbegin;
while select forupdate  from localTmpTable
            where localTmpTable.FBHAdditive == NoYes::Yes
            && localTmpTable.FBHMainAgreementLine == agreementLineQuantityCommitment.LineNumber

{
 localTmpTable.SalesQty = Global::roundDownDec(unitConvertionValueAdditiveSalesUnit,2); 
 localTmpTable.doUpdate(); // updating temp table field data
}

ttscommit;
lineTmp.setTmpData(localTmpTable); // assigning it to original table


for data source also we need to get the data source first the get the temp table and run the loop.

delete button  event handler for selected records in form form , which is having data source as temp table and need to delete records based on conditions from temp table code is below.

[FormControlEventHandler(formControlStr(SalesAgreementGenerateReleaseOrder, DeleteLineGridCmdButton), FormControlEventType::Clicked)]
    public static void DeleteLineGridCmdButton_OnClicked(FormControl sender, FormControlEventArgs e)
    {
        FormRun                        formrun  = sender.formRun();
        FormDataSource                 lines_ds = formrun.dataSource(formDataSourceStr(SalesAgreementGenerateReleaseOrder,SalesCreateReleaseOrderLineTmp));
        SalesCreateReleaseOrderLineTmp lines = lines_ds.cursor();
       
        ttsbegin;
        MultiSelectionHelper           selectionHelper = MultiSelectionHelper::construct();
        SalesCreateReleaseOrderLineTmp tmpLines,tmpLinesMsg;
        selectionHelper.parmDatasource(lines_ds);
       
        SalesCreateReleaseOrderLineTmp  localTmpTable;
        localTmpTable.setTmpData(lines);
       
        //for error message if user selects additive lines
        tmpLinesMsg = selectionHelper.getFirst();
        While(tmpLinesMsg)
        {
            if (tmpLinesMsg.FBHAdditive)
            {
                throw Error("@FBH:FBH270269");
            }
            tmpLinesMsg =selectionHelper.getNext();
        }

        // for deleting selected lines
        tmpLines = selectionHelper.getFirst();
        While(tmpLines)
        {
            ttsbegin;
            while select forupdate localTmpTable
                where localTmpTable.RecId == tmpLines.RecId
            {
                SalesCreateReleaseOrderLineTmp  localTmpTableAdditives;
                AgreementLineQuantityCommitment agreementLineQuantityCommitment;
                localTmpTableAdditives.setTmpData(lines);

                while select forupdate  localTmpTableAdditives
                    where localTmpTableAdditives.FBHAdditive == NoYes::Yes
                join agreementLineQuantityCommitment
                    where localTmpTableAdditives.FBHMainAgreementLine == agreementLineQuantityCommitment.LineNumber
                    && agreementLineQuantityCommitment.RecId == localTmpTable.AgreementLineQuantityCommitment
                {
                    localTmpTableAdditives.doDelete(); // deleting all additive lines for corresponded link with main agreement line
                }

                localTmpTable.doDelete();// deleting main agreement line
            }
            ttscommit;
            tmpLines =selectionHelper.getNext();

        }
        lines.setTmpData(localTmpTable);
        lines_ds.research(true);
        ttscommit;
        lines_ds.executeQuery();
    }

Getting email parameters and email settings while export


Getting email parameters and email settings while export :


If print medium type is email when you are exporting data it will store data in to PrintJobSettings field which is container data type in PrintMgmtSettings table.
getting the data from below field you need to use  pass PrintJobSettings field value as a parameter for  srsPrintDestinationSettings.unpack(this.PrintJobSettings) class

SRSPrintDestinationSettings  class having all the email type settings


public void postLoad()
    {
        super();

        SRSPrintDestinationSettings srsPrintDestinationSettings = new SRSPrintDestinationSettings();
        srsPrintDestinationSettings.unpack(this.PrintJobSettings);
        if (srsPrintDestinationSettings.printMediumType() == SRSPrintMediumType::Email)
        {
            this.skipDataSourceValidateField(true);
            this.skipDataSourceValidateWrite(true);

            this.PrintMediumType     = SRSPrintMediumType::Email;
            //this.PrintMediumType   = srsPrintDestinationSettings.printMediumType();
            this.PrinterName         = srsPrintDestinationSettings.printerName();
            this.PrinterPageSettings = srsPrintDestinationSettings.printerPageSettings();
            this.landscape           = srsPrintDestinationSettings.landscape();
            this.Caption             = srsPrintDestinationSettings.caption();
            this.PrinterStatus       = srsPrintDestinationSettings.printerStatus();
            this.PrinterType         = srsPrintDestinationSettings.printerType();
            this.PrinterWhere        = srsPrintDestinationSettings.printerWhere();
            this.PrinterComment      = srsPrintDestinationSettings.printerComment();
            this.PrintAllPages       = srsPrintDestinationSettings.printAllPages();
            this.FromPage            = srsPrintDestinationSettings.fromPage();
            this.ToPage              = srsPrintDestinationSettings.toPage();
            //this.NumberOfCopies    = srsPrintDestinationSettings.numberOfCopies();
            this.EmailTo             = srsPrintDestinationSettings.emailTo();
            this.EmailCC             = srsPrintDestinationSettings.emailCc();
            this.EmailSubject        = srsPrintDestinationSettings.emailSubject();
            this.EmailAttachmentFileFormat      = srsPrintDestinationSettings.emailAttachmentFileFormat();
            this.EmailAttachmentImageFileFormat = srsPrintDestinationSettings.emailAttachmentImageFileFormat();
            this.FileName            = srsPrintDestinationSettings.fileName();
            this.FileFormat          = srsPrintDestinationSettings.fileFormat();
            this.ImageFileFormat     = srsPrintDestinationSettings.imageFileFormat();
            this.OverwriteFile       = srsPrintDestinationSettings.overwriteFile();
            //this.OrintToArchive      = srsPrintDestinationSettings.//conPeek(con,27);
            this.OverridePageSettings = srsPrintDestinationSettings.overridePageSettings();
            this.OverridePrintContractSettings = srsPrintDestinationSettings.overridePrintContractSettings();
            //this.OverwriteFileIsSet = srsPrintDestinationSettings.//conPeek(con,30);
            this.Collate             = srsPrintDestinationSettings.collate();
            this.Orientation         = srsPrintDestinationSettings.orientation();
            this.PrintOnBothSides    = srsPrintDestinationSettings.printOnBothSides();
            //this.SendToPrinterAsPdf  = srsPrintDestinationSettings.//conPeek(con,34);
           
            //container con1,con   = this.PrintJobSettings;
            //this.Obj1 = conPeek(con,1);//'fbhEmailBodyCustom';
            //this.Obj2 = conPeek(con,2);//srsPrintDestinationSettings.fbhEmailBody();
            //this.Obj3 = conPeek(con,3);
            //srsPrintDestinationSettings.printMedium().unpack(srsPrintDestinationSettings.printMedium());
            //con1 = conNull();
            //con1 = conPeek(con,4);
            //this.Obj41 = conPeek(con1,1);
            //this.Obj42 = conPeek(con1,2);
            //this.Obj43 = conPeek(con1,3);
            //this.Obj44 = conPeek(con1,4);
         
            PrintMgmtDocInstance docInstance;

            select firstonly docInstance
                where docInstance.RecId == this.ParentId;

            this.ReferencedRecId    = docInstance.ReferencedRecId;
            this.ReferencedTableId  = docInstance.ReferencedTableId;
            this.NodeType           = docInstance.NodeType;
            this.DocumentType       = docInstance.DocumentType;
            this.DocumentPriorityId = docInstance.PriorityId;

            if (this.ReportFormat)
            {
                PrintMgmtReportFormat reportFormat;
                select firstonly reportFormat
                    where reportFormat.RecId == this.ReportFormat;
                if (reportFormat.RecId)
                {
                    this.PRFCountryRegionId = reportFormat.CountryRegionId;
                    this.PRFDescription     = reportFormat.Description;
                    this.PRFDocumentType    = reportFormat.DocumentType;
                    this.PRFName            = reportFormat.Name;
                    this.PRFSystem          = reportFormat.System;
                }
            }
        }
       
    }

Skip validataion methods in D365 in DMF

Skip validataion methods in D365 in DMF: 



for skipping table validation methods when import and export the entity we need to write in to below methods. : persistEntity()

public void persistEntity(DataEntityRuntimeContext _entityCtx)
    {
        this.skipDataSourceValidateField(true);
        this.skipDataSourceValidateWrite(true);
        
        this.skipDataSourceValidateField(fieldNum(FBHPrintMgmtSettingsEntity, PrintSettingDescription), true);
        this.skipDataSourceValidateField(fieldNum(PrintMgmtSettings, Description), true);
        
        super(_entityCtx);
    }

here you can skip the table vaidate write and validate field methods

Getting container value data while import and export in D365

Getting container value data while import and export in d365: 

I have 1 field in my table which is container data type. I need to import/export that field data  through data entity.

Example:
Table :PrintMgmtSettings
Field : QueryPacked , EDT :  PackedQueryRun (container data type)
Here in this field data will store in binary code , we need to retrieve that binary code while import and export.

Created:
data entity : FBHPrintMgmtSettingsEntity
Data source : PrintMgmtSettings
Added all fields from data source to entity

Staging table for data entity : FBHPrintMgmtSettingsStaging
Added one extra field : 
Field : QueryPackedFileName
EDT: Filename

Added one method in staging table :

    public static container getFieldsToBeConvertedToFile()
    {
        return [  ['QueryPacked', 'QueryPacked', 'QueryPackedFileName', true]  ];

    }

Here QueryPacked is our original table field and QueryPackedFileName added one extra field in staging table. It will store the container QueryPacked  field data in one file for each record.

Now add one method in entity : postTargetProcess
this method will update the querypacked fild data from staging.


 public static void postTargetProcess(DMFDefinitionGroupExecution _dmfDefinitionGroupExecution)
    {
        FBHPrintMgmtSettingsStaging   staging;
        PrintMgmtSettings             printMgmtSettings;

        printMgmtSettings.skipAosValidation(true);
        printMgmtSettings.skipDataMethods(true);

        while select QueryPacked,PrintJobSettings, ParentId,PrintSettingPriorityId, RecId from staging
            where staging.DefinitionGroup == _dmfDefinitionGroupExecution.DefinitionGroup &&
                staging.ExecutionId == _dmfDefinitionGroupExecution.ExecutionId
        {
            select firstonly forupdate QueryPacked, RecId from printMgmtSettings
                where printMgmtSettings.ParentId == staging.ParentId
                && printMgmtSettings.PriorityId == staging.PrintSettingPriorityId;
            if (printMgmtSettings)
            {
                printMgmtSettings.QueryPacked = staging.QueryPacked;
                ttsbegin;
                printMgmtSettings.doupdate();
                ttscommit;
            }
        }
    }



when you exporting entity and download the package you will have one extra file in that package folder with name : Resource
here in this Resource folder for each record we have one file with querypacked field data.