Thursday, May 24, 2012

AX 2012 - How to debug Code in Visual Studio

This post basically addresses how to debug code in Visual studio. 
Most of code running on AOS runs in CIL environment, so it cannot be debugg in Microsoft Dynamics AX Debugger.
You might have confused/surprised why ax debugger is not opening inspite of  inserting breakpoint at particular place. It means code might be running in CIL and to debug visual studio 2010 is required.

Step1: 
Make sure AOS Service runs on account which you logged in. Right click on AOS Service and change log on property to logged in windows credentials.
Log off windows and then re log in.           

Step2:
Open visual studio and click on AX Application explorer (Shortcut Ctrl + D)
AOT opens and you can browse nodes as you used to do in Dynamics AX.
Open the object which you want to debug and insert breakpoint.

Step3:
Then in Visual studio, Click on Debug->Attach process

As shown in above image, First make sure two check boxes at bottom are marked.
Then only you can find and able to select AX32Serv.exe(AOS)  process and click on attach button.

Note : When you are doing this step 3 for first time it prompts you to Restart Visual studio, kindly select the same option.

Step4:
You done with setting up visual studio to debug code running in CIL.
Now restrart process in Dynamics AX which you want to debugg and you can find Visual studio debugger opened for you.
Continue debugging with hotkeys as you use to do in AX debugger like F10/F11.

AX 2012 - X++ Code to 'Create and Post Purchase Order Invoice'

Find below job to create and post purchase order in Dynamics AX 2012 

Note: Referring contoso demo data, 'CEU' company

static void CreatePOAndInvoice(Args _args)
{
    PurchTable      purchTable;
    PurchLine       purchLine;
    VendTable       vendTable = VendTable::find("3008");
    AxPurchTable    axPurchTable;
    AxPurchLine     axPurchLine;
    PurchFormLetter purchFormLetter;
   
    //Create Purchase order
    purchTable.initFromVendTable(vendTable);
   
    axPurchTable = axPurchTable::newPurchTable(purchTable);
    axPurchTable.parmPurchaseType(PurchaseType::Purch);
    axPurchTable.parmDocumentStatus(DocumentStatus::PurchaseOrder);
    axPurchTable.parmAccountingDate(systemDateGet());
    axPurchTable.parmDeliveryDate(01\06\2012);
    axPurchTable.parmPurchStatus(PurchStatus::Backorder);
    axPurchTable.doSave();

    //Create PurchLine for item 1000
    purchLine.initFromPurchTable(purchTable);

    axPurchLine = AxPurchLine::newPurchLine(purchLine);
    axpurchLine.parmItemId("1000");
    axPurchLine.parmPurchQty(10);
    axPurchLine.parmPurchPrice(100);
    axPurchLine.doSave();

    //Posting PO Confirmation,I guess its mandatory
    //You cannot do invoice without doing PO confirm
    purchTable = axPurchTable.purchTable();
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PurchaseOrder);
    purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

    //Posting PO Invoice
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
    purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

}

Setup Email Alerts and X++ Code to Send Mail in DAX 2009.

Following steps illustrates how to setup and activate Email Alerts in DAX 2009.

In Ax we have two types of Alerts.
    1 ) Pop-Up Alerts , shown in AX Forms as pop-up windows.
    2 ) Email Alerts , where alert message will be sent to users by mail.  In other words its extended
         version of Pop-up Alerts.

How it Works :
   a ) For every alert ax creates record in SysOutgoingEmailTable and  
        SysOutgoingEmailData.
   b ) Then Email distributor batch(Class->SysEmailBatch->run method)  job reads the message
         from the above table and after validating execute the mail.

Now we will see what all setups are required for activating second type of alert.

Step1 : Activates the Alerts feature for user in options form .
             Go to  Tool-->Options  , set show email alerts  as


 Step 2 :  Set Email Parameters , Administration->Setup->Email Parameters
                 Define parameters like which SMTP  Server to use for sending mails and credentials
                 by which mail will be sent to users.




Step 3 : Add Email distributor batch to BatchJob Queue. This job will be responsible for sending mails to users. So if you are not receiving any email it means u have not scheduled this batch job to run.
             Administration->Periodic->Email-Processing--->Batch
Set the recurrence as No End date and minutes as 15-30 minutes.

Step 4 : Check the Batch Job queue for Email distributor batch job , you should find new record
               in batch queue as 
               Basic-->Inquiries-->Batch Job
               For this record Click on Alerts and select check box "Error" . It means whenever this
               batch job fails you will get alert. 

Incase of any failure you can debugg SysEmailBatch Class run method .

