Home

Monday, March 31, 2014

Forms importent methods in Ax

Form Method


FormDataSource.Init
This method initializes the data source and is called from the super() of FormRun.Init(). The method is only called once when the form opens. The main task for this method is to initialize the query used for fetching data. To modify or replace the query automatically created by the form, do this after
the super() call of this method.

FormDataSource.InitValue
This method is used to initialize a new record with default values. The super() of this method calls the initValue() method on the underlying table. If you have initialization that applies system-wide, put the code on the table.

FormDataSource.Active
This event is called when a new record becomes active in the data source. This method is typically overridden to change properties which depend on the contents of the current record: Commonly this method will:
• Modify permissions to the data source
• Modify permissions to the fields
• Enable/Disable buttons

FormDataSource.LinkActive
This method is the engine that joins data sources. This method is called on the joined data source every time that the active record in the main data source is changed. The method is also called when the form is opened as the system tries to join the calling data source to the main data source of the called form.

FormDataSource.ValidateWrite
This method validates an insert or update of a record. The super() of this method calls the corresponding method on the underlying table. If you need to distinguish between an insert and update, make a condition on the RecId field, which only has a value if it is an update.

FormDataSource.Write

This method controls the insert and update of records. The super() of this method calls the corresponding method on the underlying table. If you have form-specific tasks to perform in relation to the commitment of the record, add it here.

Sunday, March 30, 2014

Sound in ax 2012

static void ExemploPlaySound(Args _args)
{
    System.Media.SoundPlayer YourMPlayer;
    ;
    YourMPlayer= new System.Media.SoundPlayer();
    YourMPlayer.set_SoundLocation("c:\\xyz.wav");
    YourMPlayer.Play();
}

-Harry

Thursday, March 27, 2014

AX2012 R2: Creating Product or Product Master through X++

