Saturday, 30 November 2019

Add new Document Type for Print management under Accounts Receivable

Extend Enum PrintMgmtDocumentType  and add new enum : SORouting
Extend Enum PrintMgmtNodeTypeand add new enum  :SORouting

Add new Document Type : 


[ExtensionOf(Classstr(PrintMgmtNode_Sales))]
final  class CITPrintMgmtNode_Sales_Extension
{
    public List getDocumentTypes()
    {
        List docTypes;

        docTypes = new List(Types::Enum);
        docTypes = next getDocumentTypes();
        docTypes.addEnd(PrintMgmtDocumentType::SORouting);
        return docTypes;
    }

}
PrintMgmtDocumentType.CITExtension
====================================================================
[ExtensionOf(classStr(PrintMgmtReportFormatPopulator))]
public final class CITPrintMgmtReportFormatPopulator_Extension
{
    //LogisticsAddressCountryRegionISOCode isoCountryCode;
    //LogisticsAddressCountryRegionId countryRegionId;
    #ISOCountryRegionCodes
    #PrintMgmtSetup
 

    protected void addDocuments()
    {
        next addDocuments();
        // this.add(PrintMgmtDocumentType::SORouting);
        this.addOther(PrintMgmtDocumentType::CITSORouting, ssrsReportStr(CITSalesConfirm, SORouting), ssrsReportStr(CITSalesConfirm, SORouting), #NoCountryRegionId);
     
    }
}
====================================================================


Wednesday, 6 November 2019

Dealing with the “The natural key for the table was not found” error in the Dynamics 365 Data Entity Wizard

https://stoneridgesoftware.com/dealing-with-the-the-natural-key-for-the-table-was-not-found-error-in-the-dynamics-365-data-entity-wizard/

https://ztirom.at/2017/05/ax7-fix-natural-key-not-found-when-creating-a-data-entity/

Sunday, 3 November 2019

Runnable class to set current fiscal year to Calendar Field in Asset book

class SetCalendarToFixedAssetBooks
{
    public static void main(Args _args)
    {
        AssetBookTable assetBookTable1,assetBookTable2;
        AssetBookId book1,book2;
        book1='AMT';
        book2='FED';
       
        RecId FiscalYearRecId = Ledger::FiscalCalendar();
        if(Box::okCancel('Set current Fiscal Year to Asset Books with BookIds- AMT & FED ?',DialogButton::Cancel) == DialogButton::Ok)
        {
            ttsbegin;

            select  forupdate assetBookTable1 where assetBookTable1.BookId == book1;
            select  forupdate assetBookTable2 where assetBookTable2.BookId == book2;


            if(assetBookTable1)
            {
                assetBookTable1.FiscalCalendar = FiscalYearRecId;
                assetBookTable1.update();
                info(strFmt("Calendar set for AssetBook with BookId %1", book1));
            }

           
            if(assetBookTable2)
            {
                assetBookTable2.FiscalCalendar = FiscalYearRecId;
                assetBookTable2.update();
                info(strFmt("Calendar set for AssetBook with BookId %1", book2));
            }
            ttscommit;
        }
    }

}

Thursday, 24 October 2019

Error when dll was changed to existing C# project

The type or namespace name 'ProcessshipmentRequest' could not be found ( are you missing a using directive or an assembly reference?)

we checked the other dll's path which are referenced to project . Taken the backup of the dll needed to add at that path and replaced with new dll given.

C:\Users\Administrator\Documents\Visual Studio 2015\Projects\ShippingAPI\ShippingAPI\Libraries\ShipWebServiceClient.exe

we made a mistake by referencing the dll from the folder we copied the project.
C:\Users\Administrator\Desktop\Smart post\ShipWebServiceClient\bin\Debug\ShipWebServiceClient.exe

Monday, 14 October 2019

how to add field to listpage (make it sortable and filterable) not a field in datasources in it.

1. Create a view (CITCustTransView )
2. Add to the form as new datasource ( Outer join) to the data source which it can be linked.
3. Add link to view and existing data source through code.


[Extensionof(formDataSourceStr(CustopenTrans,CITCustTransView ))]
final class CITCustOpenTrans_Extension
{
    public void init()
    {
        QueryBuildDataSource  queryDataSourceLink;
        next init();
        queryDataSourceLink  = this.query().datasourcetable(tablenum(CITCustTransView));
        queryDataSourceLink.addlink(fieldNum(CustTrans,Invoice),fieldnum(CITCustTransView,InvoiceId));
        queryDataSourceLink.addlink(fieldNum(CustTrans,TransDate),fieldnum(CITCustTransView,InvoiceDate));
        queryDataSourceLink.addlink(fieldNum(CustTrans,Voucher),fieldnum(CITCustTransView,LedgerVoucher));
        queryDataSourceLink.addlink(fieldNum(CustTrans,AccountNum),fieldnum(CITCustTransView,InvoiceAccount));

    }

}

Add display method to table using Extension class

[Extensionof(tableStr(CustTrans))]
final class CustTrans_Extension
{
    //[SysClientCacheDataMethodAttribute(true)]  //This attribute will cache your display method.
    public static display CustPurchaseOrder SalesTableCustReq(CustTrans _this)
    {
        CustInvoiceJour invoicejour;
        SalesTable      salesTable;
        CustPurchaseOrder  PO ="";

        select invoicejour
            where invoicejour.InvoiceId == _this.Invoice
                && invoicejour.InvoiceAccount == _this.AccountNum
                &&  invoicejour.LedgerVoucher   ==  _this.Voucher
            &&  invoicejour.InvoiceDate ==  _this.transDate;
        if(invoicejour)
        {
            select * from salesTable
                where salesTable.SalesId == invoicejour.SalesId;
            PO=salesTable.PurchOrderFormNum;
        }
       return PO;
    }
}


Add a string control to form, change properties
Data method :CustTrans_Extension::SalesTableCustReq
DataSource:CustTrans
Cachemethod:Yes

4-Customize this method in your Form 
locate your form and create a new string to add this method in the form 

set the properties for the string as the below

Data method format must be ExtensionClassName::MethodName

Thursday, 10 October 2019

Adding new datasource to existed form and linking with other data source

final class CITEcoResProductDetailsExtended_Extension
{

Created a view "ProductCategoryView"  and added link to existing data source using code.


