Thursday, December 5, 2013

Code to get display value from default dimension

Below code can be used for finding out the display value of a default dimension.

VendTable                                    vendTable;
DimensionAttributeValueSet          dimAttrValueSet;
DimensionAttributeValueSetItem   dimAttrValueSetItem;
DimensionAttributeValue               dimAttrValue;
DimensionAttribute                        dimAttr;
Common                                       dimensionValueEntity;
;

vendTable = VendTable::find(‘VEND_001’);

dimAttrValueSet = DimensionAttributeValueSet::find(vendTable.DefaultDimension);

while select dimAttrValueSetItem
      where dimAttrValueSetItem.DimensionAttributeValueSet == dimAttrValueSet.RecId
{
      dimAttrValue = DimensionAttributeValue::find(dimAttrValueSetItem.DimensionAttributeValue);

      dimAttr = DimensionAttribute::find(dimAttrValue.DimensionAttribute);

      dimensionValueEntity = DimensionDefaultingControllerBase::findBackingEntityInstance(curext(),  
                                              dimAttr, dimAttrValue.EntityInstance);

      info(dimAttr.Name + ' ' + dimAttrValue.getValue());
}

Create number sequence record through code including format in Ax 2012

The below code can be used to create a new number sequence record and format can also be specified without opening the form.      

NumberSequenceTable   numberSeqTable;
NumberSequenceScope  numberSeqScope;
container                         segments;
str                                   annotatedFormat, format;
;

select  numberSeqScope
       where numberSeqScope.DataArea == 'QYS';

segments += [[0, 'QYS']];
segments += [[-1,'-']];
segments += [[-2,'######']];

annotatedFormat  = NumberSeq::createAnnotatedFormatFromSegments(segments);
format                  = NumberSeq::createAnnotatedFormatFromSegments(segments, false);

numberSeqTable.clear();
numberSeqTable.NumberSequence           = '111';
numberSeqTable.Txt                                 = 'Test';
numberSeqTable.AnnotatedFormat           = annotatedFormat;
numberSeqTable.NumberSequenceScope = numberSeqScope.RecId;
numberSeqTable.Format                           = format;
numberSeqTable.Highest                           = 999999;
numberSeqTable.Lowest                           = 1;
numberSeqTable.NextRec                         = 1;
numberSeqTable.insert();

Code to retrieve the postal addresses of customers, vendors, employees etc. based on the Party ID and Location Role type.

Hi guys please find the below code to get the postal addresses of customer based on the Party ID and location role type.

    CustTable                                  custTable;
    LogisticsPostalAddress              postalAddress;
    DirPartyLocation                       dirPartyLocation;
    DirPartyLocationRole                dirPartyLocationRole;
    LogisticsLocationRole                locationRole;
    LogisticsLocation                       logisticsLocation;
    ;
   
    custTable = CustTable::find("C-000005");
   
    select postalAddress
        join Description from logisticsLocation
            join dirPartyLocation
                join dirPartyLocationRole
                    join locationRole
                    where postalAddress.Location                         == dirPartyLocation.Location
                        && logisticsLocation.RecId                          == dirPartyLocation.Location
                        && dirPartyLocation.RecId                          == dirPartyLocationRole.PartyLocation
                        && dirPartyLocationRole.LocationRole        == locationRole.RecId
                        && dirPartyLocation.Party                           == custTable.Party
                        && locationRole.Type                                  == LogisticsLocationRoleType::Delivery; //(to get delivery address)
   
    info(strFmt("%1, %2", logisticsLocation.Description, postalAddress.Address));

The above code is an example for customer address. Similarly we can find it for vendors, employees etc by passing the party id of the corresponding record.

Code to create masters in AX 2012


Vendor master creation through code in AX 2012

DirPerson           dirPerson;
DirPersonName dirPersonName;
DirParty             dirParty;
VendTable         vendTable;
DirOrganization  dirOrganisation;
;

//If record type is Person

