4 Jun 2014

Create Employee from class


//CreateEmployee

private void createEmployee(System.Data.SqlClient.SqlDataReader   dr1)
{
    CompanyInfo                             companyInfo;
    HcmEmploymentRecId                      newEmploymentRecId;
    ValidFromDateTime                       employmentStartDateTime;
    ValidToDateTime                         employmentEndDateTime;
    HcmWorker                               newHcmWorker;
    DirPerson                               dirPerson;
    DirPersonName                           dirPersonName;
    HcmEmploymentType                       hcmEmploymentType = HcmEmploymentType::Employee;
    NumberSeq                               numberSeqPersonnelNum;
    HcmPersonPrivateDetails                 HcmPersonPrivateDetails;
    HcmEmployment                           hcmEmployment;

    HcmWorkerTitle  hcmWorkerTitle;

    DirParty                        dirparty;
    DirPartyContactInfoView         contactView;
    HcmPersonDetails                persondetails;
    HcmPersonIdentificationNumber   hcmPersonIdentificationNumber;

    utcdatetime                     _validFrom = DateTimeUtil::utcNow();

    Struct              struct;
    container           ledgerDimension;
    DimensionDefault    DimensionDefault;
    int                 k;


    TransDate       HireDate,DOB;
    HcmPersonID     Employeecode;
    str             FirstName,Title,MobilePhone,email,MaritalStatus,NationalityCode,NationalityName,PaymentMode,MiddleName,LastName;

    str             DepartmentCode,DepartmentName,SubDivisionCode,SubDivisionName,DivisionCode,DivisionName ,SectorCode, SectorName;
    str             DesignationCode,DesignationName,SponsorCode,SponsorDesc,MOLNo,PASSPORTNUMBER,Gender,BloodGroup,ReligionCategory,EmployeeCategory,Emiratization;


    ;

    Employeecode    = dr1.get_Item('Employeecode');     FirstName       = dr1.get_Item('FirstName'); MiddleName = dr1.get_Item('Middlename'); LastName = dr1.get_Item('Lastname');
    Title           = dr1.get_Item('Title');            MobilePhone     = dr1.get_Item('MobilePhone');
    email          = dr1.get_Item('email');            DOB             = dr1.get_Item('DOB');
    MaritalStatus   = dr1.get_Item('MaritalStatus');    NationalityCode = dr1.get_Item('NationalityCode');
    NationalityName = dr1.get_Item('NationalityName');  HireDate        = dr1.get_Item('HireDate');
    PaymentMode     = dr1.get_Item('PaymentMode');      DepartmentCode  = dr1.get_Item('DepartmentCode');
    DepartmentName  = dr1.get_Item('DepartmentName');   //SubDivisionCode = dr1.get_Item('SubDivisionCode');
  //  SubDivisionName = dr1.get_Item('SubDivisionName'); // DivisionCode    = dr1.get_Item('DivisionCode');
  //  DivisionName    = dr1.get_Item('DivisionName');    // SectorCode      = dr1.get_Item('SectorCode');
   // SectorName      = dr1.get_Item('SectorName');       DesignationCode = dr1.get_Item('DesignationCode');
    DesignationName  = dr1.get_Item('DesignationName'); //SponsorCode  = dr1.get_Item('SponsorCode');
    SponsorDesc     = dr1.get_Item('SponsorName');
    MOLNo           = dr1.get_Item('MOLNo');
    PASSPORTNUMBER  = dr1.get_Item('PASSPORTNUMBER');
    Gender          = dr1.get_Item('Gender');
    BloodGroup        = dr1.get_Item('BloodGroup');
    ReligionCategory  = dr1.get_Item('ReligionCategory');
    EmployeeCategory  = dr1.get_Item('EmployeeCategory');
    Emiratization   = dr1.get_Item('Emiratization');





    companyInfo = companyInfo::find();

    newHcmWorker = HcmWorker::findByPersonnelNumber(Employeecode);

    if(! newHcmWorker)
    {
        employmentStartDateTime = datetobeginUtcDateTime(HireDate, DateTimeUtil::getUserPreferredTimeZone());
        employmentEndDateTime   = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::maxValue(), DateTimeUtil::getUserPreferredTimeZone());

        dirPersonName.FirstName     = FirstName;
        dirPersonName.MiddleName    = Middlename;
        dirPersonName.LastName      = LastName;
        newHcmWorker = HcmWorker::find(HcmWorkerTransition::newCreateHcmWorker(dirPersonName
                                                                               , Employeecode
                                                                               , companyInfo.RecId
                                                                               , hcmEmploymentType
                                                                               , employmentStartDateTime
                                                                               , employmentEndDateTime));
    }
    else
    {

        dirPersonName               = DirPersonName::find(newHcmWorker.Person,true);
        dirPersonName.FirstName     = FirstName;
        dirPersonName.MiddleName    = Middlename;
        dirPersonName.LastName      = LastName;
        dirPersonName.update();
    }

    hcmPersonPrivateDetails                     = HcmPersonPrivateDetails::findByPerson(newHcmWorker.Person,true);
    hcmPersonPrivateDetails.initValue();
    hcmPersonPrivateDetails.Person              = dirPersonName.Person;
    hcmPersonPrivateDetails.BirthDate           = DOB;
    hcmPersonPrivateDetails.Gender              = SQLIntegration::convGender(Gender);
    hcmPersonPrivateDetails.CitizenshipCountryRegion = NationalityCode;
    hcmPersonPrivateDetails.BloodGroup          = SQLIntegration::convBlood(BloodGroup);
    hcmPersonPrivateDetails.ReligionCategory    = SQLIntegration::convReligion(ReligionCategory);
    hcmPersonPrivateDetails.EmployeeCategory    = SQLIntegration::convEmployeeCategory(EmployeeCategory);
    hcmPersonPrivateDetails.Emiratization       = SQLIntegration::convEmiratization(Emiratization);
    if(hcmPersonPrivateDetails)
        hcmPersonPrivateDetails.update();
    else
        hcmPersonPrivateDetails.insert();

    persondetails               = HcmPersonDetails::findByPerson(newHcmWorker.Person);
    persondetails.initValue();
    persondetails.Person        = dirPersonName.Person;
    persondetails.MaritalStatus = SQLIntegration::convMarital(MaritalStatus);
    persondetails.ValidFrom     = DateTimeUtil::utcNow();
    persondetails.ValidTo       = DateTimeUtil::maxValue();
    //if (persondetails)
    //{
        //persondetails.selectForUpdate(true);
        //persondetails.update();
    //}
    //else
    //{
       persondetails.insert();
    //}


    hcmWorkerTitle          = HcmWorkerTitle::findByWorker(newHcmWorker.RecId);
    hcmWorkerTitle.initValue();
    hcmWorkerTitle.Worker   = newHcmWorker.RecId;
    hcmWorkerTitle.Title    = HcmTitle::findByTitle(DesignationCode).RecId;
    hcmWorkerTitle.ValidFrom = DateTimeUtil::utcNow();
    hcmWorkerTitle.ValidTo  = DateTimeUtil::maxValue();
    //if(hcmWorkerTitle)
    //{
        //hcmWorkerTitle.selectForUpdate(true);
        //hcmWorkerTitle.update();
    //}
    //else
    //{
        hcmWorkerTitle.insert();
    //}

        hcmPersonIdentificationNumber = HcmPersonIdentificationNumber::findByPersonAndType(newHcmWorker.RecId,HcmIdentificationType::findByIdentificationType("SponsorCode").RecId);
        hcmPersonIdentificationNumber.Person = dirPersonName.Person;
        hcmPersonIdentificationNumber.IdentificationType =  HcmIdentificationType::findByIdentificationType("SponsorCode").RecId;
        hcmPersonIdentificationNumber.IdentificationNumber = SponsorCode;
        hcmPersonIdentificationNumber.Description = SponsorDesc;
    if(hcmPersonIdentificationNumber)
    {
        hcmPersonIdentificationNumber.selectForUpdate(true);
        hcmPersonIdentificationNumber.update();
    }
    else
    {
        hcmPersonIdentificationNumber.insert();
    }

          hcmPersonIdentificationNumber.clear();
        hcmPersonIdentificationNumber = HcmPersonIdentificationNumber::findByPersonAndType(newHcmWorker.RecId,HcmIdentificationType::findByIdentificationType("Passport").RecId);


        hcmPersonIdentificationNumber.Person = dirPersonName.Person;
        hcmPersonIdentificationNumber.IdentificationType =  HcmIdentificationType::findByIdentificationType("Passport").RecId;
        hcmPersonIdentificationNumber.IdentificationNumber = PASSPORTNUMBER;

     if(hcmPersonIdentificationNumber)
    {
        hcmPersonIdentificationNumber.selectForUpdate(true);
        hcmPersonIdentificationNumber.update();
    }
    else
    {
        hcmPersonIdentificationNumber.insert();
    }

        hcmPersonIdentificationNumber.clear();
         hcmPersonIdentificationNumber = HcmPersonIdentificationNumber::findByPersonAndType(newHcmWorker.RecId,HcmIdentificationType::findByIdentificationType("EmpPersonNo").RecId);


        hcmPersonIdentificationNumber.Person = dirPersonName.Person;
        hcmPersonIdentificationNumber.IdentificationType =  HcmIdentificationType::findByIdentificationType("EmpPersonNo").RecId;
        hcmPersonIdentificationNumber.IdentificationNumber = MOLNo;

    if(hcmPersonIdentificationNumber)
    {
        hcmPersonIdentificationNumber.selectForUpdate(true);
        hcmPersonIdentificationNumber.update();
    }
    else
    {
        hcmPersonIdentificationNumber.insert();
    }



    dirPerson                   = dirPerson::find(dirPersonName.Person, true);
    dirPerson.PersonalTitle     = DirNameAffix::find(DirNameAffixType::PersonalPrefix ,Title).RecId;
    dirPerson.update();

    //select firstonly ValidTimeState(_validFrom) hcmEmployment
                //where hcmEmployment.Worker == newHcmWorker.RecId
                //&&    hcmEmployment.LegalEntity == companyInfo.RecId;