    public void init()
    {
        QueryBuildDataSource  queryDataSourceLink;
        next init();   
        queryDataSourceLink  = this.query().datasourcetable(tablenum(ProductCategoryView));
        queryDataSourceLink.addlink(fieldNum(EcoResProductCategory,Category),fieldnum(ProductCategoryView,ChildRecId)); 
    }

}

Monday, 30 September 2019

Get last 2 digits of field on to listpage

1. Create computed column method. create new field and assigned method to that. drag and drop the field on to listpage.


private static str getLastTwoCharOfCode()
        {
            #define.ViewName(CITProductCategoryView)
            #define.DataSourceName("EcoResCategory")
            #define.FieldSubsegmentId("Code")
            const str datasourceName = 'EcoResCategory';
            const str CodeField = 'Code';

            // Instantiate a DictView object for the view
            DictView viewView1 = new DictView(tableNum(CITProductCategoryView));

            str Code = viewView1.computedColumnString
                    (#DataSourceName,
                    #FieldSubsegmentId,
            FieldNameGenerationMode::FieldList,
                true);
            // create the SQL code snippet that computes the column
            str ret = "Right("+ Code+ ",2)";
            return ret;
    }

CSV to Azure File Storage


using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.WindowsAzure.Storage.StorageException;
#File
class WriteCSVFileInAzureFileStorage
{
    Dynamics.AX.Application.Exception exception;