static void CreateEcoResProduct(Args _args)
{
    EcoResEcoResProduct_TrackingDimGroup        tracDimGroup;
    EcoResEcoResProduct_Product_Master          productMaster;
    EcoResEcoResProduct_Product_Distinct        distMaster;
    EcoResEcoResProduct_ProductDimGroup         prodDimGroup;
    EcoResEcoResProduct_StorageDimGroup         storDimGroup;
    EcoResEcoResProduct_translation             translation;
    EcoResEcoResProduct_Identifier              identifier;
    EcoResProductService                        ecoProdSvc;
    EcoResProductNumber                         lEcoResProductNumber;
    NumberSequenceTable                         numberSequenceTable;
    EcoResEcoResProduct                         ecoResProd;
    EcoResProductType                           ecoResProductType;
    boolean                                     isMaster = false;
    EcoResProductSearchName                     _ecmProductName;
    EcoResProductSubtype                        prodSubType;
    ;

    prodSubType = EcoResProductSubtype::ProductMaster;
    _ecmProductName = " IDB test 09";
    lEcoResProductNumber = "IDB -099";

    try
    {
        // create product by initializing the Service object
        ecoProdSvc = EcoResProductService::construct();

        // initialize the EcoResEcoResProduct object
        ecoResProd = new EcoResEcoResProduct();

       // numberSequenceTable = EcoResProductParameters::numRefProductNumber().numberSequenceTable(); // Automated

      //  lEcoResProductNumber = NumberSeq::newGetNumFromId(numberSequenceTable.RecId).num(); // Automated


        ecoResProductType = EcoResProductType::Item;

        if(prodSubType == EcoResProductSubtype::ProductMaster)
        {
            isMaster = true;

            //Create a new product master
            productMaster = new EcoResEcoResProduct_Product_Master();

            //initialize product master
            productMaster.parmDisplayProductNumber(lEcoResProductNumber);
            productMaster.parmProductType(ecoResProductType);
            productMaster.parmSearchName(_ecmProductName);
            productMaster.parmProductType(EcoResProductType::Service);

            productMaster.parmVariantConfigurationTechnology(EcoResVariantConfigurationTechnologyType::PredefinedVariants);

            //create a product master Translation Object
            translation = productMaster.createTranslation().addNew();

            // create a new identifier object
            Identifier = productMaster.createIdentifier().AddNew();

            // Create the ProductDimensionGroup
            prodDimGroup = productMaster.createProductDimGroup().addNew();
            prodDimGroup.parmProduct(lEcoResProductNumber);

            prodDimGroup.parmProductDimensionGroup('Con-Dim');

            // Create the StorageDimgroup object
            storDimGroup = productMaster.createStorageDimGroup().addNew();
            storDimGroup.parmProduct(lEcoResProductNumber);
            storDimGroup.parmStorageDimensionGroup("Con-Dim"); // Storage dimension group

            // Create the TrackingDimGroup object
            tracDimGroup = productMaster.createTrackingDimGroup().addNew();
            tracDimGroup.parmProduct(lEcoResProductNumber);
            tracDimGroup.parmTrackingDimensionGroup("Con-Dim"); // Tracking dimension group
        }
        else
        {
            // Create a new product distinct master
            distMaster = new EcoResEcoResProduct_Product_Distinct();

            // Take the newly created and initialize ProdMaster - variable and fill with product data
            distMaster.parmDisplayProductNumber(lEcoResProductNumber);
            distMaster.parmProductType(ecoResProductType);
            distMaster.parmSearchName(_ecmProductName);

            // Create a translation object
            translation = distMaster.createTranslation().addNew();

            // Create a new identifier object
            Identifier = distMaster.createIdentifier().addNew();

            // Create the StorageDimgroup object
            storDimGroup = distMaster.createStorageDimGroup().addNew();
            storDimGroup.parmProduct(lEcoResProductNumber);
            storDimGroup.parmStorageDimensionGroup("Con-Dim");

            // Create the TrackingDimGroup object
            tracDimGroup = distMaster.createTrackingDimGroup().addNew();
            tracDimGroup.parmProduct(lEcoResProductNumber);
            tracDimGroup.parmTrackingDimensionGroup("Con-Dim");
        }

        // fill the translation object
        translation.parmDescription(_ecmProductName);
        translation.parmLanguageId('en-us');

        //translati
        translation.parmName(_ecmProductName);

        // fill the identifier
        identifier.parmProductNumber(lEcoResProductNumber);

        // add the product to ecoResProd
        if(isMaster)
            ecoResProd.createProduct().add(productMaster);
        else
            ecoResProd.createProduct().add(distMaster);

        // create the product using service
        ecoProdSvc.create(ecoResProd);
    }
    catch(Exception::Error)
    {
        throw Exception::Error;
    }
    catch(Exception::Deadlock)
    {
        retry;
    }
    catch(Exception::UpdateConflict)
    {
        if(appl.ttsLevel() == 0)
        {
            if(xSession::currentRetryCount() >= 4)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }
}

Wednesday, March 12, 2014

Set focus on specific control when opening form

To set the focus on specific control when form is open, you need to override the firstField() method of the form and set your desired control after super() call.

public void firstField(int _flags=1)
{
    ;
    super(_flags);
    desiredControlName.setFocus();
}

ax code 2009

static void Job38(Args _args)
{
    InventDimSetup  InventDimSetup;
    ;
    ttsbegin;
    select forupdate InventDimSetup where  InventDimSetup.RecId == 5637152344
                                       && InventDimSetup.dimGroupId == 'scsw';
     {
    //5637152344
        info (strfmt("%1,%2", InventDimSetup.Active,InventDimSetup.RecId));
        InventDimSetup.Active = Noyes::Yes;
        //InventDimSetup.Update();
       info (strfmt("%1,%2", InventDimSetup.Active,InventDimSetup.RecId));
    }
    ttscommit;
}

Tuesday, March 11, 2014

Under Stand Joins in X++ code

1-Create Two Tables
   i-Student with Fields Id and Name



  ii-Student Assignment with fields AddressCity and Id


2- Create a normal relation in Student Assignment Table in relation node
     StudentAssignment.Id == Student.Id

3- Write a job to find which data will come while using join statement in X++ code for these Tables
   static void Student(Args _args)
{
  Student student;
    StudentAssignment studentAssignment;

    while select student  join studentAssignment where student.Id == StudentAssignment.Id
    {
        info(strfmt("%1",student.Name));
    }

}

OutPut ---->

Monday, March 10, 2014

Alphabets In String Ax

static void AlphabetsInString(Args _args)
{
TextBuffer txt = new TextBuffer();
str msg = "AbcdAzjjtref59995";
;

txt.setText(msg);
txt.regularExpressions(true); // activate regular expr in search

// Regular expression to validate only alphabets
if (txt.find("^[A-Z]+$"))
{
info("String contains only Alphabets");
}
else
{
info("String contains others characters");
}

}

Text buffer class Example

static void TxtB(Args _args)
{

TextBuffer buffer;
str vlu;
;

vlu = "somendra.Pratap.singh";
   
buffer = new TextBuffer();
buffer.setText(vlu);

while (buffer.nextToken(0, '.'))
{

info (buffer.token());

}
}
output:  Somendra
             pratap
             singh
             

Friday, March 7, 2014

listen beep through Axapta code

 static void exicuteExcs(Args _args)
{
    ;
    WINAPI::beep(100000,10000);

}

Wednesday, March 5, 2014

Get Database Name Axapta

static void DatabaseName(Args _args)
{
    ;
    info(SysSQLSystemInfo::construct().getloginDatabase());


}

Get employee detail by code Ax 2012

static void EmployeeDetails(Args _args)
{
    HcmWorker                     hcmWorker;
    DirPartyTable                 dirPartyTable;
    DirPartyLocation              dirPartyLocation;
    LogisticsPostalAddress        logisticsPostalAddress;
    LogisticsLocation             logisticsLocation;
    HcmPersonPrivateDetails       hcmPersonPrivateDetails;
    HcmEmployment                 hcmEmployment;
    LogisticsElectronicAddress    logisticsElectronicAddress;
    HcmWorkerTitle                hcmWorkerTitle;
    HcmTitle                      hcmTitle;
    HcmPositionWorkerAssignment   hcmPositionWorkerAssignment;
    HcmPositionDetail             hcmPositionDetail;
    HcmPosition                   hcmPosition;
    HcmJob                        hcmJob;
    OMOperatingUnit               oMOperatingUnit;
    ;

    select hcmWorker where hcmWorker.Person == 5637144585
    join dirPartyTable where dirPartyTable.RecId == hcmWorker.Person
    join hcmPersonPrivateDetails where hcmPersonPrivateDetails.Person == hcmWorker.Person
    join hcmEmployment where hcmEmployment.Worker == hcmWorker.RecId
    join dirPartyLocation where dirPartyLocation.Party == dirPartyTable.RecId
    join logisticsPostalAddress where logisticsPostalAddress.Location == dirPartyLocation.Location;

    select dirPartyLocation where dirPartyLocation.Party == dirPartyTable.RecId
    join logisticsLocation where logisticsLocation.RecId == dirPartyLocation.Location
    join logisticsElectronicAddress where logisticsElectronicAddress.Location == logisticsLocation.RecId
    && logisticsElectronicAddress.Type == LogisticsElectronicAddressMethodType::Phone;



    while select hcmPositionWorkerAssignment where hcmPositionWorkerAssignment.Worker == hcmWorker.RecId
    join hcmPosition where hcmPosition.RecId == hcmPositionWorkerAssignment.Position
    join hcmPositionDetail  where hcmPositionDetail.Position == hcmPosition.RecId
    join hcmJob where hcmJob.RecId == hcmPositionDetail.Job
    join oMOperatingUnit where  oMOperatingUnit.RecId == hcmPositionDetail.Department
          && oMOperatingUnit.OMOperatingUnitType == OMOperatingUnitType::OMDepartment
       {
            info(strFmt("Name of Worker : %1 , Date of Birth : %2 , Date Of Joining : %3 , Address : %4 , Phone : %5, Department : %6 ,  Postion : %7 , Designation : %8 , Job : %9" ,
            dirPartyTable.Name,hcmPersonPrivateDetails.BirthDate,hcmEmployment.ValidFrom,logisticsPostalAddress.Address,logisticsElectronicAddress.Locator,
            oMOperatingUnit.Name,hcmPosition.PositionId,hcmPositionDetail.Description,hcmJob.JobId));
       }


 }

=====================================================================
2---
static void Jobswa(Args _args)
{
    HcmWorker                   hcmWorker;
    HcmPosition                 hcmPosition;
    HcmPositionDetail           hcmPositionDetail;
    HcmJob                      hcmJob;
    HcmEmployment               hcmEmployment;
    DirPerson                   dirPerson;
    DirPartyPostalAddressView   dirPartyPostalAddressView;
    HcmPersonPrivateDetails     hcmPersonPrivateDetails;
    OMOperatingUnit             OMOperatingUnit;
    HcmMyDepartments            hcmMyDepartments;
    HcmPositionWorkerAssignment hcmPositionWorkerAssignment



    ;

     select hcmWorker where hcmWorker.Person == 5637144585                          join dirPerson where
                           hcmWorker.Person == dirPerson.RecId                      join hcmPersonPrivateDetails where
                           dirPerson.RecId == hcmPersonPrivateDetails.Person        join hcmEmployment where
                           hcmWorker.RecId ==   hcmEmployment.Worker  join OMOperatingUnit where
                           OMOperatingUnit.HcmWorker == hcmWorker.RecId             join hcmMyDepartments where
                           hcmMyDepartments.DepartmentRecId == OMOperatingUnit.RecId;
    {


        info(strFmt("startdate : %1",hcmEmployment.ValidFrom));
        info(strFmt("Workerid :%1", hcmWorker.PersonnelNumber));
        info(strFmt("Person name: %1",dirPerson.Name));
        info(strFmt("Date of birth: %1",hcmPersonPrivateDetails.BirthDate));
        info(strFmt("Department : %1",hcmMyDepartments.DepartmentRecId));

        while select hcmPositionWorkerAssignment where

                     hcmPositionWorkerAssignment.Worker ==   hcmWorker.RecId   join  hcmPosition where
                     hcmPositionWorkerAssignment.Position == hcmPosition.RecId join hcmPositionDetail where
                     hcmPosition.RecId == hcmPositionDetail.Position join hcmJob where
                     hcmPositionDetail.Job == hcmJob.RecId

        {

            info(strFmt("worker position : %1",hcmPosition.PositionId));
             info(strFmt("worker Job : %1",hcmJob.JobId));

        }
    }




}

How to use join in X++ code

static void DemoJoins(Args _args)
{
    CustTable       custTable;
    DirPartyTable   dirPartyTable;


    while select dirPartyTable order by Name desc join custTable
                  where custTable.Party == dirPartyTable.RecId
    {
        info(strFmt('%1 %2',dirPartyTable.Name, custTable.AccountNum));
    }

}
==================================================================
static void vivek_test(Args _args)
{
SPLPayIncomeTaxDefination       IncomeTaxSetup;
    SPLPayIncomeTaxHead             IncomeTaxHead;
    //SPLPayFormula                   Formula;
    //TransDate                       RunDate;
    AmountCur                       YearlyAmount;
    //AmountCur                       MonthlyAmount;
    TransDate                       salarymonth,x;
    ;
    x = systemdateget();
    info(strfmt("%1",x));
    salarymonth = 5\3\2012;
  while select IncomeTaxHead order by SequenceNo
        where   IncomeTaxHead.Nature    ==  SPLPaynature::IncomeTax
        join IncomeTaxSetup
            where   IncomeTaxSetup.IncomeTaxHeadId ==    IncomeTaxHead.IncomeTaxHeadId
            &&      IncomeTaxSetup.FinancialStart    <=    SalaryMonth
            &&      IncomeTaxSetup.FinancialEnd      >=    SalaryMonth

            {
                if(IncomeTaxSetup.FinancialStart    <=    SalaryMonth)
                    info("done");
            }
     if(x == salarymonth)
     {
        info("double");
     }
}
==================================================================

Create simple excel File Ax-2012

static void SomesCreateExl(Args _args)
{
   SysExcelApplication  xlsApplication;
   SysExcelWorkBooks    xlsWorkBookCollection;
   SysExcelWorkBook     xlsWorkBook;
   SysExcelWorkSheets   xlsWorkSheetCollection;
   SysExcelWorkSheet    xlsWorkSheet;
   SysExcelRange        xlsRange;
   CustTable            custTable;
   int                  row = 1;
   str                  fileName;
   ;
   //Filename
   fileName = "E:\\Test.xlsx";
   //Initialize Excel instance
   xlsApplication           = SysExcelApplication::construct();
   //Open Excel document
   //xlsApplication.visible(true);
   //Create Excel WorkBook and WorkSheet
   xlsWorkBookCollection    = xlsApplication.workbooks();
   xlsWorkBook              = xlsWorkBookCollection.add();
   xlsWorkSheetCollection   = xlsWorkBook.worksheets();
   xlsWorkSheet             = xlsWorkSheetCollection.itemFromNum(1);
   //Excel columns captions
   xlsWorkSheet.cells().item(row,1).value("Account Num");
   xlsWorkSheet.cells().item(row,2).value("InvoiceAddress");
    xlsWorkSheet.cells().item(row,3).value("BankAccount");
    xlsWorkSheet.cells().item(row,4).value("CreditMax");
    xlsWorkSheet.cells().item(row,5).value("Currency");
   row++;
   //Fill Excel with CustTable AccountNum and Name fields (only 20 records)
   while select custTable
   {
      if(row == 71)
        break;
      xlsWorkSheet.cells().item(row,1).value(custTable.AccountNum);
      xlsWorkSheet.cells().item(row,2).value(custTable.InvoiceAddress);
      xlsWorkSheet.cells().item(row,3).value(custTable.BankAccount);
       xlsWorkSheet.cells().item(row,4).value(custTable.CreditMax);
        xlsWorkSheet.cells().item(row,5).value(custTable.Currency);

      row++;
   }
   //Check whether the document already exists
   if(WinApi::fileExists(fileName))
      WinApi::deleteFile(fileName);
   //Save Excel document
   xlsWorkbook.saveAs(fileName);
   //Open Excel document
   xlsApplication.visible(true);
   //Close Excel
   //xlsApplication.quit();
   //xlsApplication.finalize();
}

Copy Data From Xml File to Table in ax 2012

static void XML2AXTABLE(Args _args)
{
    MyTables mt;
    XMLDocument XMLdoc = XMLDocument::newFile(@"D:\\Somendra\\accounts.xml");
int i,CountItemtags=100;
;
    XMLdoc.load(XMLdoc.toString());

for (i = 0 ; i < countItemTags; i++)
{
mt.AccountNum =( xmldoc.getElementsByTagName('AccountNum').item(i).text());
mt.BankAccount=( xmldoc.getElementsByTagName('BankAccount').item(i).text());
  countItemTags = xmldoc.getElementsByTagName('AccountNum').length();
   mt.insert();
}
}

Copy data from Ax to Xml File in ax 2012

static void JobAxToXML(Args _args)
{
    XmlDocument doc;
XmlElement nodeXml;
XmlElement nodeTable;
XmlElement nodeAccount;
XmlElement nodeName;
CustTable CustTable;
#define.filename('D:\\Somendra\\accounts.xml')
;
doc = XmlDocument::newBlank();
nodeXml = doc.createElement('xml');
    doc.appendChild(nodeXml);
while select CustTable
{
nodeTable = doc.createElement(tablestr(CustTable));
nodeTable.setAttribute(
fieldstr(CustTable, RecId),
int642str(CustTable.RecId));
nodeXml.appendChild(nodeTable);
nodeAccount = doc.createElement(
fieldstr(CustTable, AccountNum));
nodeAccount.appendChild(
doc.createTextNode(CustTable.AccountNum));
nodeTable.appendChild(nodeAccount);
nodeName = doc.createElement(
fieldstr(CustTable,BankAccount));
nodeName.appendChild(
doc.createTextNode(CustTable.BankAccount));
nodeTable.appendChild(nodeName);
}
doc.save(#filename);
}

Monday, March 3, 2014

Creating a custom compiler output type and displaying in the compiler output in Dynamics Ax 2009

This article will guide in creating a custom compiler output Type like “To Do” , “Error” and “Best Practices” in Dynamics Ax 2009.


0. First change your compiler to “Message window” until you complete this. Retaining it as “Form” might result in runtime errors which cannot be resolved. This is because it will stop your compiler from executing and consequently any further progress.
1. Add a element to the enum “SysCompilerOutput”. Let’s call it “Custom”
2. Add a new datasource to the Form “SysCompilerOutput” for the table “TmpCompilerOutput”. Name it “Custom”. Also create a tab, grid and drag fields to it.
3. Now override the “init” method of the datasource and write the following code.
public void init()
{
    QueryBuildRange range;
    ;
    super();
    range = this.query().dataSourceNo(1).addRange(fieldnum(TmpCompilerOutput, SysCompilerOutputTab));
    range.value(queryValue(SysCompilerOutputTab::Custom));
    range.status(RangeStatus::Hidden);
}


4. Go to class “ClassesSysCompilerOutput” and create a global variable “Custom_Ds” and create a parm method for this datasource like “ClassesSysCompilerOutputparmBestPractices_ds
5. Go to “ClassesSysCompilerOutputupdateDataSources ” and add the following lines
?
1
2
this.updateCursor(custom_ds, tmpCompilerOutput);
custom_ds.research();
6. Now change your compiler output to “Form”
7. Run the following Job to test it.
?
1
2
3
4
5
6
7
8
9
10
static void JobTestCompiler(Args _args)
{
    SysCompileroutput     output;
    ;
 
    output = infolog.compilerOutput();
 
    output.compilerOutputMessage('Custom Message 1', 66, 1, 2, 3, 'Just a try', 'Method name', SysCompilerOutputTab::Custom);
    output.compilerOutputMessage('Custom Message 2', 85, 1, 2, 3, 'Second Try', 'Property name', SysCompilerOutputTab::Custom);
}

8. Now you can make the above call from any place in the application to add contents to the compiler output tab.