//
    ////Department Code    Department Name    Sub Division Code    Sub Division Name    Division Code    Division Name    Sector Code
//
    //this.findorCreateDimension('Department',DepartmentCode,DepartmentName);
    //this.findorCreateDimension('SubDivision',SubDivisionCode,SubDivisionName);
    //this.findorCreateDimension('Division',DivisionCode,DivisionName);
    //this.findorCreateDimension('Sector',SectorCode,SectorName);
//
//
    //struct = new Struct();
    //struct.add('Department',DepartmentCode);
    //struct.add('Division', DivisionCode);
    //struct.add('SubDivision', SubDivisionCode);
    //struct.add('Sector', SectorCode);
//
    //ledgerDimension = conNull();
    //ledgerDimension += struct.fields();
//
    //for (k = 1; k <= struct.fields(); k++)
    //{
        //ledgerDimension += struct.fieldName(k);
        //ledgerDimension += struct.valueIndex(k);
    //}
//
    //DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
    //hcmEmployment.DefaultDimension = DimensionDefault;
    //hcmEmployment.update();



    DirParty = DirParty::constructFromPartyRecId(dirPerson.recid);

    if(email && (email != "NA"))
    {
        contactView.LocationName = "Email";
        contactView.Locator      = strLRTrim(email);
        contactView.Type         = LogisticsElectronicAddressMethodType::Email;
        contactView.Party        = dirPerson.recid;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);
    }
    if(MobilePhone && MobilePhone != "NA")
    {
        contactView.LocationName = "Phone";
        contactView.Locator      = strLRTrim(MobilePhone);
        contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
        contactView.Party        = dirPerson.recid;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);

    }
}