    public static void main(Args _args)
    {
        CommaStreamIo io = CommaStreamIo::constructForWrite();
        str     fileName = 'Cust_DE.csv',
       fileContent;
        CustTable   custTable;

        // Write header
        io.writeExp(['Customer', 'Account number', 'Currency', 'DataAreaId']);

        // Write line
        while select custTable
     where custTable.DataAreaId == 'USMF'
        {
            io.writeExp([custTable.name(),
       custTable.AccountNum,
       custTable.Currency,
       custTable.DataAreaId]);
        }

        // Set stream
        System.IO.Stream stream = io.getStream();
        stream.Position = 0;

        // Set stream reader
        System.IO.StreamReader sReader = new System.IO.StreamReader(stream);

        // Set file contentn string
        fileContent = sReader.ReadToEnd();

        //// Save file
        //File::SendStringAsFileToUser(fileContent, fileName);
        Dynamics.AX.Application.Exception exception;
        infolog.add(exception::Info, "Azure Storage File Sample");


        WriteCSVFileInAzureFileStorage writeCSVFileInAzureFileStorage = new WriteCSVFileInAzureFileStorage();
        WriteCSVFileInAzureFileStorage::BasicAzureFileOperations(fileContent,fileName);

    }

    private static void BasicAzureFileOperations(str _fileContent,str _fileName)
    {
        //const str DemoShare = "democsvfileshare";
        const str DemoShare = "agreementfileshare";
        //const str DemoDirectory = "DemocsvFileDirectory";
        const str DemoDirectory = "AgreementcsvFileDirectory";
        //const str DemoFile = "demofile";
       // const str ImageToUpload = @'C:\Users\Usere4627ee6be0\Desktop\VS error.PNG'; //"HelloWorld.png";
        str FileContents = _fileContent;
        str fileName = _fileName;

        Dynamics.AX.Application.Exception exception;
        StorageException storageException = new Microsoft.WindowsAzure.Storage.StorageException();
       
        // Retrieve storage account information

        Microsoft.WindowsAzure.Storage.Auth.StorageCredentials storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials('siyedev813pu23e0d5d398f4', 'k03yWIis7PV3yIIUNxXKseUQZ7GSQMW3Ch0Ri2vAGmWVbov/dcj/7mzjpbAYrwA46LSuvKOWZKyBpA60B+zXpA==');

        Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);

        // Create a file client for interacting with the file service.

        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

        // Create a share for organizing files and directories within the storage account.

        CloudFileShare share = fileClient.GetShareReference(DemoShare);
           
        try
        {
            share.CreateIfNotExistsAsync();
        }
        catch (storageException)
        {
            infolog.add(exception::Error, "Unable to connect to Azure File Storage");
            throw exception::Error;
        }

        // Get a reference to the root directory of the share.

        CloudFileDirectory root = share.GetRootDirectoryReference();

        // Create a directory under the root directory

        CloudFileDirectory dir = root.GetDirectoryReference(DemoDirectory);
        dir.CreateIfNotExistsAsync();

        // Creating a new file in the directory created above and writing contents to the file
        // Also delete if exists

        CloudFile file = dir.GetFileReference(fileName);
        file.DeleteIfExistsAsync();
        file.UploadTextAsync(FileContents);

        // Uploading a local file to the directory created above

        //CloudFile file = dir.GetFileReference(ImageToUpload);
        //file.UploadFromFileAsync(ImageToUpload, System.IO.FileMode::Open);
    }

}

Friday, 20 September 2019

Filter the listpage Data source


