Search This Blog

Thursday, April 20, 2017

AX2012 Update AIF Port adresses

When we export from one environmen to another we should update the port addresses to the new environment addresses.
Like moving from config environmen to SIT, QA..etc.


static void krishh_UpdateAddressForPorts(Args _args)
{
    AifChannel  aifchannel;
    str         fromPath, toPath;
    boolean     Update;

    Dialog      dialog;

    DialogField _from;
    DialogField _to;
    dialogField _Update
    ;

    dialog = new Dialog("Move configdata");

    dialog.addInfoImage();
    dialog.addText("This job changes all paths on inbound and outbound ports!!!");

    dialog.addGroup("Paths");
    _from   = dialog.addField(ExtendedTypeStr(String255), "From enviroment" , "Normally from MasterConfigData (CFG)"     );
    _to     = dialog.addField(ExtendedTypeStr(String255), "To enviroment"   , "Valid enviroments are SIT, UAT, QA & PROD");
    dialog.addGroup("Update");
    _Update = dialog.addField(ExtendedTypeStr(NoYesId)  , "Commit change"          , "Update the changes");

    //InitValues
    _from.value("CFG");
    _Update.value(false);

    dialog.run();

    fromPath = _from.value();
    toPath   = _to.value();

    if ((!fromPath || !toPath) || (fromPath == toPath))
    {
        return;
    }

    ttsBegin;
    while select forupdate aifchannel where aifchannel.Direction != AIFChannelDirection::Both
    {
        if (strScan(aifchannel.TransportAddress, fromPath, 1, 255))
        {
            aifchannel.TransportAddress=strReplace(aifchannel.transportAddress, fromPath, toPath);
            info(aifchannel.TransportAddress);

            if (_Update)
             aifchannel.update();
        }
    }
    ttsCommit;
}

AX2012 Flush recids

