Showing posts with label TO. Show all posts
Showing posts with label TO. Show all posts

Wednesday, November 22, 2017

HOW TO GET DAY OF THE WEEK IN MICROSOFT DYNAMICS AX

HOW TO GET DAY OF THE WEEK IN MICROSOFT DYNAMICS AX 
static void dayOfWkExample(Args _arg)
{
    date d = today();
    int i;
    ;
    i = dayOfWk(d);
    print "Today's day of the week is " + int2Str(i);
    pause;
}

Tuesday, November 21, 2017

SAVE REPORT TO PDF FROM AX JOB CONTROLLER CLASS : VIKAS MEHTA HOW TO CALL A REPORT FROM JOB AND SAVE IT IN PDF

SAVE REPORT TO PDF FROM AX JOB CONTROLLER CLASS : VIKAS MEHTA
HOW TO CALL A REPORT FROM JOB AND SAVE IT IN PDF

public static void SaveReportToPDFFromController(Args _args)
{
    VIKSalesInvoiceFinanceController  salesInvoiceController;
    VIKSalesInvoiceFinanceContract    salesInvoiceContract;
    Args                    args = new Args();
    SrsReportRunImpl        srsReportRun;
    CustInvoiceJour         custInvoiceJour;
    SRSReportExecutionInfo  reportExecutionInfo;
    ReportName              reportName = "VIKSalesFinance.PrecisionDesign1";//PrecisionDesign1_backup
    #define.ReportName('VIKSalesFinance.PrecisionDesign1')
    ;
    //SRSReportExecutionInfo = new SRSReportExecutionInfo();d
    select firstOnly custInvoiceJour where custInvoiceJour.SalesId == "1234”;
    args.record(custInvoiceJour);

    salesInvoiceController = new VIKSalesInvoiceFinanceController();
    salesInvoiceController.parmReportName(reportName);

    reportExecutionInfo = salesInvoiceController.parmReportContract().parmReportExecutionInfo() as SrsPrintMgmtExecutionInfo;

    if (!reportExecutionInfo)
    {
       reportExecutionInfo = new SrsPrintMgmtExecutionInfo();
    }
    //reportExecutionInfo.parmOriginalDestinationFileName("c:\\SalesInvoice.pdf");
    salesInvoiceContract = salesInvoiceController.parmReportContract().parmRdpContract();
    salesInvoiceContract.parmReportCopyName('');
    salesInvoiceContract.parmTenderTypeId('21');
    salesInvoiceContract.parmInvoiceId(custInvoiceJour.InvoiceId);
    salesInvoiceContract.parmSalesId(custInvoiceJour.SalesId);

  //  salesInvoiceContract.
   // salesInvoiceContract.parmRecordId(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty
   // salesInvoiceContract.parmInvoiceIdparm(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty
    salesInvoiceController.parmArgs(args);
    salesInvoiceController.parmReportName(#ReportName);
    salesInvoiceController.parmDialogCaption("Sales Finance Invoice");
     args.parm(strFmt("Copy - 1"));

    srsReportRun = salesInvoiceController.parmReportRun() as SrsReportRunImpl;

    salesInvoiceController.parmReportRun(srsReportRun);
    salesInvoiceController.parmReportContract().parmReportExecutionInfo(reportExecutionInfo);
    salesInvoiceController.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::File);
    salesInvoiceController.parmReportContract().parmPrintSettings().overwriteFile(true);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileFormat(SRSReportFileFormat::PDF);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileName("c:\\test123\\SREPORT.pdf");
    salesInvoiceController.runReport();
}