public void initializeQuery(Query _query)
{
............................

....
else if (this.getListPageType() == PurchTableListPage::NkwWorkerDimensionView)
    {
        qbds = _query.dataSourceTable(tableNum(PurchTable));
        qbds.clearDynalinks();
        qbds = _query.dataSourceTable(tableNum(PurchTable)).addDataSource(tableNum(PurchLine));
        //qbds.addSortField(fieldnum(PurchLine, PurchId));
        //qbds.addOrderByField(fieldnum(PurchLine, PurchId));
        //qbds.orderMode(OrderMode::GroupBy);
        qbds.firstOnly(true);
        qbds.relations(true);
        qbds.fetchMode(0);
        //qbds.joinMode(JoinMode::ExistsJoin);
        qbds.addRange(fieldNum(PurchLine,DefaultDimension)).value(queryValue(HcmWorker::find(DirPersonUser::currentWorker()).getDefaultDimension()));
        qbds.addRange(fieldNum(PurchLine,Isdeleted)).value(queryValue(NoYes::No));

    }

Monday, 19 August 2019

Generate report through X++ and save as pdf in to folder EX:SalesInvoiceReport +D365


SrsReportRunController   controller = new SrsReportRunController();

        SalesInvoiceContract     rdpContract = new SalesInvoiceContract();
        SRSPrintDestinationSettings   settings;
        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();
        ;
        CustInvoiceJour custInvoiceJour = CustInvoiceJour::findFromSalesId_IN("SO081204");
        if(custInvoiceJour)
        {
            if (!WinAPI::pathExists("C:\\Temp\\Invoices\\"))
                WinAPI::createDirectoryPath("C:\\Temp\\Invoices\\");

            Filename filename =strfmt("C:\\Temp\\Invoices\\%1%2",custInvoiceJour.InvoiceId,".pdf");

            controller.parmReportName(ssrsReportStr(SalesInvoice, Report));
            controller.parmShowDialog(false);// Explicitly provide all required parameters
            rdpContract.parmRecordId(custInvoiceJour.RecId);
            controller.parmReportContract().parmRdpContract(rdpContract);// Change print settings as needed
            settings = controller.parmReportContract().parmPrintSettings();
            settings.printMediumType(SRSPrintMediumType::File);
            settings.fileFormat(SRSReportFileFormat::PDF);
            settings.overwriteFile(true);
            settings.fileName(filename);
            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());

            if (reportBytes)
            {
                System.IO.Stream            stream         = new System.IO.MemoryStream(reportBytes);
                var fileStream = new System.IO.FileStream(filename, System.IO.FileMode::Create, System.IO.FileAccess::ReadWrite);
                stream.CopyTo(fileStream);

            }
        }


==========================================================================
http://www.dnetsoft.com/en-us/d365-generate-a-report-through-x-and-save-in-a-local-folder/

Tuesday, 13 August 2019

XPO Interface

https://app.swaggerhub.com/apis-docs/xposc/FulfillmentServicesGateway/1.0.0#/Shipment/createShipment

Friday, 2 August 2019

Listpage Interaction class

1. Change Properties form control from listpage class example code.

public void initializeQuery(Query _query)
{
    // ListPageLabelChange =>
    Common              externalRecord;
    FormDataSource      frmDs;
    FormRun             formRun;
    FormControl         frmCtrl;
    // ListPageLabelChange <=
     
    _query.dataSourceTable(tableNum(HRSBenefitEntitlement)).addRange(fieldNum(HRSBenefitEntitlement,Employment)).value(SysQuery::value(HcmEmployment::findByWorkerLegalEntity(HcmWorker::userId2Worker(curUserId()),CompanyInfo::find().RecId).RecId));
     
    super(_query);
     
     // ListPageLabelChange =>
    externalRecord = this.listPage().activeRecord(_query.dataSourceTable(tableNum(HRSBenefitEntitlement)).name());//No intrisic function for form DS?
    if(externalRecord.isFormDataSource())
    {
        frmDs   = externalRecord.dataSource();
        formRun = frmDs.formRun();
        if(formRun)
        {
            frmCtrl = formRun.design().controlName(formControlStr(TIDBenefitEntitlementListPage,HRSBenefitEntitlement_Entitlement));
            if(frmCtrl)
            {
                frmCtrl.userPromptText("newName");
            }
        }
    }
    // ListPageLabelChange <=
}