How to get User Roles for different available companies in AX 2012 X++


//How to get User Roles for different available companies


static void UserRolebyCompany(Args _args)
{

    TextIo              txIoRead,txIoWrite;
    FileIOPermission    fioPermission;
    container           containFromRead;
    int                         xx,iConLength;
    str                         sTempPath,sFileName = "UserRolebyCompany.txt", sOneRecord;
    SecurityUserRole     SecurityUserRole;
    SecurityUserRoleCondition   SecurityUserRoleCondition;
    SecurityRole         SecurityRole ;
    UserInfo             userInfo;
    Company              comp;
    container            cont;
    ;

    //To Get the temporary file path.
    sTempPath = WINAPI::getTempPath();
    info("File is at: " + sTempPath + sFileName);

    // Assert permission for file.
    fioPermission = new FileIOPermission
        (sTempPath + sFileName ,"RW");
    fioPermission.assert();

    // If the test file already exists, delete it.
    if (WINAPI::fileExists(sFileName))
    {
        WINAPI::deleteFile(sTempPath + sFileName);
    }
 
    // "W" mode overwrites existing content, or creates the file.
    txIoWrite = new TextIo( sTempPath + sFileName ,"W");
        while select SecurityUserRole
    {
        cont = conNull();
        select SecurityRole  where SecurityRole .RecId == SecurityUserRole.SecurityRole;
        select userInfo where userInfo.id == SecurityUserRole.User;
        while select SecurityUserRoleCondition where SecurityUserRoleCondition.SecurityUserRole

== SecurityUserRole.RecId
        {
              cont += SecurityUserRoleCondition.DataArea;
        }
        if(!cont)
        {
            txIoWrite.write(strFmt("%1 -- %2 -- %3 -- %4 -- %5 -- %6",userInfo.name,

userInfo.networkAlias,userInfo.company,SecurityUserRole.User, SecurityRole .Name,"ALL"));
        }
        else
        {
            txIoWrite.write(strFmt("%1 -- %2 -- %3 -- %4 -- %5 -- %6",userInfo.name,
userInfo.networkAlias,userInfo.company,SecurityUserRole.User, SecurityRole

.Name,con2StrUnlimited(cont, ',')));
        }
    }
}