Step 5: Set up Email Templates and attach to EventParameters.
              Basic -> Setup -> Alerts -> Alert Parameter.

Step 6 :   Job to test whether u have configured correctly or not.
                  static void Mail_Send(Args _args)
                 {

                       EventParameters eventParameters = EventParameters::find();
                      SysUserInfo             sysUserInfo;
                     UserInfo                userInfo;
                     ;

                    // SysUserInfo has Alert and email info
                    sysUserInfo = SysUserInfo::find(curuserid());

                     // UserInfo has the language info
                    //userInfo = xUserInfo::find(false, eventRule.UserId);
                                         
 SysEmailTable::sendMail(eventParameters.AlertTemplateId,userInfo.Language,sysUserInfo.Email);

               }  
             

Even workflow framework uses same alert setups for sending mails for approval and task notifications.

Steps to Implement Default Account in Dynamics ax 2012.


Create a new Table in the AOT and name it for example SampleDimensionPattern.
2. Add a new field in the SampleDimensionPattern table of type Int64 and name it ExpenseLedgerDimension and specify the EDT on that field as LedgerDimensionDefaultAccount
3. Add a new form under form node in the AOT and name it as TutorialDefaultAccountForm
4. Add/ Drag the table SampleDimensinPattern to the datasource node of the form.
5. Right mouse click on the TabPage:TabDefaultAccount node and select New Control -> SegmentedEntry from the list.  This creates a new Segmented Entry control that we can now specialize to handle default accounts.
6. Highlight the node SegmentedEntry:SegmentedEntry and change the Name, DataSource and ReferenceField properties to ExpenseLedgerDimension, SampleDimensionPatterns and ExpenseLedgerDimension.
7. Place the following code in Declaration area of the form
public class FormRun extends ObjectRun
{   LedgerDimensionDefaultAccountController ledgerDimensionDefaultAccountController;
}
8. In the Init method add below code
public void init()
{
   super();
   ledgerDimensionDefaultAccountController =
   LedgerDimensionDefaultAccountController::construct(SampleDimensionPatterns_ds,
          fieldstr(SampleDimensionPatterns, ExpenseLedgerDimension));
}
9. Overload the following methods on the method of new Segmented entry control that is added in step 6
jumpRef
public void jumpRef()
{
ledgerDimensionDefaultAccountController.jumpRef();
}
loadAutoCompleteData
public void loadAutoCompleteData(LoadAutoCompleteDataEventArgs _e)
{
super(_e);
ledgerDimensionDefaultAccountController.loadAutoCompleteData(_e);
}
segmentValueChanged
public void segmentValueChanged(SegmentValueChangedEventArgs _e)
{
super(_e);
ledgerDimensionDefaultAccountController.segmentValueChanged(_e);
}
loadSegments
public void loadSegments()
{
super();
ledgerDimensionDefaultAccountController.parmControl(this);
ledgerDimensionDefaultAccountController.loadSegments();
}
 validate
public boolean validate()
{
boolean isValid;
isValid = super();
isValid = ledgerDimensionDefaultAccountController.validate() && isValid;
return isValid;
}
10. Overload the resolveReference method in the method node of the datasource field “ExpenseLedgerDimension”.
public Common resolveReference(FormReferenceControl _formReferenceControl)
{
    return ledgerDimensionDefaultAccountController.resolveReference();
}

Tuesday, May 15, 2012

Dynamics AX 2012 - X++ code to create General Journal

static void Demo_CreateGLJournal(Args _args)
{
    AxLedgerJournalTable journalTable;
    AxLedgerJournalTrans journalTrans;
    container            accEntryPattern;
    container            offSetEntryPattern;
    ;

    journalTable = new AxLedgerJournalTable();
    journalTrans = new AxLedgerJournalTrans();

    //Journal Name
    journalTable.parmJournalName("GenJrn");
    journalTable.save();

    journalTrans.parmJournalNum(journalTable.ledgerJournalTable().JournalNum);
    journalTrans.parmTransDate(systemDateGet());
    journalTrans.parmAccountType(LedgerJournalACType::Ledger);

    //LedgerDimension  => Ledgeraccount, DAX 2009
    accEntryPattern = ["601501", "601501", 0]; 
    journalTrans.parmLedgerDimension(AxdDimensionUtil::getLedgerAccountId(accEntryPattern));

    journalTrans.parmAmountCurDebit(2000);

    //OffsetLedgerDimension => OffsetLedgerAccount,  DAX 2009
    offSetEntryPattern = ["401100", "401100", 0];
    journalTrans.parmOffsetAccountType(LedgerJournalACType:: Ledger );
    journalTrans.parmOffsetLedgerDimension(AxdDimensionUtil::getLedgerAccountId( offSetEntryPattern));
  
    journalTrans.save();

    info(strFmt("Journal %1 created", journalTable.ledgerJournalTable().JournalNum));
}