/*dirPerson.Name             = 'Test name';
dirPerson.NameAlias        = 'Test alias name';
dirPerson.NameSequence = dirNameSequence::find('First Last').RecId;
dirPerson.insert();


dirPersonName.FirstName       = 'Test first name';
dirPersonName.MiddleName   = 'Test middle name';
dirPersonName.LastName       = 'Test last name';
dirPersonName.ValidFrom      = DateTimeUtil::newDateTime(systemDateGet(),str2time ('00:00:00'),DateTimeUtil::getUserPreferredTimeZone());
dirPersonName.ValidTo          = DateTimeUtil::maxValue();
dirPersonName.Person            = dirPerson.RecId;
dirPersonName.insert();


dirParty = new DirParty(dirPerson);*/

//If record type is Organization

dirOrganisation.Name               = 'Test name';
dirOrganisation.NameAlias       = 'Test alias name';
dirOrganisation.LanguageId      = 'EN-US';
dirOrganisation.KnownAs        = 'Test';
dirOrganisation.PhoneticName = 'Test phonetic name';
dirOrganisation.insert();


dirParty = new DirParty(dirOrganisation);


ttsBegin;
vendTable.initValue();
vendTable.AccountNum       = 'VENDTEST_001';
vendTable.Party                   = dirOrganisation.RecId; //dirPerson.RecId;
vendTable.Currency             = 'AED';
vendTable.VendGroup         = '10';
vendTable.initFromVendGroup(VendGroup::find(vendTable.VendGroup));
vendTable.insert();
ttsCommit;



Customer master creation through code in AX 2012


DirPerson            dirPerson;
DirPersonName  dirPersonName;
DirParty              dirParty; 
CustTable           custTable;
DirOrganization   dirOrganisation;
;

//If record type is Person

/*dirPerson.Name              = 'Test name';
dirPerson.NameAlias         = 'Test alias name';
dirPerson.NameSequence  = dirNameSequence::find('First Last').RecId;
dirPerson.insert();


dirPersonName.FirstName         = 'Test first name';
dirPersonName.MiddleName     = 'Test middle name';
dirPersonName.LastName         = 'Test last name';
dirPersonName.ValidFrom        = DateTimeUtil::newDateTime(systemDateGet(),str2time ('00:00:00'),DateTimeUtil::getUserPreferredTimeZone());
dirPersonName.ValidTo            = DateTimeUtil::maxValue();
dirPersonName.Person              = dirPerson.RecId;
dirPersonName.insert();


dirParty = new DirParty(dirPerson);*/

//If record type is Organization

dirOrganisation.Name              = 'Test name';
dirOrganisation.NameAlias      = 'Test alias name';
dirOrganisation.LanguageId     = 'EN-US';
dirOrganisation.KnownAs       = 'Test';
dirOrganisation.PhoneticName = 'Test phonetic name';
dirOrganisation.insert();

dirParty = new DirParty(dirOrganisation);


ttsBegin;
custTable.clear();
custTable.initValue();
custTable.Party              = dirOrganisation.RecId;
custTable.AccountNum  = 'CUST0001';
custTable.Currency        = 'USD';
custTable.CustGroup     = '20';
custTable.initFromCustGroup(CustGroup::find(custTable.CustGroup));
custTable.insert();
ttsCommit;




Retail store master creation through code in AX 2012

RetailStoreTable    store; 
OMOperatingUnit operatingUnit;
DirOrganization     orgn;
DirParty                dirParty;
NumberSeq           numSeq;


orgn.clear();
orgn.Name          = 'Store1';
orgn.NameAlias  = 'Store1 alias name';
orgn.LanguageId = 'EN-US';
orgn.insert();

dirParty = new DirParty(orgn);

numSeq = NumberSeq::newGetNum(OMOperatingUnit::getNumberSequenceReference());

operatingUnit.initFromDirParty(dirParty);
operatingUnit.Name                                = 'Store1';
operatingUnit.OMOperatingUnitNumber = numSeq.num();
operatingUnit.OMOperatingUnitType      = OMOperatingUnitType::RetailChannel;
operatingUnit.LanguageId                        = 'EN-US';
operatingUnit.insert();