send Automatic appointment to Mail id by using outlook through X++


// Steps to send Automatic appointment to Mail id by using outlook through X++

static void OutlookAppointment(Args _args)
 {
   COM    sysOutlookCollection;
   COM    receipiants;
   COM    collection;
   COMVariant comStartDate = new COMVariant();
   COMVariant comEndDate  = new
   COMVariant();
   COM    c;
   #SysOutLookCOMDEF
   #define.mapi("MAPI")
   #define.outlook("Outlook.Application")
   COM    sysOutlook;
   COM    sysOutlookNameSpace;
   COM    sysOutlookMAPIFolder;
   sysOutlook         = new COM(#outlook);
   sysOutlookNameSpace     = sysOutlook.getNamespace(#mapi);
   sysOutlookNameSpace.logon();  
   sysOutlookMAPIFolder    = sysOutlookNameSpace.getDefaultFolder(#OlDefaultFolders_olFolderTasks);
   collection         = sysOutlookMAPIFolder.items();
   c = collection.add();
   comStartDate.date(today());
   comStartDate.time(str2Time( "10:40:00"));
   comEndDate.date(today());
   comEndDate.time(str2Time( "10:45:00"));
   c.subject("Meeting regd Microsoft Dynamics AX 2012");
   c.body("Lets discuss on whats new in DAX 2012");
   c.save();
   if (c)
   {
     receipiants = c.Recipients();
     receipiants.add(" Desired mail Id");
     receipiants.ResolveAll();
     c.assign();
     //c.display();
     c.send();
     info("The action is created in Microsoft Outlook");
   }
   else
   throw error("@SYS31969");
   sysOutlookNameSpace.logoff();
 } 

To get a User Id in AX client workspace Display..


//To get a User Id in AX client workspace Display..

class->info->method->workspaceWindowcreated
info Class: http://msdn.microsoft.com/en-us/library/xinfo.aspx


static void printCurrentUserId()


{
        //info(curUserId());
        //info(curext());

    SecurityRole        role;
     SecurityUserRole    userRole;
     UserInfo            userInfo,userInfoName;

     ;


    select firstonly  role
    exists join userRole
    where role.RecId     == userRole.SecurityRole
          && userRole.User == curUserId();
    select userInfoName where userInfoName.id == curUserId();

    info(strFmt("System Role :%1 \n UserID :  %2 \n userName: %3 \n UserCompany: %4", role.Name,curUserId(),userInfoName.name,curext()));

}

void workspaceWindowCreated(int _hWnd)
{

     UserInfo userInfoName;
        ;
    super(_hWnd);

    // Put workspace window specific initialization here.

    select userInfoName where userInfoName.id == curUserId();
     WinAPI::setWindowText(_hWnd,strFmt("%1-%2", userInfoName.name, WinAPI::getWindowText(_hWnd)));
}


// To get a Current User id and current working company in X++

info(curuserid());
info(curext());


// In order find out the employee linked to the current user..

In AX 2009:
EmplTable::find(SysCompanyUserInfo::find(curUserId()).EmplId);

In AX 2012:
HcmWorker::find(DirPersonuser::findUserWorkerReference(curUserId())).name();

Display data in Title bar of Form and Code to get all object of project node



// Display data in Title bar of Form

http://daynamicsaxaptatutorials.blogspot.in/search/label/title%20bar%20info

//Code to get all object of project node

http://daynamicsaxaptatutorials.blogspot.in/2011/06/code-to-get-all-object-of-project-node.html

Steps to create and Post a BOM journal through X++

/ Steps to create and Post a BOM journal through X++

void clicked()
{

        InventJournalTable          journalTable ;
        InventJournalTrans          journalTrans;
        InventJournalTableData      journalTableData;
        InventJournalTransData      journalTransData;
        InventJournalNameId         inventJournalName;
        InventTransId               num;
        InventJournalVoucherId      numV;
        ComboBOMHeader              Header;
        Filename                    filename;
        NumberSeq                   numberSeq,numberSeq1;
        ComboBOMLine                line;
        InventDim                   inventDim;
        Dialog                      dialog;
        DialogField                 dlgfeild;
        str a;
        InventJournalCheckPost      journalCheckPost;// = new InventJournalCheckPost();
         int   L = 10;

        ;
        
        journalTableData = JournalTableData::newTable(journalTable);
        journalTransData = journalTableData.journalStatic().newJournalTransData(journalTrans,journalTableData);
//
        journalTable.clear();
        journalTable.JournalId = journalTableData.nextJournalId();
        journalTable.JournalNameId =  InventParameters::find().BOMJournalNameId;
        journalTable.JournalType = InventJournalType::BOM;
        journalTableData.initFromJournalName(journalTableData.journalStatic().findJournalName(journalTable.JournalNameId));
        journalTable.insert();
   
        journalTrans.clear();
        journalTrans.JournalId      = journalTable.JournalId;
        journalTrans.JournalType    = InventJournalType::BOM;
       
       
       
        numberSeq1 = NumberSeq::newGetNum(InventParameters::numRefInventJournalVoucherId());
        numV = numberSeq1.num();
   
      
        journalTrans.Voucher = numV;
        journalTransData.initFromJournalTable();

        dialog = new Dialog();
        dlgfeild = dialog.addField(extendedTypeStr(BOMId));

        dialog.run();
        filename = dlgfeild.value();

         select line where line.bomid == filename;
            {
                journalTrans.LineNum = L;
                journalTrans.TransDate      = systemdateget();
               
                numberSeq = NumberSeq::newGetNum(Inventparameters::numRefInventTransId());
                num = numberSeq.num();
                journalTrans.InventTransId = num;
                journalTrans.InventTransIdFather = '00162615_068';
                journalTrans.ItemId =line.ItemId;
                journalTrans.CostAmount = line.CostPrice;
                // Dimension details
                inventDim.configId = 'HD';
                inventDim.InventSizeId ='42';
                inventDim.InventColorId ='01';
                inventDim.InventSiteId ='1';
                inventDim.InventLocationId = '11';
                inventDim.inventBatchId = '1001';
                //inventDim.wMSLocationId = '11';
               
                journalTrans.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;

                journalTrans.BOMLine = true;
                //journalTransData.create();
                    journalTrans.insert();
                    //L += 10;

            }
       

        // Call the static method to post the journal
        if(InventJournalCheckPost::newPostJournal(journalTable).validate())
        InventJournalCheckPost::newPostJournal(journalTable).run();
}

// for Multiple lines
error

void clicked()
{

        InventJournalTable          journalTable ;
        InventJournalTrans          journalTrans,inventJournalTransAssembly;
        InventTransOrigin           inventTransOrigin;
        InventJournalTableData      journalTableData;
        InventJournalTransData      journalTransData;
        InventJournalNameId         inventJournalName;
   
        InventTransId               inventtransid;
        InventTransId               num;
        InventJournalVoucherId      numV;
        ComboBOMHeader              Header;
        Filename                    filename;
        NumberSeq                   numberSeq,numberSeq1;
        ComboBOMLine                line;
       
        InventDim                   inventDim;
        Dialog                      dialog;
        DialogField                 dlgfeild;
        str a;
        InventJournalCheckPost      journalCheckPost;// = new InventJournalCheckPost();
        int   L = 10;
        ;
        
        journalTableData = JournalTableData::newTable(journalTable);
        journalTransData = journalTableData.journalStatic().newJournalTransData(journalTrans,journalTableData);
//
        journalTable.clear();
        journalTable.JournalId = journalTableData.nextJournalId();
        journalTable.JournalNameId =  InventParameters::find().BOMJournalNameId;
        journalTable.JournalType = InventJournalType::BOM;
        journalTableData.initFromJournalName(journalTableData.journalStatic().findJournalName(journalTable.JournalNameId));
        journalTable.insert();
   
        journalTrans.clear();
        journalTrans.JournalId      = journalTable.JournalId;
        journalTrans.JournalType    = InventJournalType::BOM;
       
       
       
        numberSeq1 = NumberSeq::newGetNum(InventParameters::numRefInventJournalVoucherId());
        numV = numberSeq1.num();
   
      
        journalTrans.Voucher = numV;
        journalTransData.initFromJournalTable();

        dialog = new Dialog();
        dlgfeild = dialog.addField(extendedTypeStr(BOMId));

        dialog.run();
        filename = dlgfeild.value();

        while select line where line.bomid == filename
            {
                journalTrans.LineNum = L;
                journalTrans.TransDate      = systemdateget();
               
                numberSeq = NumberSeq::newGetNum(Inventparameters::numRefInventTransId());
                num = numberSeq.num();
               
                //journalTrans.InventTransId = num;           
                journalTrans.ItemId =line.ItemId;
               
                    if( L <= 10)
                    {
                   
                        journalTrans.InventTransId = num;
                        journalTrans.BOMLine = false;
                        journalTrans.Qty    = line.qty;
                    }      
                    if(L > 11)
                    {
                        journalTrans.BOMLine = true;
                        inventJournalTransAssembly = InventJournalTrans::findInventTransId(num);
                        //select InventTransId from journalTrans where journalTrans.InventTransId == inventTransOrigin.InventTransId
                                                                     //&& inventTransOrigin.InventTransId == num;
                        //
                        //journalTrans.InventTransIdFather = num;
                        journalTrans.Qty    = -(line.qty);
                        //info(strFmt("%1",journalTrans.Qty));
                    }
                    journalTrans.CostAmount = line.CostPrice;
                    // Dimension details
                    inventDim.configId = '';
                    inventDim.InventSizeId ='02';
                    inventDim.InventColorId ='';
                    inventDim.InventSiteId ='1';
                    inventDim.InventLocationId = '11';
                    inventDim.inventBatchId = '1001';
                    //inventDim.wMSLocationId = '11';
               
                    journalTrans.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;

                    //journalTrans.BOMLine = true;
                    //journalTransData.create();
                    journalTrans.insert();
                    L += 10;

            }
       
        // Call the static method to post the journal
        if(InventJournalCheckPost::newPostJournal(journalTable).validate())
        InventJournalCheckPost::newPostJournal(journalTable).run();
}