static void SaveReportToPDFFromController(Args _args)
{
    SalesInvoiceController  salesInvoiceController;
    SalesInvoiceContract    salesInvoiceContract;
    SRSPrintDestinationSettings     settings;
    Args                    args = new Args();
    SrsReportRunImpl        srsReportRun;
    CustInvoiceJour         custInvoiceJour;
    ReportName              reportName = "SalesInvoice.Report";
    ;

    select firstOnly custInvoiceJour where custInvoiceJour.invoiceid == "sid";
    args.record(custInvoiceJour);

    salesInvoiceController = new SalesInvoiceController();
    salesInvoiceController.parmReportName(reportName);

    salesInvoiceContract = salesInvoiceController.parmReportContract().parmRdpContract();
    salesInvoiceContract.parmRecordId(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty
  //  salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo()); // comment this code if tested in pre release
    salesInvoiceController.parmArgs(args);

    srsReportRun = salesInvoiceController.parmReportRun() as SrsReportRunImpl;

     salesInvoiceController.parmReportName(ssrsReportStr(VIKSalesFinance, PrecisionDesign1));
    // Use execution mode appropriate to your situation
  //  salesInvoiceController.parmExecutionMode(SysOperationExecutionMode::ScheduledBatch);
    // Suppress report dialog
    salesInvoiceController.parmShowDialog(false);

    salesInvoiceController.parmReportRun(srsReportRun);
    salesInvoiceController.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::File);
    salesInvoiceController.parmReportContract().parmPrintSettings().overwriteFile(true);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileFormat(SRSReportFileFormat::PDF);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileName("c:\\VIKAS\\sdc.pdf");


    settings = salesInvoiceController.parmReportContract().parmPrintSettings();
    settings.printMediumType(SRSPrintMediumType::File);
    settings.fileFormat(SRSReportFileFormat::PDF);
    settings.fileName(@'c:\\TEST\1234.pdf');

    salesInvoiceController.startOperation();
}



p EXPORT TO CSV WITH DATE DIRECT JOB X++ : VIKAS MEHTA :MICROSOFT DYNAMICS AX X++ CODE

EXPORT TO CSV DIRECT JOB X++ WITH DATE : VIKAS MEHTA