How to post with Financial dimensions:

Format : 
["DisplayValue", "MainAccount", NumberOfDimensions, "DimensionName", "DimensionValue"]; 

E.g:
accEntryPattern = ["601501-Test", "601501", 1, "Department", "OU_1"]

Monday, May 14, 2012

Limiting user sessions

select count(recid) from sysClientSessions
where sysClientSessions.userId == curuserid() &&
sysClientSessions.Status == 1 &&
sysClientSessions.clientType == 0;

if(sysClientSessions.RecId > UserSessionLimits::getMaxSessions(curUserid()))
{
box::stop(strfmt("You have exceeded your session limit of %1, the application will now close",
UserSessionLimits::GetMaxSessions(curUserid())));
appl.globalcache().set(classstr(info),identifierStr(AutoLogoff), true);
this.shutDown(true);
}

Adding a role to all or multiple users using X++ Code [Dynamics AX 2012]


static void SR_AssignRoleToAllUsers(Args _args)
{
    SecurityRole        role;
    SecurityUserRole    userRole;
    boolean             added;
    UserInfo            userInfo;
    ;

    select role where role.Name == ‘Budget clerk’;
    while select userInfo
    {
        select * from userRole
            where userRole.SecurityRole == role.RecId &&
                userRole.User == userInfo.id;

        if (!userRole || (userRole.AssignmentStatus != RoleAssignmentStatus::Enabled))
        {
            info(strFmt(‘Role %1 added to the user %2 successfully.’, role.Name, userInfo.id));

            userRole.User = userInfo.id;
            userRole.SecurityRole = role.RecId;
            userRole.AssignmentMode = RoleAssignmentMode::Manual;
            userRole.AssignmentStatus = RoleAssignmentStatus::Enabled;
            SecuritySegregationOfDuties::assignUserToRole(userRole, null);
        }
        else
        {
            warning(strFmt(‘skipping – Role %1 to the user %2.’, role.Name, userInfo.id));
        }
    }
}

Get underlying SQL query using getSQLStatement [Dynamics AX 2012]


static void SR_getSQLStatement(Args _args)
{
    CustTable custTable;
    CustTrans custTrans;
    ;
   
    select generateonly firstOnly AccountNum, CustGroup
        from custTable join custTrans where custTrans.AccountNum == custTable.AccountNum;
    info(custTable.getSQLStatement());

}

Remove new line from text


display str 250 CompanyAddress()
{
    str 250 Address;
    TextBuffer txt = new TextBuffer();
;


    CompanyInfo = CompanyInfo::find();
    Address = companyInfo.postalAddress().Address;
    txt.setText(Address);
    txt.replace('\n',' ');
    Address = txt.getText();
    Address = Address + "  Company Registration Number " + CompanyInfo.BranchId + " Tax Registration Number " + Companyinfo.CoRegNum;



    return Address;
}

Wednesday, May 9, 2012

Correct file to upload in ax 2012


static void loadCSVFile(Args _args)