store.initValue();

store.OMOperatingUnitID  = operatingUnit.RecId;
store.DefaultCustAccount   = 'CUST0001'; //default cust account based on the requirement
store.inventLocation            = 'Loc1';
store.StoreNumber             = 'Store1';
store.Currency                    = 'SAR';
store.taxGroup                    = 'TaxGrp1';
store.insert();

Sending emails with CC and attachment in AX 2012

Hi guys, following is the code to send emails with cc and attachment from AX. 

Before proceeding, server settings must be done in the Email parameters form which is available in the below mentioned path.

System administration --> Setup --> System --> E-mail parameters.

static void mailFromAX(Args _args)
{
    str                                   sender    = 'abc@example.com';  // mail id of the sender
    str                                   recipient = '123@example.com';  //mulitple recipients can be specified
    str                                   cc          = 'xyz@example.com';  // mulitple cc id's can be specified
    str                                   subject   = 'Subject of the mail';
    str                                   body      = 'Content of the mail';
    str                                   fileName = @'C:\Attachment.txt';  //Location of the attachment file

    List                                                       toList;
    List                                                       ccList;
    ListEnumerator                                     enumList;    
    Set                                                        permissionSet;
    System.Exception                                  exception;

    str                                                          mailServer;
    int                                                          mailServerPort;
    System.Net.Mail.SmtpClient                  mailClient;
    System.Net.Mail.MailMessage               mailMessage;
    System.Net.Mail.MailAddress                mailFrom;
    System.Net.Mail.MailAddress                mailTo;
    System.Net.Mail.MailAddressCollection mailToCollection;
    System.Net.Mail.MailAddressCollection mailCCCollection;
    System.Net.Mail.AttachmentCollection   mailAttachementCollection;
    System.Net.Mail.Attachment                  mailAttachment;
    ;

    try
    {
        toList = strSplit(recipient, ';');
        ccList = strSplit(cc, ';');
       
        permissionSet = new Set(Types::Class);
        permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
        permissionSet.add(new FileIOPermission(filename, 'test1'));
        CodeAccessPermission::assertMultiple(permissionSet);

        mailServer         = SysEmaiLParameters::find(false).SMTPRelayServerName;
        mailServerPort  = SysEmaiLParameters::find(false).SMTPPortNumber;
        mailClient          = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);

        enumList = toList.getEnumerator();
        enumList.moveNext();
       
        mailFrom      = new System.Net.Mail.MailAddress(sender);
        mailTo          = new System.Net.Mail.MailAddress(strLTrim(strRTrim(enumList.current())));
        mailMessage = new System.Net.Mail.MailMessage(mailFrom, mailTo);
       
        mailToCollection = mailMessage.get_To();
        while (enumList.moveNext())
        {
            mailToCollection.Add(strLTrim(strRTrim(enumList.current())));
        }
       
        enumList                 = ccList.getEnumerator();
        mailCCCollection    = mailMessage.get_CC();
        while (enumList.moveNext())
        {
            mailCCCollection.Add(strLTrim(strRTrim(enumList.current())));
        }
       
        mailMessage.set_Priority(System.Net.Mail.MailPriority::High);
        mailMessage.set_Subject(subject);
        mailMessage.set_Body(body);

        mailAttachementCollection   = mailMessage.get_Attachments();
        mailAttachment              = new System.Net.Mail.Attachment(fileName);
        mailAttachementCollection.Add(mailAttachment);

        mailClient.Send(mailMessage);
        mailMessage.Dispose();

        CodeAccessPermission::revertAssert();

        info("Email sent successfully");
    }
    catch (Exception::CLRError)
    {
        exception = ClrInterop::getLastException();
        while (exception)
        {
            info(exception.get_Message());
            exception = exception.get_InnerException();
        }
        CodeAccessPermission::revertAssert();
    }

}