Thursday, January 21, 2016

Refreshing caller form in ax 2012

//To refresh caller form ax 2012

//CLass
#Task
    FormRun formRun;
    formRun = element.args().caller();
    if(formRun)
    {
        formRun.task(#taskF5);
    }

//form
FormRun             callingForm;
    Object              o;

;
 callingForm = this.args().caller() as FormRun;
        if (callingForm != null && formHasMethod(callingForm, identifierStr(refresh)))
        {
            o = callingForm;
            o.refresh();
        }


callingForm          = element.args().caller();
callingForm.dataSource().refresh();
callingForm.dataSource().reread();
callingForm.dataSource().research();

Assign New User Roles and Groups from Existing User ax 2012


// Assign New User Roles and Groups from Existing User ax 2012
public void fromUserLookup(FormStringControl userLookupControl)
{
    Query                   qry = new Query();
    QueryBuildDataSource    qbd;
    QueryBuildRange         qbr;
    SysTableLookup          sysTableLookup;
    Userinfo                userInfo;
    systablelookup = SysTableLookup::newParameters(tableNum(UserInfo), userLookupControl);
    SysTableLookup.addLookupfield(fieldNum(UserInfo, ID));
    SysTableLookup.addLookupfield(fieldNum(UserInfo, NetworkAlias));
    SysTableLookup.addLookupfield(fieldNum(UserInfo, Name));
    qbd = qry.addDataSource(tableNum(userInfo));
    qbd.addRange(fieldNum(UserInfo,Company)).value(curext());
    sysTableLookup.parmQuery(qry);
    sysTableLookup.performFormLookup();
}
public void toUserLookup(FormStringControl userLookupControl)
{
    Query                   qry = new Query();
    QueryBuildDataSource    qbd;
    QueryBuildRange         qbr;
    SysTableLookup          sysTableLookup;
    Userinfo                userInfo;
    systablelookup = SysTableLookup::newParameters(tableNum(UserInfo), userLookupControl);
    SysTableLookup.addLookupfield(fieldNum(UserInfo, ID));
    SysTableLookup.addLookupfield(fieldNum(UserInfo, NetworkAlias));
    SysTableLookup.addLookupfield(fieldNum(UserInfo, Name));
    qbd = qry.addDataSource(tableNum(userInfo));
    qbd.addRange(fieldNum(UserInfo,Company)).value(curext());
    qbr = qbd.addRange(fieldNum(UserInfo, Enable));
    qbr.value('1');
    sysTableLookup.parmQuery(qry);
    sysTableLookup.performFormLookup();
}
//Function to copy USER ROLES
private boolean copyUserRoles()
{
    boolean                 ret = true;
    SecurityRole            securityRole;
    SecurityUserRole        securityUserRole;
    SecurityUserRole        securityUserRoleExist;
    SecurityUserRole        securityUserRoleInsert;
    OMUserRoleOrganization  userRoleOrganization, userRoleOrganization_Insert;
    List                    copiedUserRoles = new List(Types::String);
    ListEnumerator          lEnumerator;
    setPrefix(strFmt("Copy user", fromUser, toUser));
    try
    {
        select securityRole where securityRole.AotName == 'SystemUser';
        delete_from securityUserRole where securityUserRole.User == toUser
&& securityUserRole.SecurityRole == securityRole.RecId;      
        while select securityUserRole
                where securityUserRole.User == fromUser
            notExists join * from securityUserRoleExist
                where securityUserRoleExist.SecurityRole    == securityUserRole.SecurityRole
                    && securityUserRoleExist.User           == toUser
        {
            select securityRole where securityRole.RecId == securityUserRole.SecurityRole;
            copiedUserRoles.addStart(securityRole.Name);
            securityUserRoleInsert.initValue();
            securityUserRoleInsert.SecurityRole = securityUserRole.SecurityRole;
            securityUserRoleInsert.User         = toUser;
            securityUserRoleInsert.insert();
            securityUserRoleInsert.clear();
            while select userRoleOrganization
                    where userRoleOrganization.User == fromUser
                        && userRoleOrganization.SecurityRole == securityUserRole.SecurityRole
            {
                userRoleOrganization_Insert.initValue();
                userRoleOrganization_Insert.OMHierarchyType             = userRoleOrganization.OMHierarchyType;
                userRoleOrganization_Insert.OMInternalOrganization      = userRoleOrganization.OMInternalOrganization;
                userRoleOrganization_Insert.SecurityRole                = userRoleOrganization.SecurityRole;
                userRoleOrganization_Insert.SecurityRoleAssignmentRule  = userRoleOrganization.SecurityRoleAssignmentRule;
                userRoleOrganization_Insert.User                        = toUser;
                userRoleOrganization_Insert.insert();
                userRoleOrganization_Insert.clear();
            }
        }
    }
    catch
    {
        ret = false;
    }
    if (ret)
    {
        lEnumerator = copiedUserRoles.getEnumerator();
        if (copiedUserRoles.empty())
            info(strFmt("User %1 and %2 have already the same user role",fromUser, toUser));
        while (lEnumerator.moveNext())
        {
            info(strFmt('%1',lEnumerator.current()));
        }
    }
    else
        error(strFmt("User Roles aborted please review list"));
    return ret;
}
//Function to copy USER OPTIONS
private boolean copyUserOptions()
{
    boolean                 ret = true;
    UserInfo                userInfoSource;
    UserInfo                userInfoTarget;
    SysUserInfo             sysUserInfoSource;
    SysUserInfo             sysUserInfoTarget;
    setPrefix(strFmt("Copy user options", fromUser, toUser));
    try
    {
        select userInfoSource
            where userInfoSource.id == fromUser
        join sysUserInfoSource
            where sysUserInfoSource.Id == userInfoSource.id;
        ttsBegin;      
            select forUpdate userInfoTarget where userInfoTarget.id == toUser;
            userInfoTarget.filterByGridOnByDefault = userInfoSource.filterByGridOnByDefault;
            userInfoTarget.statuslineInfo = userInfoSource.statuslineInfo;
            userInfoTarget.update();          
            select forUpdate sysUserInfoTarget where sysUserInfoTarget.Id == toUser;
            sysUserInfoTarget.DefaultCountryRegion = sysUserInfoSource.DefaultCountryRegion;
            sysUserInfoTarget.update();
        ttsCommit;
    }
    catch
    {
        ret = false;
    }
    if (ret)
    {
        info(strFmt("User %1 and %2 have already the same user options ", fromUser, toUser));
    }
    else
        error(strFmt("User Options aborted please review list "));
    return ret;
}
//Function to copy USER GROUPS
private boolean copyUserGroups()
{
    boolean                 ret = true;
    UserGroupList           userGroupList;
    UserGroupList           userGroupListExist;
    UserGroupList           userGroupListInsert;
    List                    copiedGroups = new List(Types::String);
    ListEnumerator          lEnumerator;
    setPrefix(strFmt("Copy user groups", fromUser, toUser));
    try
    {
        while select userGroupList
                where userGroupList.userId == fromUser
            notExists join * from userGroupListExist
                where userGroupListExist.groupId == userGroupList.groupId
                    && userGroupListExist.userId == toUser
        {
            copiedGroups.addStart(userGroupList.groupId);
            userGroupListInsert.initValue();
            userGroupListInsert.groupId = userGroupList.groupId;
            userGroupListInsert.userId  = toUser;
            userGroupListInsert.insert();
            userGroupListInsert.clear();
        }
    }
    catch
    {
        ret = false;
    }
    if (ret)
    {
        lEnumerator = copiedGroups.getEnumerator();
        if (copiedGroups.empty())
            info(strFmt("User %1 and %2 have already the same user Groups ",fromUser, toUser));
        while (lEnumerator.moveNext())
        {
            info(strFmt('%1',lEnumerator.current()));
        }
    }
    else
        error(strFmt("User Groups aborted please review list "));
    return ret;
}

Customer upload Address/Phone

static void Fcc_UploadCustomerInfoCsv(Args _args)
{
   CommaTextIO                     csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName;
    DirPartyPostalAddressView   addressView;
    str                                     accountnum,phone;
     LogisticsLocation   logisticsLocation;
    LogisticsElectronicAddress  electronicAddress;
    DirPartyLocation dirpartyLocation, findDirPartyLocation;
    CustTable                               custTable;
     LogisticsPostalAddress      address;
    FileName                    fileName;
    DirParty                    dirParty;
   VendTable    vendTable;
    RecId       partyRecId;
    int Ccount;
    inserted =0;
    #File

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

    if (dialog.run())
    {
        csvFile = new CommaTextIo(dfFileName.value(), 'r');
        csvFile.inFieldDelimiter(',');
        readCon = csvFile.read();
        ttsBegin;
        while(csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            if(readCon)
            {
                accountnum = conPeek(readCon,1);
                phone = conPeek(readCon,3);
                custTable = CustTable::find(accountnum);
                select findDirPartyLocation
                    where findDirPartyLocation.Party == custTable.Party
                        && findDirPartyLocation.IsPostalAddress == false;
                partyRecId = custTable.Party;
                 DirParty = DirParty::constructFromPartyRecId(partyRecId);
                address.clear();
                address.CountryRegionId = strLRTrim(conPeek(readCon,2));
                if( address.CountryRegionId != "")
                {
                    address.Street  = strLRTrim(conPeek(readCon,4));
                    addressView.LocationName = "Address";
                    addressView.IsPrimary = NoYes::Yes;
                    addressView.Party = partyRecId;
                    addressview.initFromPostalAddress(address);

                    DirParty = DirParty::constructFromPartyRecId(addressView.Party );
                    DirParty.createOrUpdatePostalAddress(addressView);
                }
               
                if (!findDirPartyLocation && accountnum != "")
                {
                    logisticsLocation.clear();
                    logisticsLocation.initValue();
                    logisticsLocation.IsPostalAddress   = NoYes::No;
                    logisticsLocation.insert();
                    electronicAddress.Description       = "Customer phone Number";
                    electronicAddress.Location          = logisticsLocation.RecId;
                    electronicAddress.Locator           = phone;
                    electronicAddress.Type              = LogisticsElectronicAddressMethodType::Phone;
                    electronicAddress.IsPrimary         = NoYes::Yes;
                    electronicAddress.insert();
                    dirpartyLocation.Location           = logisticsLocation.RecId;
                    dirpartyLocation.Party              = custTable.Party;
                    dirpartyLocation.IsPrimary          = NoYes::Yes;
                    dirpartyLocation.IsLocationOwner    = NoYes::Yes;
                    dirpartyLocation.IsPostalAddress    = NoYes::No;
                    dirpartyLocation.insert();
                     icount++;
                }
            }
        }
        ttsCommit;
        info(strFmt(" No of Records updated is %1",icount));
    }
}


static void Fcc_UploadCustomerInfoCsv(Args _args)
{
   CommaTextIO                     csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName;
    str                                     accountnum,phone;
     LogisticsLocation   logisticsLocation;
    LogisticsElectronicAddress  electronicAddress;
    DirPartyLocation dirpartyLocation, findDirPartyLocation;
    CustTable                               custTable;
    FileName                    fileName;
   VendTable    vendTable;
    int Ccount;
    inserted =0;
    #File

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

    if (dialog.run())
    {
        csvFile = new CommaTextIo(dfFileName.value(), 'r');
        csvFile.inFieldDelimiter(',');
        readCon = csvFile.read();
        ttsBegin;
        while(csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            if(readCon)
            {
                accountnum = conPeek(readCon,1);
                phone = conPeek(readCon,2);
                custTable = CustTable::find(accountnum);
                select findDirPartyLocation
                    where findDirPartyLocation.Party == custTable.Party
                        && findDirPartyLocation.IsPostalAddress == false;
                if (!findDirPartyLocation && accountnum != "")
                {
                    logisticsLocation.clear();
                    logisticsLocation.initValue();
                    logisticsLocation.IsPostalAddress   = NoYes::No;
                    logisticsLocation.insert();
                    electronicAddress.Description       = "Customer phone Number";
                    electronicAddress.Location          = logisticsLocation.RecId;
                    electronicAddress.Locator           = phone;
                    electronicAddress.Type              = LogisticsElectronicAddressMethodType::Phone;
                    electronicAddress.IsPrimary         = NoYes::Yes;
                    electronicAddress.insert();
                    dirpartyLocation.Location           = logisticsLocation.RecId;
                    dirpartyLocation.Party              = custTable.Party;
                    dirpartyLocation.IsPrimary          = NoYes::Yes;
                    dirpartyLocation.IsLocationOwner    = NoYes::Yes;
                    dirpartyLocation.IsPostalAddress    = NoYes::No;
                    dirpartyLocation.insert();
                     icount++;
                }
            }
        }
        ttsCommit;
        info(strFmt(" No of Records updated is %1",icount));
    }
}

Breakpoint ax 2012

//If Breakpoint is not worked
For your specific issue, you need to do that in class 'SysOperationRPCFrameworkService' to change the method 'runServiceOperation' to,
public static container runServiceOperation(ClassId controllerClassId, container packedController)
{
    return SysOperationServiceController::runServiceOperation([controllerClassId, packedController]);
}

One of the neat features of Dynamics AX 2012 is that it provides a way to compile X++ code to IL which then can be consumed by Microsoft .NET framework and  in return enhances the performance. But this brings some complexity to the issue identification and debugging efforts. In Dynamics AX 2012 client, if you receive an Infolog message which is not very meaningful and the double click on that message does not take you to any code, it is very likely that the code that you are running during your process is compiled into IL using this new feature. One way to get around this issue and to debug the System Operations Framework is to make the following change on runServiceOperation function of SysOperationRPCFrameworkService  class:

public static container runServiceOperation(ClassId controllerClassId, container packedController)
{
    // Use the runas API to transition to a CLR session
    new XppILExecutePermission().assert();
   
    // Disable this piece of Code - AK
    /*return SysDictClass::invokeStaticMethodIL(classStr(SysOperationServiceController),
                                        staticMethodStr(SysOperationServiceController, runServiceOperation),
                                        [controllerClassId, packedController]);*/
 
    // instead make this call - AK
    return SysOperationServiceController::runServiceOperation([controllerClassId, packedController]);
}
 After making this change, you will be able to double click the Infolog message and put a breakpoint and trace the call stack to find the underlying issue that causes the Infolog message.

Ledegr dimension Value Ax 2012

static void LedgerDimValues(Args _args)
 {
     DimensionAttributeLevelValueAllView dimAttrView;
     DimensionAttribute dimAttr;
     ;
     while select DisplayValue from dimAttrView
            where dimAttrView.ValueCombinationRecId == 5637164076 //Ledger Dimension
        join BackingEntityType from dimAttr
            where dimAttr.RecId == dimAttrView.DimensionAttribute           
            && dimAttr.Name == "Employees" // Dimension name
     {
        info(strFmt("%1 - %2",dimAttr.Name, dimAttrView.DisplayValue));
     }
 }

To Reverse Ledger Transaction in ax 2012 X++

// To Reverse Ledger Transaction in ax 2012 X++
TransactionReversal_Ledger
Class
Args As GeneralJournalEntry
TransactionReversalTrans -- Table
 TransactionReversalTrans::createTransaction()
TransactionReversal
http://daynamicsaxaptatutorials.blogspot.com/2011/03/reverse-transaction-in-axapta.html

Cusotmer Invoice Agianst Packingslip in ax 2012

    CustInvoiceTrans                    custInvoiceTrans;
    CustInvoicePackingSlipQuantityMatch custInvoicePackingSlipQuantityMatch;
    CustPackingSlipTrans                custPackingSlipTrans;
    Notes                               packingslipId;
    ;
    while  select PackingSlipId from custPackingSlipTrans Group by PackingSlipId
            exists join custInvoicePackingSlipQuantityMatch
                where custInvoicePackingSlipQuantityMatch.PackingSlipSourceDocumentLine == custPackingSlipTrans.SourceDocumentLine
            exists join custInvoiceTrans
                where custInvoiceTrans.SourceDocumentLine == custInvoicePackingSlipQuantityMatch.InvoiceSourceDocumentLIne &&
                    custInvoiceTrans.SalesId == this.SalesId &&
                    custInvoiceTrans.InvoiceId == this.InvoiceId &&
                    custInvoiceTrans.InvoiceDate == this.InvoiceDate &&
                    custInvoiceTrans.NumberSequenceGroup == this.numberSequenceGroup
    {
        packingslipId += strFmt("%1,",custPackingSlipTrans.PackingSlipId);
    }
    return packingslipId;

Ax Build in AX 2012 Full compile Application

//Ax Build in AX 2012
Delete Log file from following Folder Path:

C:\Users\administrator\Microsoft\Dynamics Ax\Log
C:\Program Files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\Log


Cmd
//C:\Program Files (x86)\Microsoft Dynamics AX\6.0\Client\Bin
C:\Program Files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\bin
To Start AX build
axbuild.exe  xppcompileall  /s=01
     /altbin="C:\Program Files (x86)\Microsoft Dynamics AX\6.0\Client\Bin"
axbuild.exe  xppcompileall  /s=01

layer Objects through X++ in Ax 2012

// layer Objects in Ax 2012
static void San_LayerObjects(Args _args)
{
    #AOT
    treeNode      treeNode;
    xInfo         xInfo = new xInfo();
    UtilElements  utilElements;
    int counter = 0;
    textBuffer textBuffer = new textBuffer();
    dialog dialog = new dialog("Find the Modified objects by Layer Wise");
    dialogfield layerName;
    ;
    layerName = dialog.addField(enumStr(utilEntrylevel),"Choose the layer");
    if(dialog.run())
    {
        treeNode = treenode::findNode(#TablesPath);
        treeNode = treeNode.AOTfirstChild();
        while (treeNode)
        {
           if(SysTreeNode::existsInLayer(treeNode, layerName.value()))
           {
               textBuffer.appendText(treeNode.AOTname());
               textBuffer.appendText('\n');
               counter ++;
           }
          treeNode = treeNode.AOTnextSibling();
        }
    }
    if(strlen(textbuffer.getText()) > 0)
    {
        textBuffer.toFile(@"C:\Users\Gowtham\Desktop\TablemodifiedObjectInLayer.txt");
        info("Total modified objects in usr layer are " + int2str(counter));       
    }
}

update primary Contact Person for customer ax 2012

static void UpdatePrimaryContact(Args _args)
{
    DirPartyTable dirpartyTable;
    LogisticsElectronicAddress  electronicAddress;
    CustTable   custTable;
    DirPartyLocation        dirpartyLocation;
    LogisticsLocation      location;
    ;
    while select custTable
        //where custTable.AccountNum == "30008"
        join dirpartyLocation
         where dirpartyLocation.Party == custTable.Party
        join location where location.RecId == dirpartyLocation.Location
        && location.IsPostalAddress == false
        join electronicAddress
        where electronicAddress.Location == location.RecId
    {
        dirpartyTable.ttsbegin();
        dirpartyTable = DirPartyTable::findRec(custTable.Party,true);
        dirpartyTable.PrimaryContactPhone = electronicAddress.RecId;
        dirpartyTable.update();
        dirpartyTable.ttscommit();
    }
}

Skip Inventory reservation on Sales order lines in D365FO

[ExtensionOf(classStr(InventUpd_Reservation))] final class InventUpd_ReservationCls_SAN_Extension {     void updateNow()     {         if(mo...