Search This Blog

Friday, March 30, 2012

AX2012 Import HCMWorker or Employee from CSV

This is the sample code for creating the Employee and if employee exists then updating the employee.
First build the class to read from CSV file and call this methods for creating/updateing the worker.
Please change the container column number values from your csv positions.

we can use HCMWorkerImportService for create, but this service did'nt provide the update functionality.
I will update the the next post using service to create/update the employee.

private void run()
{

 if (!HcmWorker::findByPersonnelNumber(conPeek(_c, #EmployeeNumber)).RecId)
        {//Update employee
            this.employeeCreate(_c);
        }
        else
        {//Insert employee
            this.employeeUpdate(_c);
        }

}


static public Description createDescription(DirPersonName _dirPersonName)
{
    #Define.Space(" ")
    return _dirPersonName.FirstName
        + (_dirPersonName.MiddleName ? #Space + _dirPersonName.MiddleName : "")
        + (_dirPersonName.LastName   ? #Space + _dirPersonName.LastName   : "");
}


public Static HcmPersonGender convGender(str _gender)
{
    HcmPersonGender ret;
    #Define.Female("Kvinde")
    #Define.Male("Mand")
    ;
    switch (_gender)
    {
        case #Female:
            ret = HcmPersonGender::Female;
            break;

        case #Male:
            ret = HcmPersonGender::Male;
            break;

        default:
            ret = HcmPersonGender::None;
    }

    return ret;
}


public Static str defaultCountryRegionId()
{
    str ret;
    LogisticsPostalAddress  logisticsPostalAddress_Default;
    ;

    logisticsPostalAddress_Default.initValue();

    ret = logisticsPostalAddress_Default.CountryRegionId;

    return ret;
}





public static date convDate(str _date)
{
    Date ret;
    ;

    ret = str2Date(_date, 123);

    return ret;
}


This method is used to create the employee.
Create
private void employeeCreate(container _c)
{
    boolean                                 ret = true;
    CompanyInfo                             companyInfo;
    HcmEmploymentRecId                      newEmploymentRecId;
    ValidFromDateTime                       employmentStartDateTime;
    ValidToDateTime                         employmentEndDateTime;
    HcmWorker                               newHcmWorker;
    DirPerson                               dirPerson;
    DirPersonName                           dirPersonName;
    HcmEmploymentType                       hcmEmploymentType = HcmEmploymentType::Employee;
    NumberSeq                               numberSeqPersonnelNum;
    HcmPersonPrivateDetails                 HcmPersonPrivateDetails;
    AxLogisticsPostalAddress                axLogisticsPostalAddress = new AxLogisticsPostalAddress();
    AxLogisticsLocation                     axLogisticsLocation;
    ;

    companyInfo = companyInfo::find();

    employmentStartDateTime = datetobeginUtcDateTime(HrmImportEmployeeMasterdata::convDate(conpeek(_c, #DateOfHiring)), DateTimeUtil::getUserPreferredTimeZone());
    employmentEndDateTime   = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::maxValue(), DateTimeUtil::getUserPreferredTimeZone());

    dirPersonName.FirstName     = conpeek(_c, #FirstName);
    dirPersonName.MiddleName    = conpeek(_c, #MiddleName);
    dirPersonName.LastName      = conpeek(_c, #LastName);
    newHcmWorker = HcmWorker::find(HcmWorkerTransition::newCreateHcmWorker(dirPersonName
                                                                           , conpeek(_c, #EmployeeNumber)
                                                                           , companyInfo.RecId
                                                                           , hcmEmploymentType
                                                                           , employmentStartDateTime
                                                                           , employmentEndDateTime));

    if (newHcmWorker.RecId == 0)
    {
        ret = false;
    }

    if (newHcmWorker.RecId == 0)
    {
        // Updating an existing worker

        // If there is no active employment for the worker
        newEmploymentRecId = HcmWorkerTransition::newCreateHcmEmployment(newHcmWorker.RecId, companyInfo.RecId,
                hcmEmploymentType, employmentStartDateTime, employmentEndDateTime);


        if (newEmploymentRecId == 0)
        {
            ret = false;
        }
    }

    if (ret)
    {
        if(numberSeqPersonnelNum)
        {
            // mark number sequence based ID consumed
            numberSeqPersonnelNum.used();
        }
    }
    else
    {
        if(numberSeqPersonnelNum)
        {
            numberSeqPersonnelNum.abort();
        }

        dirPerson.clear();
        dirPersonName.Person = 0;
    }

    hcmPersonPrivateDetails.initValue();
    hcmPersonPrivateDetails.Person      = dirPersonName.Person;
    hcmPersonPrivateDetails.BirthDate   = HrmImportEmployeeMasterdata::convDate(conpeek(_c, #BirthDate));
    hcmPersonPrivateDetails.Gender      = HrmImportEmployeeMasterdata::convGender(conpeek(_c, #Gender));
    hcmPersonPrivateDetails.insert();

    dirPerson                   = dirPerson::find(dirPersonName.Person, true);
    dirPerson.Initials          = conpeek(_c, #Initials);
    dirPerson.ProfessionalTitle = conpeek(_c, #Position);
    dirPerson.update();

    //Create address
    axLogisticsLocation = new AxLogisticsLocation();
    axLogisticsLocation.validateInput(true);
    axLogisticsLocation.parmIsPostalAddress(NoYes::Yes);
    axLogisticsLocation.parmDescription(HrmImportEmployeeMasterdata::createDescription(dirPersonName));
    axLogisticsLocation.save();

    axLogisticsPostalAddress    = new AxLogisticsPostalAddress();
    axLogisticsPostalAddress.parmLocation(axLogisticsLocation.parmRecId());
    axLogisticsPostalAddress.validateInput(true);
    axLogisticsPostalAddress.parmCountryRegionId(HrmImportEmployeeMasterdata::defaultCountryRegionId());
    axLogisticsPostalAddress.parmZipCode(conpeek(_c, #PostalCode));
    axLogisticsPostalAddress.parmZipCodeRecId(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).RecId);
    axLogisticsPostalAddress.parmStreet(conpeek(_c, #Address));
    axLogisticsPostalAddress.parmCity(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).City);
    axLogisticsPostalAddress.parmCityRecId(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).CityRecId);
    axLogisticsPostalAddress.save();

    DirParty::addLocation(dirPersonName.Person, axLogisticsLocation.parmRecId(), true, true, true);
}


This method is used to update the employee

Update
private void employeeUpdate(container _c)
{
    boolean                                 ret = true;
    CompanyInfo                             companyInfo;
    ValidFromDateTime                       employmentStartDateTime;
    ValidToDateTime                         employmentEndDateTime;
    HcmWorker                               hcmWorker;
    DirPerson                               dirPerson;
    DirPersonName                           dirPersonName;
    HcmEmploymentType                       hcmEmploymentType = HcmEmploymentType::Employee;
    HcmPersonPrivateDetails                 HcmPersonPrivateDetails;
    AxLogisticsPostalAddress                axLogisticsPostalAddress = new AxLogisticsPostalAddress();
    AxLogisticsLocation                     axLogisticsLocation;
    Description                             description_Old;
    HcmEmployment                           hcmEmployment;
    LogisticsLocation                       logisticsLocation;
    LogisticsPostalAddress                  logisticsPostalAddress;
    DirPartyLocation                        dirPartyLocation;
    ;

    companyInfo = companyInfo::find();
    hcmWorker   = hcmWorker::findByPersonnelNumber(conpeek(_c, #EmployeeNumber));

    //Update dirPersonName
    dirPersonName   = dirPersonName::find(hcmWorker.Person, true);
    description_Old = HrmImportEmployeeMasterdata::createDescription(dirPersonName);
    if (   dirPersonName.FirstName  != conpeek(_c, #FirstName)
        || dirPersonName.MiddleName != conpeek(_c, #MiddleName)
        || dirPersonName.LastName   != conpeek(_c, #LastName))
    {
        dirPersonName.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
        dirPersonName.FirstName     = conpeek(_c, #FirstName);
        dirPersonName.MiddleName    = conpeek(_c, #MiddleName);
        dirPersonName.LastName      = conpeek(_c, #LastName);
        dirPersonName.update();
    }

    //Update hiring
    employmentStartDateTime = datetobeginUtcDateTime(HrmImportEmployeeMasterdata::convDate(conpeek(_c, #DateOfHiring)), DateTimeUtil::getUserPreferredTimeZone());
    employmentEndDateTime   = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::maxValue(), DateTimeUtil::getUserPreferredTimeZone());

    hcmWorker       = HcmWorker::findByPersonnelNumber(conpeek(_c, #EmployeeNumber));
    hcmEmployment   = hcmEmployment::getActiveEmploymentsByWorker(hcmWorker.RecId, employmentStartDateTime, employmentEndDateTime, true);
    if (hcmEmployment.RecId)
    {
        HcmWorkerTransition::newUpdateHcmEmployment(hcmEmployment, employmentStartDateTime, employmentEndDateTime);
    }
    else
    {
        hcmWorker = HcmWorker::find(HcmWorkerTransition::newCreateHcmWorker(dirPersonName
                                                                           , conpeek(_c, #EmployeeNumber)
                                                                           , companyInfo.RecId
                                                                           , hcmEmploymentType
                                                                           , employmentStartDateTime
                                                                           , employmentEndDateTime));
    }

    hcmPersonPrivateDetails = HcmPersonPrivateDetails::findByPerson(hcmWorker.Person, true);
    if (hcmPersonPrivateDetails)
    {
        if (   hcmPersonPrivateDetails.BirthDate    != HrmImportEmployeeMasterdata::convDate(conpeek(_c, #BirthDate))
            || hcmPersonPrivateDetails.Gender       != HrmImportEmployeeMasterdata::convGender(conpeek(_c, #Gender)))
        {
            hcmPersonPrivateDetails.BirthDate   = HrmImportEmployeeMasterdata::convDate(conpeek(_c, #BirthDate));
            hcmPersonPrivateDetails.Gender      = HrmImportEmployeeMasterdata::convGender(conpeek(_c, #Gender));
            hcmPersonPrivateDetails.update();
        }
    }
    else
    {
        hcmPersonPrivateDetails.initValue();
        hcmPersonPrivateDetails.Person      = dirPersonName.Person;
        hcmPersonPrivateDetails.BirthDate   = HrmImportEmployeeMasterdata::convDate(conpeek(_c, #BirthDate));
        hcmPersonPrivateDetails.Gender      = HrmImportEmployeeMasterdata::convGender(conpeek(_c, #Gender));
        hcmPersonPrivateDetails.insert();
    }

    dirPerson                   = dirPerson::find(dirPersonName.Person, true);
    if (   dirPerson.Initials               != conpeek(_c, #Initials)
        || dirPerson.ProfessionalTitle      != conpeek(_c, #Position))
    {
        dirPerson.Initials          = conpeek(_c, #Initials);
        dirPerson.ProfessionalTitle = conpeek(_c, #Position);
        dirPerson.update();
    }

    //Update or Create address
    select firstOnly forUpdate logisticsLocation
        where logisticsLocation.Description == description_Old
        join dirPartyLocation
            where dirPartyLocation.Location == logisticsLocation.RecId
               && dirPartyLocation.Party    == dirPerson.RecId;

    if (logisticsLocation)
    {
        axLogisticsLocation = AxInternalBase::construct(logisticsLocation);
    }
    else
    {
        axLogisticsLocation = new AxLogisticsLocation();
    }

    axLogisticsLocation.validateInput(true);
    axLogisticsLocation.parmIsPostalAddress(NoYes::Yes);
    axLogisticsLocation.parmDescription(HrmImportEmployeeMasterdata::createDescription(dirPersonName));
    axLogisticsLocation.save();


    //Update or Create postaladdress
    select firstOnly forUpdate logisticsPostalAddress
        where logisticsPostalAddress.Location == axLogisticsLocation.parmRecId();

    if (logisticsPostalAddress)
    {
        axLogisticsPostalAddress = AxInternalBase::construct(logisticsPostalAddress);
    }
    else
    {
        axLogisticsPostalAddress = new AxLogisticsPostalAddress();
    }

    axLogisticsPostalAddress.parmLocation(axLogisticsLocation.parmRecId());
    axLogisticsPostalAddress.validateInput(true);
    axLogisticsPostalAddress.parmCountryRegionId(HrmImportEmployeeMasterdata::defaultCountryRegionId());
    axLogisticsPostalAddress.parmZipCode(conpeek(_c, #PostalCode));
    axLogisticsPostalAddress.parmZipCodeRecId(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).RecId);
    axLogisticsPostalAddress.parmStreet(conpeek(_c, #Address));
    axLogisticsPostalAddress.parmCity(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).City);
    axLogisticsPostalAddress.parmCityRecId(LogisticsAddressZipCode::find(conpeek(_c, #PostalCode)).CityRecId);
    axLogisticsPostalAddress.save();

    DirParty::addLocation(dirPersonName.Person, axLogisticsLocation.parmRecId(), true, true, true);
}

Wednesday, March 28, 2012

Microsoft plan: You need a new ERP system every year

Microsoft will now publish brand-new versions of Dynamics every year.
See following Microsoft's reason to accelerate the development work so spectacularly.
http://www.computerworld.dk/art/215140/microsoft-plan-du-skal-have-nyt-erp-system-hvert-aar

Tuesday, March 27, 2012

Monday, March 26, 2012

Microsoft Dynamics AX 2012 Development cource part IV


Development IV in Microsoft Dynamics AX 2012


Download the course from the following link if you are have partnersource  id.

Course Number 80313

What we are learning from this course
Last Modified 20-03-2012
Posted 20-03-2012

This training dives deeper into the programming architecture of Microsoft Dynamics AX 2012. It provides individuals with a case study/hands-on approach to customizing the system. This training contains coding.


AudienceThe intended audience is experienced systems consultants typically working for a Microsoft Dynamics partner that is selling, consulting, implementing, and supporting Microsoft Dynamics AX 2012.
At Training Material CompletionAfter completing this training, individuals will be able to:
  • Describe the features of number sequences in Microsoft Dynamics AX 2012.
  • Describe the steps for setting up and administering a number sequence.
  • Develop new number sequences by extending the NumberSeqApplicationModule class.
  • Use the Form Handler to create number sequences in a form.
  • Describe the concept of events and how they can be used in Microsoft Dynamics AX.
  • Describe the various methods for integrating with Microsoft Dynamics AX.
  • Describe the various types of services available in Microsoft Dynamics AX.
  • Use a proxy class for .NET interop to X++.
  • Access managed assemblies from X++.
  • Explain how .NET Framework assemblies are deployed.
  • Describe how to set up and use the Global Address Book.
  • Review the data model and classes for the Global Address Book framework.
  • Create a new entity for the Global Address Book.
  • Modify the Extensible Data Security policy for the new Global Address Book entity.
  • Retrieve an address from the Global Address Book on a transaction.
  • Describe how extensible data security policies can be used to help secure your data.
  • Create and use extensible data security policies.
  • Describe how financial dimensions are used.
  • Describe the various types of organizations available in Microsoft Dynamics AX 2012.
  • Describe how the organization model is used throughout the system.
  • Create a custom operating unit, and organization type.
  • Describe how cases are used in Microsoft Dynamics AX 2012.
  • Create a new case association type.
  • Add case management to a form.
  • Explain how policy rules are used.
  • Review the data model for the policies framework.
  • Create a new policy type and policy rule.
  • Describe currencies, exchange rates, fiscal calendars, and periods.
  • Describe the components that comprise the chart of accounts.
  • Review the steps for adding financial dimension controls to a form.
  • Create a new system-defined dimension.
  • Describe how journals and transactions are used to update the general ledger.
  • Describe how the Budgeting module is used.
    Review the data model and key classes used for budgeting and budget checking.
  • Describe how the Fixedassets module is used.
  • Review the data model for fixed assets.
  • Describe how products are set up, released, and finalized.
  • Describe how inventory dimensions and groups are used to manage product information.
  • Review the data model for inventory dimensions.
  • Describe how reservations and marking are used in the system.
  • Review the inventory transactions and on hand inquiries.
  • Describe the data model for inventory transactions and on hand inventory.
  • Review the structure of the InventOnHand Class.
  • Explain how inventory journals are used.
  • Discuss the inventory journals data model and the structure of the InventJournalCheckPost classes.
  • Describe how quarantine management and quality management are used in the system.
  • Explain inventory blocking.
  • Describe other functionality that is available in the Inventory and warehouse management module.
  • Describe the activities and transactions that can be created for customers.
  • Review the customer data model.
  • Describe the activities and transactions that can be created for customers.
  • Describe how free text invoices are used.
  • Review the data model and framework that is used for processing free text invoices.
  • Review the various ways that vendor invoices can be generated.
  • Describe the set up that is required for payments and review the data model for payment set up.
  • Describe how customer and vendor payments are made.
  • Review the customer payment data model and discuss the framework that is used for making and generating payments.
  • Describe how collections and interest notes are used.
  • Review the data model and framework for interest notes.
  • Describe the functionality that is available for bill of exchanges.
  • Describe the functionality that is available for promissory notes.
  • Review the general features that are supported with sales and purchase orders.
  • Describe how sales and purchase orders integrate with other modules,
  • Discuss the primary tables used in the purchase order flow.
  • Describe how the PurchType, PurchLineType, and PurchTotals classes work.
  • Describe how trade agreements are used and set up.
  • Review the data model for trade agreements.
  • Discuss how the trade agreement classes are used and can be extended.
  • Describe how sales and purchase agreements are used and set up.
  • Review the data model for sales and purchase agreements.
  • Discuss how the sales and purchase agreement classes are used and can be extended.
  • Describe how pricing policies are used.
  • Describe how charges are used and set up.
  • Review the data model for charges.
  • Describe how the FormLetter framework is used.
  • List the various documents that are processed through the FormLetter framework.
  • Describe the data model for updating documents.
  • Describe how the FormLetter classes relate to each other and generally work.
  • Describe how to make modifications to the FormLetter framework.
  • Describe the differences between the sales order and the sales quotation features, data model, and classes.
  • Describe the differences between the purchase order and the request for quotation features, data model, and classes.
  • Describe the differences between the purchase order and the purchase requisitions features, data model, and classes.
  • Explain how to use and set up categories and category hierarchies.
  • Review the data model for categories and category hierarchies.
  • Describe how projects are created, and the various types of projects that are available.
  • Review the data model for projects.
  • Discuss the significant classes that are used with projects.
  • Describe how the work breakdown structure is used with projects and how the data model relates to the project data model.
  • Discuss the transaction types that are used for journals in the Project management and accounting module and how categories, pricing, and line properties control the posting of these transactions.
  • Review the data model and the ProjTrans class hierarchy that is used for posting transactions against a project.
  • Describe how budgeting and forecasting works with projects.
  • Review the data model for budgets and forecasts.
  • Describe how project contracts are used.
  • Review the data model for project contracts.
  • Describe how project invoice proposals and invoices are generated in Microsoft Dynamics AX.
  • Review the data model and classes used for generating invoice proposals and invoices.
  • Review how estimate projects and cost templates are used in the system.
  • Describe the Project Management and Accounting Add-In.
  • Review the basics of bill of materials and the data model
    Introduce routes and operations.
  • Describe the major features of production orders.
  • Review scheduling methods, resources and jobs.
  • Describe master planning and the planned production order journal model.
  • Introduce lean manufacturing, Kanban, and production flow models.
  • Review Process Industries in Microsoft Dynamics AX 2012.
  • Implement a new line-item workflow.
  • Review the workflow providers in Microsoft Dynamics AX 2012.
  • Create a custom workflow provider.
  • Enable queues for a workflow document.
  • Discuss how currency type fields function within the Condition Editor.
  • Review the steps required to implement a new hierarchy type field to be used in the Condition Editor.
  • Explain the report capabilities in Microsoft Dynamics AX 2012.
  • Describe the key concepts involved when specifying data for your reports.
  • Create a new query and then bind the query to a new SQL Server Reporting Services report together with an auto design.
  • Add sorting, grouping, filters, and parameters to a report.
  • Save, deploy, and view a report in Microsoft Dynamics AX.
  • Discuss the Model-View-Controller (MVC) pattern.
  • Define the report dataset.
  • Create a temporary table to store the report dataset.
  • Manage report parameters in a data contract class in X++.
  • Create a report data provider (RDP) class.
  • Work with report precision design.
  • Explain how to print a report, set the print settings, prevent the display of print setup, set the query range, and set a report parameter value in X++.
  • Review how reports bound to a report data method can contain business logic to access data.
  • Describe the components of print management and the steps that are used to implement each component of print management.
PrerequisitesBefore reviewing this training, individuals must have:
  • knowledge of Microsoft Dynamics AX 2012
  • attended course 80303: Development I in Microsoft Dynamics AX 2012
  • attended course 80304: Development II in Microsoft Dynamics AX 2012
  • attended course 80312: Development III in Microsoft Dynamics AX 2012



Friday, March 23, 2012

AX2012 SSRS Error- An item with the same key has already been added

When we tried to execute the report we are getting this issue.

 An item with the same key has already been added


I tried to remove the cache of AOS,SSRS cache but no luck.So I redeployed the report  then the issue is fixed.
so when you got the above issue please remove the cache and redeploy the report.


AX2012 SSRS Reports Error and Strange Errors


Error when running SSRS-reports just after deleting a table field from report's temporary table in AX2012


When designing reports I sometimes faced a strange problem. After testing a new SSRS-report successfully I am always checking the SSRS-report’s temporary tables for table fields which were created by me during    

Friday, March 9, 2012

Ax2012 Get Table Field Names , Labels using MetaDataService


Before writing this code please take the reference of the service
net.tcp://localhost:8101/DynamicsAx/Services/MetadataService

I have create the windows project with two textboxes,txtTableName,txtFieldsList in the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Krishh_GetTableFieldLabels.MetadataServiceReference;

namespace Krishh_GetTableFieldLabels
{
    public partial class GetTableFieldswithLabels : Form
    {
        public GetTableFieldswithLabels()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            AxMetadataServiceClient client = new AxMetadataServiceClient();
            try
            {
                string[] tablenames = new string[1];
                tablenames[0] = txtTableName.Text;

                // Gets the table metadata.
                TableMetadata[] tableMetadata = client.GetTableMetadataByName(tablenames);
                TableMetadata tableMetadata1 = tableMetadata[0];

                foreach (DataFieldMetadata fieldMetadata in tableMetadata1.Fields)
                {
                    txtFieldsList.Text += fieldMetadata.Name + "," + client.GetLabelMetadataForLanguageById("EN-US", new string[] { fieldMetadata.LabelId })[0].LabelString + Environment.NewLine;
                }
             
                client.Close();
            }
            catch
            {
                client.Abort();
                throw;
            }
        }
    }
}



Monday, March 5, 2012

AX2012 Import Vendors from CSV using VENDVendTableService


The following sample is used to import the Data into Vendors from CSV using VENDVENDTABLEService.

Please change the container positions accordingly to your file.
static void Krishh_ImportVendorMaster(Args _args)
{
    VendVendTableService                        vendVendTableService;
    VendVendTable                               vendVendTable;
    VendVendTable_VendTable                     vendTable;
    VendVendTable_DirPartyPostalAddressView     adresss;
    VendVendTable_DirPartyTable_DirOrganiza1    dirPartyTable;
    VendVendTable_DirPartyContactInfoView       contactInfo;
    VendVendTable_OrganizationName              organizationName;
    TaxVATNumTable                              TaxVATNumTable;
    str                                         countryRegionId;
    CommaTextIo                 file;
    container                   rec;

    Dialog              d;
    DialogField         df1, df2;
    ;
    d = new Dialog("Import vendors");
    df1 = d.addField(ExtendedTypeStr("FilenameOpen"));

    if (d.run())
    {
        file = new CommaTextIo(df1.value(), 'r');
        file.inFieldDelimiter(';');

        vendVendTableService = vendVendTableService::construct();

        ttsBegin;

        while (file.status() == IO_Status::Ok)
        {
            rec = file.read();

            vendVendTable = new VendVendTable();
            vendTable = vendVendTable.createVendTable().addNew();

            vendTable.parmAccountNum(conPeek(rec, 1));
            vendTable.parmCurrency(conPeek(rec, 2));
            vendTable.parmName(conPeek(rec, 3));
            vendTable.parmVendGroup(conPeek(rec, 4));
            vendTable.parmVATNum(conPeek(rec, 11));

            countryRegionId = conPeek(rec, 6);

            if (!TaxVATNumTable::exist(vendTable.parmVATNum(), countryRegionId))
            {
                TaxVATNumTable.VATNum = vendTable.parmVATNum();
                TaxVATNumTable.CountryRegionId = countryRegionId;
                TaxVATNumTable.insert();
            }

            dirPartyTable = new VendVendTable_DirPartyTable_DirOrganiza1();
            //dirPartyTable = new VendVendTable_DirPartyTable_CompanyInfo();
            vendTable.createDirPartyTable().add(dirPartyTable);
            dirPartyTable.parmLanguageId(conPeek(rec, 10));
            //companyInfo.parmTCC


            organizationName = dirPartyTable.createOrganizationName().addNew();
            organizationName.parmName(conPeek(rec, 3));

            adresss = dirPartyTable.createDirPartyPostalAddressView().addNew();
            adresss.parmCity(conPeek(rec, 5));
            adresss.parmCountryRegionId(conPeek(rec, 6));
            adresss.parmStreet(conPeek(rec, 7));
            adresss.parmZipCode(conPeek(rec, 8));
            adresss.parmRoles('Business');

            contactInfo = dirPartyTable.createDirPartyContactInfoView().addNew();
            contactInfo.parmIsPrimary(NoYes::Yes);
            contactInfo.parmType(LogisticsElectronicAddressMethodType::Phone);
            contactInfo.parmRoles('Business');
            contactInfo.parmLocator(conPeek(rec, 9));

            vendVendTableService.create(vendVendTable);
        }

        ttsCommit;
    }

}

AX2012 Import Vendors from CSV


The following sample code is used to import Vendors from CSV.

static void Krishh_importVendorfromCSV(Args _args)
{
    CommaIO                     csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName;
    DirPartyRecId               partyRecId,contactPartyRecid;
    Name                        name,contactName;
    VendTable                   vendtable;
    FileName                    fileName;
    str                         contactperson;
    DirPartyPostalAddressView   addressView;
    DirPartyContactInfoView     contactView;
    ContactPerson               contactpersonTable;
    LogisticsElectronicAddressMethodType enumType;


    DirParty                    dirParty;
    LogisticsPostalAddress      address;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    BinData binData;
    str stringImage;
    inserted =0;
    #File


    dialog = new Dialog("Pick the file");
    dfFileName = dialog.addField(extendedTypeStr(FileNameOpen));
    dialog.filenameLookupFilter(["All files", #AllFiles]);


    if (dialog.run())
    {
            filename =  dfFileName.value();
    }

    csvFile = new CommaIO(filename, 'r');


    if (csvFile)
    {
        readCon = csvFile.read();
        ttsbegin;
        while (csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            icount++;
            if (readCon)
            {
                name = conPeek(readCon,2);
                partyRecId = DirPartyTable::createNew( DirPartyType::Organization, name).RecId;


                vendtable.clear();
                vendtable.initValue();
                vendtable.Party = partyRecId;
                vendtable.AccountNum = conPeek(readCon,1);
                vendtable.VendGroup  = conPeek(readCon,5);
                vendtable.Currency   = conPeek(readCon,6);
                //vendtable.Blocked    =
                vendtable.DlvMode    = conPeek(readCon,8);
                vendtable.PaymMode   = conPeek(readCon,9);
                ContactPerson = conPeek(readCon,12);
                if(contactperson != '')
                {
                    contactname = conPeek(readCon,12);
                    ContactPerson::findOrCreateNameParty(partyRecId,contactname);
                }

                vendtable.insert();


                address.CountryRegionId = strLRTrim(conPeek(readCon,14));
                //addressView.State = strLRTrim(conPeek(readCon,16));
                address.ZipCode = strLRTrim(conPeek(readCon,15));
                address.Street  = strLRTrim(conPeek(readCon,19));
               // address.county = strLRTrim(conPeek(readCon,17));
               address.City    = strLRTrim(conPeek(readCon,18));
                addressView.LocationName = name;
                addressView.IsPrimary = NoYes::Yes;
                addressView.Party = partyRecId;
                addressview.initFromPostalAddress(address);


                DirParty = DirParty::constructFromPartyRecId(addressView.Party );
                DirParty.createOrUpdatePostalAddress(addressView);


                contactView.LocationName = "Delivery email";
                contactView.Locator      = strLRTrim(conPeek(readCon,10));
                contactView.Type         = LogisticsElectronicAddressMethodType::Email;
                contactView.Party        = partyRecId;
                contactView.IsPrimary    = NoYes::Yes;
                dirParty.createOrUpdateContactInfo(contactView);


                contactView.LocationName = "Delivery Cellular Phone";
                contactView.Locator      = strLRTrim(conPeek(readCon,11));
                contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                contactView.Party        = partyRecId;
                contactView.IsPrimary    = NoYes::Yes;
                dirParty.createOrUpdateContactInfo(contactView);


                contactView.LocationName = "Delivery Phone";
                contactView.Locator      = strLRTrim(conPeek(readCon,3));
                contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                contactView.Party        = partyRecId;
                contactView.IsPrimary    = NoYes::Yes;
                dirParty.createOrUpdateContactInfo(contactView);


                contactView.LocationName = "Delivery Fax";
                contactView.Locator      = strLRTrim(conPeek(readCon,4));
                contactView.Type         = LogisticsElectronicAddressMethodType::Fax;
                contactView.Party        = partyRecId;
                contactView.IsPrimary    = NoYes::Yes;
                dirParty.createOrUpdateContactInfo(contactView);
                inserted++;
            }
        }
        ttsCommit;
    }
    info(strfmt("%1 records inserted out of %2",inserted,icount));
}

AX2012 Import Ledger Journal Trans from CSV


Smaple code to import Ledger Journal Trans from CSV file.

Before doing this code, I have created parm Method of LedgerJournaTable which have LedgerJournalTable record with journal Num.

Please change the Container positions according to your file in createJournalTrans method.



class NavisionPayrollImportDialog extends RunBaseBatch
{
    DialogRunbase                               dialog;
    DialogField                                 dialogFilename;
    DialogField                                 dialogPostingdate;

    Filename                                    filename;
    TransDate                                   postingdate;
    LedgerJournalId                             journalId;
    LedgerJournalTable                          ledgerJournalTable;

    LedgerJournalEngine                         journalEngine;

    #define.CurrentVersion(2)
    #localmacro.CurrentList
        filename,
        postingdate
    #endmacro
}

//Parm method that stores Ledger Journal Table

public LedgerJournalTable  parmParmLedgerJournalTable(LedgerJournalTable  _parmLedgerJournalTable = ledgerJournalTable)
{
    ledgerJournalTable    = _parmLedgerJournalTable;
    return ledgerJournalTable;
}

// Main Method

public static void main(Args args)
{
    NavisionPayrollImportDialog  navisionPayrollImportDialog;
    ledgerJournalTrans             localJournalTrans;
    ;
    navisionPayrollImportDialog =NavisionPayrollImportDialog::construct();

    if(args.dataset() ==tableNum(LedgerJournalTrans))
    {
       localJournalTrans=args.record();
       navisionPayrollImportDialog.parmParmLedgerJournalTable(localJournalTrans.ledgerJournalTable());
    }

    if (navisionPayrollImportDialog.prompt())
    {
        navisionPayrollImportDialog.run();
    }
}



// Run Method where it initiates Import functionality
public void run()
{
    if(this.validate())
    {
        journalEngine = new LedgerJournalEngine();
        journalEngine.ledgerJournalTable(ledgerJournalTable);
        this.importPayrollFromNavision();
    }
}


private void importPayrollFromNavision()
{
    AsciiIo                    csvFile;
    container                  readCon;
    AxLedgerJournalTrans        journalTrans;
    LedgerJournalACType         accountType;
    #File
    ;
    try
    {
        new FileIOPermission(filename, #io_read).assert();
        csvFile = new AsciiIo(filename,#io_read);
        CodeAccessPermission::revertAssert();
        csvFile.inFieldDelimiter(',');
        csvFile.inRecordDelimiter(#delimiterCRLF);
        if (csvFile)
        {
            while (csvFile.status() == IO_Status::OK)
            {
                readCon = csvFile.read();
                if (readCon)
                {
                    this.createJournalTrans(readCon);
                }
            }//while close

        }// if csv file close

    }
    catch (Exception::Deadlock)
    {
        retry;
    }
    catch(Exception::Error)
    {
       throw error(strFmt("File Read Error,fileName:%1",filename));
    }
    csvFile.finalize();

}// method close

// create the journal Trans.

private void createJournalTrans(container   _c)
{
    LedgerJournalTrans      ledgerJournalTrans;

    LedgerAccountContract   ledgerAccountContract;
    DimensionStorage        dimensionStorage;
    AxLedgerJournalTrans    axJournalTrans;
    DimensionAttributeValueContract attributeValueContract;

    str                     acType;
    MainAccountNum          mainAccount;
    Amount                  amount;
    str                     department;

    mainaccount                     = strLRTrim(conPeek(_c,5));
    if(mainAccount::findByMainAccountId(mainaccount).RecId>0)
    {
        journalEngine.initValue(ledgerJournalTrans);
        ledgerJournalTrans.Company        = curext();
        if(strLRTrim(conPeek(_c,12))=="")
        {
            ledgerJournalTrans.CurrencyCode   = CompanyInfo::standardCurrency();
        }
        else
        {
            ledgerJournalTrans.CurrencyCode =strLRTrim(conPeek(_c,11));
        }
        ledgerJournalTrans.initForCurrency(ledgerJournalTable);

        ledgerAccountContract = new LedgerAccountContract();
        ledgerAccountContract.parmValues(new List(Types::Class));

        axJournalTrans = new AxLedgerJournalTrans();
        axJournalTrans.ledgerJournalTrans(ledgerJournalTrans);
        axJournalTrans.parmJournalNum(ledgerJournalTable.JournalNum);
        axJournalTrans.parmTransDate(postingdate);
        axJournalTrans.parmDocumentDate(str2Date(conPeek(_c,7),321));
        axJournalTrans.parmAccountType(LedgerJournalACType::Ledger);
        axJournalTrans.parmOffsetAccountType(LedgerJournalACType::Ledger);
        axJournalTrans.parmTxt(strLRTrim(conPeek(_c,10)));
        amount = str2num(conPeek(_c,13));

        if (amount > 0)
            axJournalTrans.parmAmountCurDebit(amount / 100);
        else
            axJournalTrans.parmAmountCurCredit(amount / 100);

        department = strLRTrim(conPeek(_c,14));

        ledgerAccountContract.parmMainAccount(mainAccount);
        if (department)
        {
            attributeValueContract = new DimensionAttributeValueContract();
            attributeValueContract.parmName("@SYS850");
           attributeValueContract.parmValue(department);

            ledgerAccountContract.parmValues().addEnd(attributeValueContract);
        }

        dimensionStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(ledgerAccountContract);

        axJournalTrans.parmLedgerDimension(dimensionStorage.save());

        axJournalTrans.currentRecord().insert();
    }
    else
    {
        info(strFmt("Main Account Id is Not available %1",mainaccount));
    }

}





AX2012 Import Chart of Accounts from CSV


// Assumes a file structure with:
// Account number;Account name;Account type (based on the enum DimensionLedgerAccountType)
static void Krishh_ImportChartOfAccounts(Args _args)
{
    ChartOfAccountsService      chartOfAccountsService;
    MainAccountContract         mainAccountContract;
    CommaTextIo                 file;
    container                   rec;
    Name                        ledgerChartOfAccountsName;
    MainAccountNum              mainAccountId;
    DimensionLedgerAccountType  dimensionledgerAccountType;

    MainAccount                                 MainAccount;
    DimensionAttribute                          mainAccountDimAttribute;
    DimensionAttributeValue                     dimensionAttributeValue;
    DimensionAttributeValueTotallingCriteria    totalCriteria;

    str                 strOfAccounts, fromA, toA;
    int                 sep;
    Dialog              d;
    DialogField         df1, df2;
    ;
    d = new Dialog("Import chart of accounts (main accounts)");
    df1 = d.addField(ExtendedTypeStr("FilenameOpen"));
    df2 = d.addField(extendedTypeStr("Name"), "Chart of account name");

    if (d.run())
    {
        file = new CommaTextIo(df1.value(), 'r');
        file.inFieldDelimiter(';');
        ledgerChartOfAccountsName = df2.value();
        ttsBegin;
        while (file.status() == IO_Status::Ok)
        {
            rec = file.read();
             mainAccountId = strlrTrim(conPeek(rec, 1));
            dimensionledgerAccountType = conPeek(rec, 3);

            if (!mainAccount::findByMainAccountId( mainAccountId , false, LedgerChartOfAccounts::findByName(ledgerChartOfAccountsName).RecId))
            {
                mainAccountContract = new MainAccountContract();
                mainAccountContract.parmMainAccountId( mainAccountId );
                mainAccountContract.parmName(conPeek(rec, 2));
                mainAccountContract.parmLedgerChartOfAccounts(ledgerChartOfAccountsName);
                mainAccountContract.parmType(dimensionledgerAccountType);

                chartOfAccountsService = new ChartOfAccountsService();
                chartOfAccountsService.createMainAccount(mainAccountContract);

                if (dimensionledgerAccountType == DimensionledgerAccountType::Total)
                {
                    strOfAccounts = conPeek(rec, 4);

                    sep = strScan(strOfAccounts, '..', 1, strLen(strOfAccounts));

                    if (sep)
                    {
                        fromA = subStr(strOfAccounts, 1, sep - 1);
                        toA   = subStr(strOfAccounts, sep + 2, strLen(strOfAccounts));
                    }

                    select recid from MainAccount where mainAccount.MainAccountId ==  mainAccountId  ;

                    mainAccountDimAttribute.RecId = DimensionAttribute::getMainAccountDimensionAttribute();

                    dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndEntityInst(mainAccountDimAttribute.RecId, mainAccount.RecId, true, true);

                    totalCriteria.DimensionAttributeValue = dimensionAttributeValue.RecId;
                    totalCriteria.FromValue = fromA;
                    totalCriteria.ToValue   = toA;
                    totalCriteria.insert();
                }
            }
        }

        ttsCommit;
    }

}