static void krishh_flushAllRecIds(Args _args)
{
    #AviFiles

    Dictionary              dictionary  =   new Dictionary();
    systemSequence          systemseq   =   new systemSequence();

    SysDictTable            dictTable;
 
    TableId                 tableId,LastTableId;
 
    SysOperationProgress    progress;
    container               fileContainer;

    int                     i;  
   
    setPrefix("Flush all RecIds");
 
    tableId = dictionary.tableNext(0);
    lastTableId = dictionary.tableCnt();
 
    progress = new SysOperationProgress();
    progress.updateInterval(1);
    progress.setAnimation(#AviStopwatch);
    progress.setTotal(LastTableId);

    progress.setText(strfmt("Flushing recIds"));

    ttsbegin;
    while (tableId)
    {
        progress.incCount();

        dictTable = new SysDictTable(tableId);

        setPrefix(dictTable.name());

        Systemseq.suspendRecIds(tableId);
        Systemseq.suspendTransIds(tableId);
        Systemseq.flushValues(tableId);
        Systemseq.removeRecIdSuspension(tableId);
        Systemseq.removeTransIdSuspension(tableId);

        //info(strFmt("Tables RecId Flushed (%1)", dictTable.name()));
     
        tableId = dictionary.tableNext(tableId);
    }

    ttscommit;
}

AX2012 get gropu dimension from financial dimension

static void krish_findGroupDimension(Args _args)
{
    Name                                _dimensionTypeName    = 'COSTCENTER';
    DimensionValue                      _dimensionDisplayName = 'csttest';

    DimensionExt                        retVal;

    OMOperatingUnit                     oMOperatingUnit;
    DimensionAttribute                  dimensionAttribute;
    DimensionAttributeLevelValue        dimensionAttributeLevelValue;
    DimensionAttributeValue             dimensionAttributeValue;
    DimensionAttributeValueSetItemView  dimensionAttributeValueSetItemView;
    ;

    select oMOperatingUnit
        Join dimensionAttribute where dimensionAttribute.Name == _dimensionTypeName
        join dimensionAttributeValue where dimensionAttributeValue.DimensionAttribute == dimensionAttribute.RecId
        Join dimensionAttributeLevelValue where dimensionAttributeLevelValue.DimensionAttributeValue == dimensionAttributeValue.recid
                                             && dimensionAttributeLevelValue.DisplayValue == _dimensionDisplayName;

    retVal = dimensionAttributeValue.GroupDimension;

    if (!retVal)
    {
        select dimensionAttribute where dimensionAttribute.Name == _dimensionTypeName
            Join dimensionAttributeValueSetItemView where dimensionAttributeValueSetItemView.DimensionAttribute == dimensionAttribute.RecId &&
                 dimensionAttributeValueSetItemView.DisplayValue == _dimensionDisplayName
            join dimensionAttributeValue where dimensionAttributeValue.RecId == dimensionAttributeValueSetItemView.DimensionAttributeValue;

        retVal = dimensionAttributeValue.GroupDimension;
    }


    info(strFmt("DimensionAttribute = %1", DimensionAttribute.RecId));
    info(strFmt("DimensionAttributeValueSetItemView = %1", DimensionAttributeValueSetItemView.RecId));
    info(strFmt("%1 : %2 = %3 (%4)", _dimensionTypeName, _dimensionDisplayName, retVal, dimensionAttributeValue.RecId));


}

AX2012 File Reader Test

static void fileAccessTest(Args _args)
{
    CommaIO             commaIO;
    int                     row;
    Container           c;
    FileIOPermission    fileIOPermission;
    int                 recCountNotExist;
    boolean             errorlog;
    Dialog                  dialog;
    DialogField             dialogField;
    FilenameOpen            filename;
    ;

    dialog = new Dialog("Test version of File reader");

    dialogField = dialog.addFieldValue(extendedTypeStr(FilenameOpen), "", "File to access");

    if (dialog.run())
        filename = dialogField.value();
    else
        throw error("No filename");


    fileIOPermission = new FileIOPermission(filename,'r');
    fileIOPermission.assert();

    //BP Deviation documented
    commaIO = new CommaIO(filename, 'r');

    if (commaIO != null)
    {
        if (commaIO.status())
        {
            throw error("@SYS52680");
        }

        commaIO.inRecordDelimiter('\r\n');
        commaIO.inFieldDelimiter(',');
    }
    else
    {
        throw error("@SYS52680");
    }

    c = conNull();

    if (commaIO)
    {
        if (commaIO.status() == IO_Status::OK)
        {
            if (row==0)
            {
                c = commaIO.read();
            }
            info(con2Str(c));
            row++;
            c = commaIO.read();
            info(con2Str(c));
        }
    }
}

AX2012 CompileCIL and Refresh Services using X++



static void krishh_CompileCILRefreshServices(Args _args)
{
    #AviFiles
    #File

    #define.fileName('AxTime.txt')

    TextIo                  file;
    FileIoPermission        permission;
    SysOperationProgress    progress;
    container               fileContainer;

    int                     i;

    Dialog                  dialog;

    DialogField             dlgCompile;
    DialogField             dlgCIL;
    DialogField             dlgIncCIL;
    DialogField             dlgRefreshService;

    int                     timeStarted[2];
    int                     timeAverage[4]; //1:FUllCompileTime,2:FULLCILCompileTime,3:IncrementalCILTime,4:RefreshServicesTime
    int                     timeExpected;

    Filename                filename
    ;

    void getAverageTime()
    {
        filename = WinAPI::getCurrentDirectory() + '\\' + fileName;

        permission = new FileIoPermission(filename, #io_read+#io_write);
        permission.assert();

        if(WinAPI::fileExists(filename))
        {
            file        = new TextIo(filename, #io_read);
            fileContainer   = file.read();
            timeAverage[1]  = str2int(conPeek(fileContainer,1));
            timeAverage[2]  = str2int(conPeek(fileContainer,2));
            timeAverage[3]  = str2int(conPeek(fileContainer,3));
            timeAverage[4]  = str2int(conPeek(fileContainer,4));
            file = null;
        }

        CodeAccessPermission::revertAssert();
    }

    void setAverageTime()
    {
        permission = new FileIoPermission(filename, #io_write);
        permission.assert();

        fileContainer = conNull();
        fileContainer = conIns(fileContainer,1,int2str(timeAverage[1]));
        fileContainer = conIns(fileContainer,2,int2str(timeAverage[2]));
        fileContainer = conIns(fileContainer,3,int2str(timeAverage[3]));
        fileContainer = conIns(fileContainer,4,int2str(timeAverage[4]));

        file = new TextIo(filename, #io_write);
        file.write(fileContainer);
        file.finalize();

        file = null;

        CodeAccessPermission::revertAssert();
        permission = null;
    }

    dialog  = new Dialog("Compile/CIl/Refresh");

    dialog.addInfoImage();
    dialog.addText("Please select actions needed and please be aware that all are time consuming processes");

    dialog.addGroup("Compile application");
    dlgCompile  = dialog.addFieldValue(extendedTypeStr(NoYesId),NoYes::No,"AOT Compile");

    dialog.addGroup("Compile CIL");
    dlgCIL      = dialog.addFieldValue(extendedTypeStr(NoYesId), NoYes::No, "FULL");
    dlgIncCIL   = dialog.addFieldValue(extendedTypeStr(NoYesId), NoYes::No, "Incemental");

    dialog.addGroup("Other");
    dlgRefreshService   = dialog.addFieldValue(extendedTypeStr(NoYesId),NoYes::No,"Refresh Services");

    if (!dialog.run())
        throw error("Operation aborted");

    filename        = #fileName;

    timeAverage[1]  = 3600; // 60:00 min
    timeAverage[2]  = 1800; // 30:00 min
    timeAverage[3]  = 900;  // 15:00 min
    timeAverage[4]  = 300;  // 5:00 min

    getAverageTime();

    timeExpected += dlgCompile.value()          ? timeAverage[1] : 0;
    timeExpected += dlgCIL.value()              ? timeAverage[2] : 0;
    timeExpected += dlgIncCIL.value()           ? timeAverage[3] : 0;
    timeExpected += dlgRefreshService.value()   ? timeAverage[4] : 0;

    progress = new SysOperationProgress();
    progress.updateInterval(0);
    progress.setAnimation(#AviStopwatch);

    progress.setTotal(1 + dlgCompile.value() + (dlgCIL.value() || dlgIncCIL.value()) + dlgRefreshService.value());

    timeStarted[1] = timeNow();

    info(strFmt("Process stared by %1",curUserId()));

    //Compile the application
    startLengthyOperation();
    sleep(3);

    //AOT Compile
    if (dlgCompile.value())
    {
        progress.incCount();
        progress.setText(strfmt("AOT Compile compiling | Start time : %1 ETA : %2",time2str(timeNow(),1,1),time2str(timeAverage[1] + timeNow(),1,1)));

        //Do function
        timeStarted[2] = timeNow();

        SysCompileAll::flushClient();
        SysCompileAll::compile();

        SysCheckList::finished(classnum(SysCheckListItem_Compile));
        SysCheckList::finished(classnum(SysCheckListItem_CompileUpgrade));
        SysCheckList::finished(className2Id(classStr(SysCheckListItem_CompileServ)));
        SysCheckList::finished(classnum(SysCheckListItem_SysUpdateCodeCompilInit));

        timeAverage[1] = ((timeNow()-timeStarted[2]) + timeAverage[1])/2;
        info(strFmt("AOT Compile toke : %1*",time2str(timeAverage[1],1,1)));
    }

    //Incremntal CIL
    if (dlgIncCIL.value())
    {
        progress.incCount();
        progress.setText(strfmt("Incremental CIL Compiling | Start time : %1 ETA : %2",time2str(timeNow(),1,1),time2str(timeAverage[3] + timeNow(),1,1)));

        //Do function
        timeStarted[2] = timeNow();
        SysCompileIL::generateIncrementalIL();

        timeAverage[3] = ((timeNow()-timeStarted[2]) + timeAverage[3])/2;
        info(strFmt("Increment CIL toke : %1*",time2str(timeAverage[3],1,1)));
    }
    //Full CIL
    else if (dlgCIL.value())
    {
        progress.incCount();
        progress.setText(strfmt("FULL CIL Compiling | Start time : %1 ETA : %2",time2str(timeNow(),1,1),time2str(timeAverage[2] + timeNow(),1,1)));

        //Do function
        timeStarted[2] = timeNow();
        SysCompileIL::generateIL();
        timeAverage[2] = ((timeNow()-timeStarted[2]) + timeAverage[2])/2;
        info(strFmt("FULL CIL toke : %1*",time2str(timeAverage[2],1,1)));
    }

    // Refresh services
    if (dlgRefreshService.value())
    {
        progress.setText(strfmt("Refresh Services | Start time : %1 ETA : %2",time2str(timeNow(),1,1),time2str(timeAverage[4] + timeNow(),1,1)));
        progress.incCount();

        timeStarted[2] = timeNow();

        AifServiceGenerationManager::registerServices();

        timeAverage[4] = ((timeNow()-timeStarted[2]) + timeAverage[4])/2;
        info(strFmt("Refresh Services toke : %1*",time2str(timeAverage[4],1,1)));
    }

    setAverageTime();

    endLengthyOperation();

    //Flush all
    sysFlushAOD::main(_args);
    sysFlushData::main(_args);
    sysFlushDictionary::main(_args);
    info(strFmt("*Averagetime"));
    info(strFmt("Total time spendt : %1",time2str(timeNow()-timeStarted[1],1,1)));
}

Wednesday, December 7, 2016

Hide Query values in the dialog with select button Enabled


Scneario: we want to hide the query values that was selected by the user in query range select button.

I created the parmmethod as below in the class Dialog,RunBaseDialogModify


public boolean hideQueryValuesInDialog(boolean _showValues = showValues)
{
;
    showValues = _showValues;

    return showValues;
}

Added the highlighted code as below in the following method of class RunBaseDialogModify


client public static RunBaseDialogModify newRunbaseOnClient(
    RunBase         runBase,
    DialogRunbase   dialog)
{
    // <GEERU>
    RunBaseDialogModify runBaseDialogModify = RunBaseDialogModify::construct(runBase.runBaseDialogModifyType_RU());
    // </GEERU>
    ;
    runBaseDialogModify.parmRunbase(runBase);
    runBaseDialogModify.parmDialog(dialog);

//Addded by krishna
   runBaseDialogModify.rsaShowQueryValuesInDialog(dialog.rsaShowQueryValuesInDialog());
//Addded by krishna

    return runBaseDialogModify;
}

Server public static RunBaseDialogModify newRunbaseOnServer(
    RunBase         runBase,
    DialogRunbase   dialog)
{
    // <GEERU>
    RunBaseDialogModify runBaseDialogModify = RunBaseDialogModify::construct(runBase.runBaseDialogModifyType_RU());
    // </GEERU>
    ;
    runBaseDialogModify.parmRunbase(runBase);
    runBaseDialogModify.parmDialog(dialog);
//Addded by krishna
    runBaseDialogModify.rsaShowQueryValuesInDialog(dialog.rsaShowQueryValuesInDialog());
//Addded by krishna
    return runBaseDialogModify;
}

// <GEERU>
protected boolean addField(SysDictField _dictField, Set _fieldNameSet, LabelType _labelType, Range _range)
// </GEERU>
{
    boolean         ret = false;
    Map             map;
    DialogField     dialogField;
    TableId         tableId;

    if (_dictField)
    {
        tableId = _dictField.tableid();
        if (_fieldNameSet.in(_dictField.name()))
        {
            if (this.existField(_dictField))
            {
                this.addRange(this.getFieldName(_dictField), _range);
        }
    }
    else
    {
        ret = true;

            if (!dialogQueryFieldsMap.exists(tableId))
        {
                dialogQueryFieldsMap.insert(tableId, new Map(Types::String, Types::String));
        }

            map         = dialogQueryFieldsMap.lookup(tableId);
        dialogField = dialog.addField(extendedTypeStr(RunBaseRange), _labelType);

        dialogField.value(_range);
        dialogField.allowEdit(false);

//Addded by krishna
//  dialogField.visible(true);
        if(!showValues)
        {
            dialogField.visible(false);
        }
        else
        {
            dialogField.visible(true);
        }
//Addded by krishna

            map.insert(_dictField.name(), dialogField.fieldname());

            _fieldNameSet.add(_dictField.name());
        }
    }
    return ret;
}


In your runbasebatch class override the method as below
public DialogRunbase dialogInit(DialogRunbase dialog, boolean forceOnClient= false)
{
    DialogRunbase ret;
//Addded by krishna
    if (! dialog)
    {
        if (xGlobal::clientKind() != ClientType::Server || forceOnClient)
            dialog = DialogRunbase::newOnClient(this.caption(),this);
        else
            dialog = DialogRunbase::newOnServer(this.caption(),this);
    }
    dialog.rsaShowQueryValuesInDialog(false);
//Addded by krishna
    ret = super(dialog, forceOnClient);

    return ret;
}


The above changes will hide your query range selected values in the dialog with showing select button.

Monday, July 13, 2015

Ax2012 Useful functions 2

Show viewhistory on form datasources if you have ValidaTimeState Enabled DateTime enabled on the tables of that form. 
create this method in Global class so you can call whereever you want in form button click as below.

void clicked()

{
    buttonHistoryClick(element, this);
    Super();
}

static public void buttonHistoryClick(FormRun _formRun, FormButtonControl _fbc)
{
    void changeDataSources(ValidTimeStateAutoQuery _from, ValidTimeStateAutoQuery _to, boolean _allowDelete)
    {
        Counter         dataSourceNo;
        FormDataSource  formDataSource;

        for (dataSourceNo=1;_formRun.dataSourceCount()>=dataSourceNo;dataSourceNo++)
        {
            formDataSource = _formRun.dataSource(dataSourceNo) as FormDataSource;
            if (formDataSource.validTimeStateAutoQuery() == _from && new DictTable(formDataSource.table()).isValidTimeStateTable())
            {
                formDataSource.validTimeStateAutoQuery(_to);
                switch (_to)
                {
                    case ValidTimeStateAutoQuery::AsOfDate:
                        formDataSource.validTimeStateAutoQuery(ValidTimeStateAutoQuery::AsOfDate);
                        formDataSource.query().resetValidTimeStateQueryType();
                        formDataSource.allowDelete(_allowDelete);
                        break;
                    case ValidTimeStateAutoQuery::DateRange:
                        formDataSource.validTimeStateAutoQuery(ValidTimeStateAutoQuery::DateRange);
                        formDataSource.query().validTimeStateDateTimeRange(DateTimeUtil::minValue(), DateTimeUtil::maxValue());
                        formDataSource.allowDelete(_allowDelete);
                        break;
                }
                formDataSource.executeQuery();
            }
        }
    }

    if (_fbc.labelText() == "@SYS110266")
    {
        changeDataSources(ValidTimeStateAutoQuery::AsOfDate, ValidTimeStateAutoQuery::DateRange, false);
        _fbc.text("Stop viewing History");
        _fbc.normalImage("10006");
    }
    else
    {
        changeDataSources(ValidTimeStateAutoQuery::DateRange, ValidTimeStateAutoQuery::AsOfDate, true);
        _fbc.Text("@SYS110266");
        _fbc.normalImage("10007");
    }

}
// this method is used to create filenameTimeStamp.

static FileName createFilenameTimeStamp()
{
    FileName    ret;
    Microsoft.Dynamics.IntegrationFramework.Adapter.FileSystem       fileSystem;
    #Aif

    fileSystem      = AifUtil::getClrObject(#FileSystemProgId);

    ret = fileSystem.GetCurrentTimestamp();

    return ret;
}


// This method is used to split the string, and returns the conatiner with the position defined in the parameter
public static str rsaStrSplit(str _splitString,str _splitchar,int _pos)
{
    List strlist=new List(Types::String);
    ListIterator    iterator;
    container       packedList;
    ;
    strlist=strSplit(_splitString,_splitchar);
    iterator = new ListIterator(strlist);
    while(iterator.more())
    {
        packedList += iterator.value();
        iterator.next();
    }
    return conPeek(packedList,_pos);

}

public static str encrypt(str _input, str _salt = '')
{
    System.Security.Cryptography.SHA512Managed  sha512managed = new System.Security.Cryptography.SHA512Managed();
    System.Text.Encoding                        encoding = System.Text.Encoding::get_UTF8();

    System.Byte[]                               inputBytes;
    System.Byte[]                               resultBytes;

    int                                         i;
    str                                         returnString;
    ;

    new InteropPermission(InteropKind::ClrInterop).assert();

    inputBytes = encoding.GetBytes(strLwr(_salt) + _input); // Convert lower case salt + input into byte array

    // The input is hashed 1024 times for attack resiliency
    for (i = 0; i < 1024; i++)
    {
        resultBytes = resultBytes ? resultBytes : inputBytes; // First loop uses input for hashing
        resultBytes = sha512managed.ComputeHash(resultBytes);
    }

    returnString = System.Convert::ToBase64String(resultBytes);

    CodeAccessPermission::revertAssert();

    return returnString;
}

private static Map fileGetList(FilePath            _filePathArchive)

{
 
    Map                 mapFiles;

    InteropPermission   interopPermission = new InteropPermission(InteropKind::ClrInterop);
    Set                 interopPermissionSet = new Set(Types::Class);
    System.Array        arrayFiles;

    int                 i;
    ;

    // Granting file permission rights
    interopPermissionSet.add(interopPermission);
    CodeAccessPermission::assertMultiple(interopPermissionSet);

    mapFiles = new Map(Types::String, Types::String); // Key = return file | Value = archive path

        if (!System.IO.Directory::Exists(_filePathArchive))
        {
             throw  error("Path doesnt exist");
        }

        arrayFiles = System.IO.Directory::GetFiles(_filePathArchive);

        // CLRInterop::getAnyTypeForObject method is used to handle difference in AX and System types (e.g. System.Int32 != int)

        for (i = 0; i < CLRInterop::getAnyTypeForObject(arrayFiles.get_Length()); i++)
        {
       mapFiles.insert(CLRInterop::getAnyTypeForObject(arrayFiles.GetValue(i)), _filePathArchive);
        }
    }

    // Reverting file permission rights
    CodeAccessPermission::revertAssert();

    return mapFiles;
}


/// <summary>
///  Gets the SenderID from AIF xml .
/// </summary>
/// <param name="messagePartsXml">
/// An <c>AifXml</c> value.
/// </param>
/// <returns>
/// An instance of the <c>str document Namespace</c> class.
/// </returns>
public static str getSenderIDValue(AifXml messagePartsXml)
{
     XmlTextReader               xmlReader;
    str value,currentElement,pureElement;

;
#Aif
    xmlReader = XmlTextReader::newXml(messagePartsXml);
    while (xmlReader.Read())
    {
        switch (xmlReader.nodeType())
        {
             case XmlNodeType::Element:
                  currentElement = xmlReader.name();
                 break;
             case XmlNodeType::Text:
                  pureElement = subStr(currentElement,strFind(currentElement,':',1,256)+1,256);
                    switch (pureElement)
                    {
                       case "SenderId":
                        {
                            value=xmlReader.value();
                            return value;
                        }
                        break;
                    }
              break;
        }
    }

    return value;
}


AX2012 Replacing Company element value in AIF using .net dll and QueryService

Scenario:
In AIF we have some data coming from externalSystem, which externalSystem doesnt have anyinformation to which company it should load, as ExternalSystem knows the information about coRegNum as we have to find the right company in AX by using coRegNum.
Solution:
so I build a .net component where we use the dll in transformation to replace the companyelement in the header to pass the file into right company.
I am using QueryService which I querying the companyInfoTable with the range coRegNum and getting the right Company and replacing in the sourceXML in transfromation in headersection.

sample xml section below.

<ns0:Envelope xmlns:ns0="http://schemas.microsoft.com/dynamics/2011/01/documents/Message">
<ns0:Header>
<ns0:MessageId>354bcae9-45a5-411e-953f-e2920a6c0229</ns0:MessageId>
<ns0:Company>123456</ns0:Company>
<ns0:Action>http://schemas.microsoft.com/dynamics/2008/01/services/GeneralJournalService/create</ns0:Action>
</ns0:Header>
<ns0:Body>
<ns0:MessageParts>
<ns0:LedgerGeneralJournal xmlns:ns0="http://schemas.microsoft.com/dynamics/2008/01/documents/LedgerGeneralJournal" xmlns:st="http://schemas.microsoft.com/dynamics/2008/01/sharedtypes">

Before writing this class add serviceReference QueryService from AX standardservice into your solution that will create app.config as below

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <netTcpBinding>
                <binding name="QueryServiceEndpoint" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Streamed" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
            </netTcpBinding>
        </bindings>
        <client>
            <endpoint address="net.tcp://KrishhDax:8201/DynamicsAx/Services/QueryService"
                binding="netTcpBinding" bindingConfiguration="QueryServiceEndpoint"
                contract="AXQueryService.IQueryService" name="QueryServiceEndpoint">
                <identity>
                    <servicePrincipalName value="host/KrishhDax.adep01.nordic.rsa-ins.com" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>

</configuration>

Create a tranform class which extends from Itransform.
I am using xml.linq to read the element value in the class, so I referenced System.Xml.Linq;

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Dynamics.IntegrationFramework.Transform;
using System.Xml;
using System.Xml.Linq;
using KrishhIbanToCompanyTrans.AXQueryService;
using System.ServiceModel;
using System.Data;
using System.Net;


namespace KrishhIbanToCompanyTrans
{
    public class IBANToCompanyTrans : ITransform
    {
        public void Transform(System.IO.Stream input, System.IO.Stream output, string config)
        {
            XDocument inputXml = XDocument.Load(input);

            string accStr = inputXml.Root.Descendants().Where(e => e.Name.LocalName == "Company").First().Value;
           
            string[] serviceParams = config.Split(';');

            if (serviceParams.Count() != 1 && serviceParams.Count() != 4)
                throw new ArgumentException("Invalid configuration passed. Expecting single endpoint address or endpoint address with username, password and domain, separated by ;");

            NetTcpBinding binding1 = new NetTcpBinding();
            EndpointAddress epa = new EndpointAddress(serviceParams[0]);

            binding1.Name = "QueryServiceEndpoint";
            binding1.TransactionProtocol = TransactionProtocol.OleTransactions;
            binding1.TransferMode = TransferMode.Streamed;
            binding1.Security.Mode = SecurityMode.Transport;
            binding1.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding1.Security.Transport.ClientCredentialType =  TcpClientCredentialType.Windows;
            binding1.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
            binding1.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
            binding1.ReliableSession.Enabled = false;

            QueryServiceClient serviceClient = new QueryServiceClient(binding1, epa);

            if (serviceParams.Count() == 4)
            {
                serviceClient.ClientCredentials.Windows.ClientCredential.UserName = serviceParams[1];
                serviceClient.ClientCredentials.Windows.ClientCredential.Password = serviceParams[2];
                serviceClient.ClientCredentials.Windows.ClientCredential.Domain = serviceParams[3];
            }

            QueryMetadata query = new QueryMetadata();
            query.DataSources = new QueryDataSourceMetadata[1];
            query.Name = "CompanyInfo";
            QueryDataSourceMetadata queryDS = new QueryDataSourceMetadata();
            queryDS.Name = "CompanyInfo";
            queryDS.Table = "CompanyInfo";
            queryDS.Enabled = true;
            query.DataSources[0] = queryDS;
            queryDS.DynamicFieldList = false;
            queryDS.Fields = new QueryDataFieldMetadata[2];
            QueryDataFieldMetadata fieldId = new QueryDataFieldMetadata();
            fieldId.FieldName = "DataArea";
            fieldId.SelectionField = SelectionField.Database;
            queryDS.Fields[0] = fieldId;
            QueryDataFieldMetadata fieldName = new QueryDataFieldMetadata();
            fieldName.FieldName = "CoRegNum";
            fieldName.SelectionField = SelectionField.Database;
            queryDS.Fields[1] = fieldName;
            queryDS.Ranges = new QueryDataRangeMetadata[] { new QueryDataRangeMetadata() { TableName = "CompanyInfo", FieldName = "CoRegNum", Value = accStr, Enabled = true } };

            Paging paging = new ValueBasedPaging() { RecordLimit = 25 };



            DataSet dataset = serviceClient.ExecuteQuery(query, ref paging);
            Console.Write(dataset.GetXml());

            if (dataset != null)
            {
                if (dataset.Tables.Count > 2)
                {
                    if (dataset.Tables[3].Rows.Count > 0)
                    {
                        DataRow dr = dataset.Tables[3].Rows[0];

                        var element = inputXml.Root.Descendants().Where(e => e.Name.LocalName == "Company").First();
                        if (element != null)
                            element.Value = dr["DataArea"].ToString();
                    }
                }
            }
            inputXml.Save(output);

        }

This method is used to test the above code.
/*
        static void Main(string[] args)
        {
            IBANToCompanyTrans transformClass = new IBANToCompanyTrans();

            FileStream input, output;

            // Create the two streams to pass into the assembly. You will need to change these
            // to your file locations.
            input = new FileStream("C:\\Temp\\922\\922.xml", FileMode.Open);
            output = new FileStream("C:\\Temp\\922\\922_c.xml", FileMode.OpenOrCreate);

            string paramString = "net.tcp://hssdas115:8201/DynamicsAx/Services/QueryService";
            // Passes in the customers CSV file and gets back an XML file.
            transformClass.Transform(input, output, paramString);

            // Displays the XML to the console.
            //            StreamReader sreader = new StreamReader(new FileStream("c:\\temp\\testtmpn.xml", FileMode.Open));
            //            Console.Write(sreader.ReadToEnd());
            //            Console.ReadLine();

        } */
    }
}

After building this component, go to the inboundPort and click transformation button and go to transformations and create the .net dll  transformation and provide the dll and select the class in the dropdown.
in Config file provide the app.config file for this transformation.



Thursday, June 25, 2015

AIF Outbound Read ParentAXBC while processingRecord AX2012

Scenario:

In AIF outbound document service Exporting Invoices information,
In this document we have the customization as one table which contains the printTemplates where it stores the printTemplate information like,address,bankdetails,etc.Using this printTemplate number the external system will define which printing report they have to use.
The Requirement is  The Address containes all the street,country,etc. these information we have to generate from translation tables based on the language that defined in the custinvoiceJournal.

so the datasource lookes like this.
custinvoicejour->custinvoicetrans,custTable,etc, as well printTemplateTable also outerjoins to the custinvoicejour.


I didnt find the way where I can get the parentaxbc object while processing the current record.

Solution:
I thought to get parentAXBC object always for the outbound for the current AXBC record.

See the Modification that I have build.


1. AXDBase class
             added the class variable as AXInternalBase parentAXBC;

2. AxdBaseRead class
   Open method serializeRecord add the folllowing line of code above        AXbase.ProccesingRecord(common) line in that method
axdBase.parmParentAxBC(_parentAxBC);

3. AxdBaseGenerateXSD class
   Open this class edit method addDocumentProperties and add one more case for classType as below, so that while serialization class object wont fail.
// added by krishna for to check for class type also. begins
case Types::Class:
if (typename == '')
{
typename = #xsdStringType;
typeNameSpace = #xsdNameSpace ;
}
break;

// added by krishna for to check for class type also.

Now framework was updated to get parentAXBC allways while outbound. now you can write logic whatever you want to use it.


Open AXDSalesInvoice class and update the processing record with the business logic for you to handle.
It this method i am verifying the current record in printTemplate then get the parent and get the languageId from that do my logic.

public void processingRecord(Common common)
{
 PrintTemplate PrintTemplate;
 AxCustInvoiceJour axCustInvoiceJour;
 if(common.TableId == tableNum(PrintTemplate))
 {
 axCustInvoiceJour=this.parmParentAxBC();
 PrintTemplate=common;
 PrintTemplate.CompanyCountryName=LogisticsAddressCountryRegionTranslation::find(LogisticsPostalAddress::findRecId(PrintTemplate.Address).CountryRegionId,axCustInvoiceJour.parmLanguageId()).ShortName;
 super(PrintTemplate);
 }
 else
 {
 super(common);
 }

}


If you guys likes this post and useful please like and share it.

 

Editable Multi select lookup in Grid field AX2012

Scneario: Multiple select Editable lookup  in grid

I created an extension of class from SysLookupMultiselectGrid

class KrisSysLookupMultiSelectGrid extends SysLookupMultiSelectGrid
{
#Characters
}

public void setSelected()
{
 dictfield dictField;
 Common currentDSRecord;
 FormDataSource formdatasource;
 callingControlId.text(SysOperationHelper::convertMultiSelectedValueString       (selectedId));
 formdatasource = callingControlId.dataSourceObject();
 if(formdatasource && callingControlStr.dataField())
 {
  dictfield = new dictfield(formdatasource.table(),callingControlStr.dataField());
   currentDSRecord = formdatasource.cursor();
   currentDSRecord.(dictfield.id()) = currentDSRecord.(dictfield.id()) +     SysOperationHelper::convertMultiSelectedValueString(selectedStr);
  callingControlStr.update();
 }
 else
 {
 callingControlStr.text(SysOperationHelper::convertMultiSelectedValueString(selectedStr));
 }
}

public static KrisSysLookupMultiSelectGrid construct(FormControl _ctrlId,
FormControl _ctrlStr)
{
KrisSysLookupMultiSelectGrid lookupMS;
lookupMS = new KrisSysLookupMultiSelectGrid ();
lookupMS.parmCallingControlId(_ctrlId);
lookupMS.parmCallingControlStr(_ctrlStr);
return lookupMS;

}


On form declare this class on the form level as below

KrisSysLookupMultiSelectGrid multiSelectGrid;

On form Init method initiliaze this object as below
multiSelectGrid = KrisSysLookupMultiSelectGrid ::construct(GridResults_Value,GridResults_Value);

On grid string edit field lookup method you can use this object as below

Query query = new Query();

QueryBuildDataSource queryBuildDataSource;

queryBuildDataSource = query.addDataSource(tableNum(DimensionAttribute));
queryBuildDataSource.addRange(fieldNum(DimensionAttribute,Type)).value(queryValue(DimensionAttributeType::CustomList));
queryBuildDataSource.addRange(fieldNum(DimensionAttribute,Type)).value(queryValue(DimensionAttributeType::MainAccount));
queryBuildDataSource.addRange(fieldNum(DimensionAttribute,Type)).value(queryValue(DimensionAttributeType::ExistingList));
queryBuildDataSource.addSelectionField(fieldNum(DimensionAttribute,Name));
multiSelectGrid.parmQuery(query);

multiSelectGrid.run();

you can see in form as below screenshot


Its editable and multi select lookup.