public static void export2csvInvJourTrans(InventJournalId _invJournalId)
{
    container           con, conHeader;
    InventJournalTrans  invJourTrans;
    InventJournalTable  invJourTable;
    InventDim           invDim;
    CommaIo              io;

    Dialog              dialog;
    DialogField         dlgFileName;
    Filename            csvfileName;
    FileIOPermission    permission;

    int                 recordCount = 0;

    SysOperationProgress exportprogress = new SysOperationProgress();

    #File
    #AviFiles


    ;


    try
    {
        exportprogress.setCaption("Exporting journal lines to CSV file....");
        exportprogress.setAnimation(#AviTransfer);

        // Header Column

        conHeader = ["JournalId","Date","ItemId","Description","LineNum","Site","Warehouse","Location","SerialNumber","OnHand","Counted","Quantity"];

        dialog = new Dialog("Export to CSV");
        dialog.filenameLookupFilter(["Excel Files","*.csv"]);
        dlgFileName = dialog.addField(extendedTypeStr(FilenameSave),"File Name");

        if(dialog.run())
        {
            csvfileName = dlgFileName.value();
            if(csvfileName)
            {
                permission = new FileIOPermission(csvfileName,#io_write);
                permission.assert();

                io = new CommaIo(csvfileName,#io_write);

                io.inFieldDelimiter(',');


                if(!io || io.status() != IO_Status::Ok)
                {
                    throw error("Error in opening file!");
                }

                // Write the header column
                io.writeExp(conHeader);

                invJourTable = InventJournalTable::find(_invJournalId);

                if(!invJourTable.Posted)
                {
                    recordcount = 1;
                    while select * from invJourTrans where invJourTrans.JournalId == _invJournalId
                    {
                         // Create rows
                        invDim   = InventDim::find(invJourTrans.InventDimId);

                        con= [ _invJournalId,
                               date2str(invJourTrans.TransDate,123,-1,-1,-1,-1,-1),
                               invJourTrans.ItemId,
                               invJourTrans.itemName(),
                               invJourTrans.LineNum,
                               invDim.InventSiteId,
                               invDim.InventLocationId,
                               invDim.wMSLocationId,
                               invDim.inventSerialId,
                               num2str(invJourTrans.InventOnHand,1,2,1,0),
                               num2str(invJourTrans.Counted,1,2,1,0),
                               num2str(invJourTrans.Qty,1,2,1,0)
                            ];

                        io.writeExp(con);

                        recordCount++;
                    }
                }


                CodeAccessPermission::revertAssert();


            }
            else
            {
                info("Invalid file name specified!");
            }
        }


    }
    catch(Exception::Error)
    {
        throw error("Erorr in exporting journal lines.");
    }

}


HOW TO CONNECT TO SQL FROM AX AND UPDATE HOW TO CONNECT TO EXTERNAL DATABASE FROM AX HOW TO UPDATE RECORDS IN SQL FROM AX : DYNAMICS AX X++ CODE

HOW TO CONNECT TO SQL FROM AX AND UPDATE
HOW TO CONNECT TO EXTERNAL DATABASE FROM AX
HOW TO UPDATE RECORDS IN SQL FROM AX

1) fIRST CREATE AN ODBC CONNECTION FROM THE SYSTEM TO CONNECT TO THE REQUIRED DATABASES.
// X++, Main method in a class.
static public void Main(Args _args)
{
    LoginProperty loginProperty;
    OdbcConnection odbcConnection;
    Statement statement;
    ResultSet resultSet;
    str sql, criteria;
    SqlStatementExecutePermission perm;
    ;

    // Set the information on the ODBC.
    loginProperty = new LoginProperty();
    loginProperty.setDSN("dsnName");
    loginProperty.setDatabase("databaseName");

    //Create a connection to external database.
    odbcConnection = new OdbcConnection(loginProperty);

    if (odbcConnection)
    {
        sql = "SELECT * FROM MYTABLE WHERE FIELD = "
            + criteria
            + " ORDER BY FIELD1, FIELD2 ASC ;";

        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();

        //Prepare the sql statement.
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);

        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (resultSet.next())
        {
            //It is not possible to get field 3 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print resultSet.getString(1);
            print resultSet.getString(3);
        }

        //Close the connection.
        resultSet.close();
        statement.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}

HOW TO ADD RANGE USING EXPRESSIONS IN QUERY (strFmt('((%1.%2 ==) IN MICROSOFT DYNAMICS AX X++ CODE

HOW TO ADD RANGE USING EXPRESSIONS IN QUERY  strFmt('((%1.%2 ==
IN MICROSOFT DYNAMICS AX X++ CODE

static void AddRangeToQuery(Args _args)
{
    Query q = new Query();  // Create a new query.
    QueryRun qr;
    CustTable ct;
    QueryBuildDataSource qbr1;
    str strTemp;
    ;

    // Add a single datasource.
    qbr1 = q.addDataSource(tablenum(CustTable));
    // Name the datasource 'Customer'.
    qbr1.name("Customer");

    // Create a range value that designates an "OR" query like:
    // customer.AccountNum == "4000" || Customer.CreditMax > 2500.

    // Add the range to the query data source.
    qbr1.addRange(fieldNum(CustTable, AccountNum)).value(
    strFmt('((%1.%2 == "4000") || (%1.%3 > 2500))',
        qbr1.name(),
        fieldStr(CustTable, AccountNum),
        fieldStr(CustTable, CreditMax)));

    // Print the data source.
    print qbr1.toString();
    info(qbr1.toString());

    // Run the query and print the results.
    qr = new QueryRun(q);

    while (qr.next())
    {
        if (qr.changedNo(1))
        {
            ct = qr.getNo(1);
            strTemp = strFmt("%1 , %2", ct.AccountNum, ct.CreditMax);
            print strTemp;
            info(strTemp);
        }
    }
    pause;
}

Convert Date to UTCDateTime : DYNAMICS AX X++ CODE

Convert Date to UTCDateTime

static void ConvertDate2DateTime_vm(Args _args)
{
    TransDate       fromDate,toDate;
    TimeZone        tzone;
    UtcDateTime     fDateTime,tDateTime;
    ;
    
    fromDate    = mkDate(01,06,2017);
    toDate        = mkDate(30,08,2017);
    fDateTime   = Global::datetobeginUtcDateTime(fromDate,tzone);
    tDateTime   = Global::datetoendUtcDateTime(toDate,tzone);
    print fDateTime;
    print tDateTime;
 }

AX MICROSOFT DYNAMICS X++ CODE CONVERT DATE TO NUMBER

CONVERT DATE TO NUMBER

date2num(_fromdate))

Thursday, June 8, 2017

How to Upload License in Microsoft Dynamics AX 2012 :MICROSOFT DYNAMICS AX 2012

How to Upload License in Microsoft Dynamics AX 2012 :MICROSOFT DYNAMICS AX 2012

Go To System administration > Setup > Licensing > License information.
Then Click Load license file to import the license codes from a file and select license file.
Click  OK button.

This will also Synchronize the database.


HOW TO REMOVE BLANK SPACES IN AX: AX 2012 MICROSOFT DYNAMICS AX 2012 :AX 2009

HOW TO REMOVE BLANK SPACES IN AX: AX 2012 

MICROSOFT DYNAMICS AX 2012 :AX 2009


Just replace the code with the below syntax.

strRTrim(strLTrim(Dirpartytable.Name));  

Thursday, May 4, 2017

MICROSOFT DYNAMICS AX 2012 : HOW TO USE QUERYHAVINGFILTER IN AX 2012: QUERY WITH GROUP CONDITION

How to use QueryHavingFilter in AX 2012

 QueryHavingFilter:

Consider the following scenario. The CUSTTABLE table has a field called CUSTGROUP, indicating the customer group the customer belongs to. We would like to get a list of all customer groups that have less than 4 customers in them.
Traditionally, in AX queries, we can group by the CUSTGROUP field, COUNT the RecIds. However, there was no way to filter on that counted RecId field. However, in SQL, the having statement gives you that ability:

SELECT CUSTGROUP, COUNT(*) FROM CUSTTABLE
        GROUP BY CUSTGROUP
        HAVING COUNT(*) < 4

In AX you can count, group by, but you'll need to loop over the results and check the counter manually if you want to filter values out. So, in AX 2012, a new query class was added: QueryHavingFilter, that lets you do just that:

static void QueryHaving(Args _args)
{
    Query                   query;
    QueryBuildDataSource    datasource;
    QueryBuildRange         range;
    QueryHavingFilter       havingFilter;
    QueryRun                queryRun;
    int                     counter = 0, totalCounter = 0;
    CustTable               custTable;
   
    query = new Query();
    datasource = query.addDataSource(tableNum(CustTable));
    datasource.addSelectionField(fieldNum(CustTable, RecId),
            SelectionField::Count);
    datasource.orderMode(OrderMode::GroupBy);
    datasource.addGroupByField(fieldNum(CustTable, CustGroup));
   
    havingFilter = query.addHavingFilter(datasource, fieldStr(custTable, RecId),
            AggregateFunction::Count);
    havingFilter.value('<4 o:p="">
   
    queryRun = new QueryRun(query);
    while (queryRun.next())
    {
        custTable = queryRun.getNo(1);
        info(strFmt("Group %1: %2", custTable.CustGroup, custTable.RecId));
    }
}


Note that in this code example, I added a selection field on RecId and used SelectionField::Count. This is not necessary for the having filter to work, the only reason it is in the code example is to be able to show it in the infolog (ie to have the count value available). So it is independent of the HavingFilter!


MICROSOFT DYNAMICS AX 2012 : CODE TO GET ON HAND OF AN ITEM STOCK COUNT

MICROSOFT DYNAMICS AX 2012 : GET ON HAND OF AN ITEM STOCK COUNT
static void stockOnHand(Args _args)
{
    InventOnhand        inventOnHand;
    InventDim           inventDim;
    InventDimParm       inventDimParm;
    InventQty           stockOnHand;
    ItemId              itemid = "00001aTestInter";
 
    inventDim.InventSiteId = "SITE"; // site
    inventDim.InventLocationId = "WAREHOUSE"; // warehouse
 
 
    inventDimParm.initFromInventDim(inventDim);
 
    inventOnHand = InventOnhand::newParameters(itemid,inventDim,inventDimParm);
 
    stockOnHand = inventOnHand.availPhysical();
 
    info (strFmt(" Stock on Hand for Item %1 is %2",itemid,stockOnHand));
 
}

MICROSOFT DYNAMICS AX 2012 : CODE TO DEPLOY SERVICE FROM AX

DEPLOY AX SERVICES FROM CODE

Below is the script for automatically deploy or undeploy  AIF service.
In this example update the port with current company and deploy the service.
static void AIFservices(Args _args)
{
    AifPort  port;
    AifPortName portName = "servicename";
    AifPortManager::undeployPort(portName);
    port = AifPort::find(portName,true);

    if(port)
    {
        ttsBegin;
        if(port.Company != curext() )
        {
            port.Company = curext();
            port.update();
        }
        ttsCommit;
    }
    AifPortManager::deployPort(portName);
}

Monday, April 18, 2016

HOW TO CREATE A DIALOG IN DYNAMICS AX : X++ CODE

CREATE A DIALOG IN AX : X++ CODE 


class CustDialog extends RunBase
{
DialogField fieldAccount;
DialogField fieldName;
DialogField fieldGroup;
DialogField fieldCurrency;
}

pack() and unpack(0 are used to retain the last used values.
public container pack()
{
return conNull();
}
public boolean unpack(container _packedClass)
{
return true;
}
protected Object dialog()
{

Dialog dialog;
DialogGroup groupCustomer;
DialogGroup groupPayment;
dialog = super();
dialog.caption("Customer information"); dialog.allowUpdateOnSelectCtrl(true);
fieldAccount = dialog.addField(
extendedTypeStr(CustAccount), "Customer account");
fieldName = dialog.addField(extendedTypeStr(CustName));
fieldName.enabled(false);
dialog.addTabPage("Details");
groupCustomer = dialog.addGroup("Setup");
fieldGroup = dialog.addField(
extendedTypeStr(CustGroupId)); fieldCurrency = dialog.addField(
extendedTypeStr(CurrencyCode)); fieldGroup.enabled(false);
fieldCurrency.enabled(false);
groupPayment = dialog.addGroup("Payment");
return dialog;
}

Below method is used to dynamically assign the different values of the cust table
public void dialogSelectCtrl()
{
CustTable custTable;
custTable = CustTable::find(fieldAccount.value()); fieldName.value(custTable.name()); fieldGroup.value(custTable.CustGroup); fieldCurrency.value(custTable.Currency);
}
public static void main(Args _args)
CustSelect custSelect = new CustSelect();
if (CustSelect.prompt()) {
CustSelect.run();
}
}

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++
PUBLIC VOID READCOMMAFILE()
{
CommaTextIo         file;
container           line;
#define.filename(@'C:\\accounts.csv') #File
file = new CommaTextIo(#filename, #io_read);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
line = file.read();
while (file.status() == IO_Status::Ok)
{
info(con2Str(line, ' - '));
line = file.read();
                }


}

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE
public void createcommafiles()
{
CommaTextIo         file;
container            line;
MainAccount           mainAccount;
#define.filename(@'C:\accounts.csv') #File
file = new CommaTextIo(#filename, #io_write);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
while select MainAccountId, Name from mainAccount
{
line = [
mainAccount.MainAccountId,
mainAccount.Name];
file.writeExp(line);
}
info(strFmt("File %1 created.", #filename));

}

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE FOR A TABLE

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE 
FOR A TABLE

static void TabledocuAdd(Args _args) {
DocuRef      docuRef;
VendTable vendTable;
vendTable = VendTable::find('123');
docuRef.RefCompanyId = vendTable.dataAreaId;
docuRef.RefTableId    = vendTable.TableId;
docuRef.RefRecId        = vendTable.RecId;
docuRef.TypeId        = 'Note';
docuRef.Name            = 'Imported';
docuRef.Notes         = 'This vendor was imported.';
docuRef.insert();

}
Related Posts Plugin for WordPress, Blogger...