{
LedgerJournalTrans_Asset                ledgerJournalTrans_Asset;
    DimensionValue                            displayValue;
     DimensionDisplayValue                   dimensionDisplayValue;
     DimensionAttributeValueCombination      dimensionAttributeValueCombination;
    DimensionAttributeValueSet              dimensionAttributeValueSet;
    str 70                                  transType,dates;
    LedgerJournalTrans                      ledgerJournalTrans;
    DimensionAttributeValueSetItem          dimensionAttributeValueSetItem;
Dialog dialog;
DialogField dialogFileName;
SysOperationProgress simpleProgress;
Filename filename;
FileIOPermission permission;
TextIo textIo;

container c1,c2;


#File

#avifiles

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


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




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

if(!filename)
{
info("Filename must be filled");
error("file name must be filled");
}
permission = new FileIOPermission(filename,#io_read);
permission.assert();
textIo = new TextIo(filename,#io_read);
textIo.inFieldDelimiter(';');///Change the Delimeter if it is , or ; etc
simpleProgress = SysOperationProgress::newGeneral(#aviUpdate, 'Importing sales data',100);
if(textIo)
{
    while(textIo.status() == IO_Status::Ok)
    {
    c1 = textIo.read();



            if (c1)
            {
                ledgerJournalTrans.clear();
                ttsbegin;
                ledgerJournalTrans.AccountType              = LedgerJournalACType::FixedAssets;
                dates = conPeek(c1,1);
                ledgerJournalTrans.AcknowledgementDate      = str2Date(dates,123);
                ledgerJournalTrans.AmountCurDebit           = conPeek(c1,2);
                ledgerJournalTrans.Company                  = conPeek(c1,3);
                ledgerJournalTrans.CurrencyCode             = conPeek(c1,4);
                ledgerJournalTrans.ExchRate                 = conPeek(c1,5);
                ledgerJournalTrans.JournalNum               = conPeek(c1,6);
                ///////////////////////////////////LEDGER DIMENSION/////////////////////
                displayValue                                = conPeek(c1,7);
                select * from dimensionAttributeValueCombination where dimensionAttributeValueCombination.DisplayValue == displayValue;
                ledgerJournalTrans.LedgerDimension          = dimensionAttributeValueCombination.RecId;
                ///////////////////////////////////////////////////////////////////////

                ledgerJournalTrans.LineNum                  = conPeek(c1,8);
                ledgerJournalTrans.OffsetAccountType        = LedgerJournalACType::Ledger;
                ledgerJournalTrans.OffsetCompany            = conPeek(c1,9);

                /////////////////////////OFFSETDEFAULTDIMENSION///////////////
                displayValue                                = conPeek(c1,10);
                select * from dimensionAttributeValueSetItem where dimensionAttributeValueSetItem.DisplayValue == displayValue;
                ledgerJournalTrans.OffsetDefaultDimension   = dimensionAttributeValueSetItem.RecId;
                ////////////////////////////////////////

                ////////////////////////////////OFSETLEDGERDIMENSION//////////////////////////
                displayValue                                = conPeek(c1,11);
                select * from dimensionAttributeValueCombination where dimensionAttributeValueCombination.DisplayValue == displayValue;
                ledgerJournalTrans.OffsetLedgerDimension    = dimensionAttributeValueCombination.RecId;
                ///////////////////////////////////////////////////////////////////////////////

                ledgerJournalTrans.Price                    = conPeek(c1,12);
                ledgerJournalTrans.Qty                      = conPeek(c1,13);
                ledgerJournalTrans.TaxItemGroup             = conPeek(c1,14);
                ledgerJournalTrans.Voucher                  = conPeek(c1,15);

                dates = conPeek(c1,16);
                ledgerJournalTrans.TransDate                = str2Date(dates,123);
                ledgerJournalTrans.Txt                      = conPeek(c1,17);
                ledgerJournalTrans.CurrencyCode             = conPeek(c1,18);

                //LedgerJournalTrans.insert();

                ttscommit;
            }

    }

}

}

Fixed asset to LedgerjournalTrans


static void ledgerjournaltrans_fixed(Args _args)
{
    LedgerJournalTrans_Asset                LedgerJournalTrans_Asset;
    DimensionValue                            DisplayValue;
     DimensionDisplayValue                   DimensionDisplayValue;
    LedgerJournalTrans                      LedgerJournalTrans;
    SysOperationProgress simpleProgress;

    DimensionAttributeValueCombination      DimensionAttributeValueCombination;
    DimensionAttributeValueSet              DimensionAttributeValueSet;
    FileIOPermission permission;

    CommaIO                                 csvFile;
    container                               readCon;
    counter                                 icount,inserted;
    Dialog                                  dialog;
    DialogField                             dfFileName;
    FileName                                fileName;
    str                                     contactperson;
    str 70                                  TransType,dates;
    DimensionAttributeValueSetItem          DimensionAttributeValueSetItem;
    BinData binData;
    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();

        while (csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            icount++;
            if (readCon)
            {
                LedgerJournalTrans.clear();
                ttsBegin;
                LedgerJournalTrans.AccountType              = LedgerJournalACType::FixedAssets;
                dates = conPeek(readCon,1);
                LedgerJournalTrans.AcknowledgementDate      = str2Date(dates,123);
                LedgerJournalTrans.AmountCurDebit           = conPeek(readCon,2);
                LedgerJournalTrans.Company                  = conPeek(readCon,3);
                LedgerJournalTrans.CurrencyCode             = conPeek(readCon,4);
                LedgerJournalTrans.ExchRate                 = conPeek(readCon,5);
                LedgerJournalTrans.JournalNum               = conPeek(readCon,6);
                ///////////////////////////////////LEDGER DIMENSION/////////////////////
                DisplayValue                                = conPeek(readCon,7);
                select * from DimensionAttributeValueCombination where DimensionAttributeValueCombination.DisplayValue == DisplayValue;
                LedgerJournalTrans.LedgerDimension          = DimensionAttributeValueCombination.RecId;
                ///////////////////////////////////////////////////////////////////////

                LedgerJournalTrans.LineNum                  = conPeek(readCon,8);
                LedgerJournalTrans.OffsetAccountType        = LedgerJournalACType::Ledger;
                LedgerJournalTrans.OffsetCompany            = conPeek(readCon,10);

                /////////////////////////OFFSETDEFAULTDIMENSION///////////////
                DisplayValue                                = conPeek(readCon,11);
                select * from DimensionAttributeValueSetItem where DimensionAttributeValueSetItem.DisplayValue == DisplayValue;
                LedgerJournalTrans.OffsetDefaultDimension   = DimensionAttributeValueSetItem.RecId;
                ////////////////////////////////////////

                ////////////////////////////////OFSETLEDGERDIMENSION//////////////////////////
                DisplayValue                                = conPeek(readCon,12);
                select * from DimensionAttributeValueCombination where DimensionAttributeValueCombination.DisplayValue == DisplayValue;
                LedgerJournalTrans.OffsetLedgerDimension    = DimensionAttributeValueCombination.RecId;
                ///////////////////////////////////////////////////////////////////////////////

                LedgerJournalTrans.Price                    = conPeek(readCon,13);
                LedgerJournalTrans.Qty                      = conPeek(readCon,14);
                LedgerJournalTrans.TaxItemGroup             = conPeek(readCon,15);
                LedgerJournalTrans.Voucher                  = conPeek(readCon,16);
//                LedgerJournalTrans.dataAreaId               = conPeek(readCon,17);
                dates = conPeek(readCon,18);
                LedgerJournalTrans.TransDate                = str2Date(dates,123);
                LedgerJournalTrans.Txt                      = conPeek(readCon,19);
                LedgerJournalTrans.CurrencyCode             = conPeek(readCon,20);
                LedgerJournalTrans.AmountCurDebit           = conPeek(readCon,21);


                //LedgerJournalTrans.insert();

                ttsCommit;
            }
        }

    }
    info(strfmt("%1 records inserted out of %2",inserted,icount));

}

import fixed asset to Fixed asset Trans asset


static void ledgerjournalTrans_FixedAsset(Args _args)
{
    LedgerJournalTrans_Asset                LedgerJournalTrans_Asset;
     DimensionDisplayValue                   DimensionDisplayValue;
    LedgerJournalTrans                      LedgerJournalTrans;
    DimensionAttributeValueCombination      DimensionAttributeValueCombination;
    CommaIO                                 csvFile;
    container                               readCon;
    counter                                 icount,inserted;
    Dialog                                  dialog;
    DialogField                             dfFileName;
    FileName                                fileName;
    str                                     contactperson;
    str 70                                  TransType;
    BinData binData;
    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)
            {
                DimensionDisplayValue = conPeek(readCon,1);

                select * from DimensionAttributeValueCombination where DimensionAttributeValueCombination.DisplayValue == DimensionDisplayValue;
                select  * from LedgerJournalTrans where LedgerJournalTrans.LedgerDimension == DimensionAttributeValueCombination.RecId ;
                LedgerJournalTrans_Asset.clear();
                select * from LedgerJournalTrans_Asset where LedgerJournalTrans_Asset.RefRecId == LedgerJournalTrans.RecId;
                if(!LedgerJournalTrans_Asset)
                {
                    ttsBegin;
                    LedgerJournalTrans_Asset.AssetId            = DimensionDisplayValue;
                    LedgerJournalTrans_Asset.RefAssetID         = DimensionDisplayValue;
                    LedgerJournalTrans_Asset.BookId             = conPeek(readCon,2);
                    LedgerJournalTrans_Asset.Company            = conPeek(readCon,3);
                    LedgerJournalTrans_Asset.FAQty              = conPeek(readCon,4);
                    LedgerJournalTrans_Asset.FAUnit             = conPeek(readCon,5);
                    LedgerJournalTrans_Asset.FAUnitPrice        = conPeek(readCon,6);
                    TransType = conPeek(readCon,7);
                    if(TransType == "Acquisition")
                    {
                    LedgerJournalTrans_Asset.TransType             = AssetTransTypeJournal::Acquisition;
                    }
                    else
                        if(TransType == "Depreciation")
                            {
                                 LedgerJournalTrans_Asset.TransType             = AssetTransTypeJournal::Depreciation;
                            }

                    LedgerJournalTrans_Asset.insert();
                    ttsCommit;
                }

            }
        }
        ttsCommit;
    }
    info(strfmt("%1 records inserted out of %2",inserted,icount));

}

How to identify the user that was used to change an object from AOT in AX2012

Get the object name for which we need to track these (user and date&time) information's. Login to SQL Server Management Studio an...