Pages

Monday, 19 October 2015

X++ code for get File Name

Sometimes we need to get file name from path location. In that there's a lot of file format. So we could in find exact file. So that we find or get filename with pattern . Here you go i gave sample code for.....

Sample Code:

// dir-----> File directory path
// filePattern -----> .xml, .doc,.....
private List getFileLocation(FilePath dir, str filePattern)
{
    FilePath sFilePath;
    FileName fileName;

    List fileList = new List(Types::String);
    System.IO.DirectoryInfo di;
    System.IO.FileInfo[] fis;
    System.IO.FileInfo fi;

    int i;
    int l;
    ;

    sFilePath = dir;
    //BP Deviation Documented
    di = new System.IO.DirectoryInfo(sFilePath); // get file path directory
    fis = di.GetFiles(filePattern);             // filter the  file based on given file pattern
    l = fis.get_Length();

    for (i = 0; i < l; i++)
    {
        fi = fis.GetValue(i);
        fileName = fi.get_FullName();
        fileList.addEnd(fileName);
    }
    return fileList;
}


RestFul API Services in dynamics AX2009 & AX2012

When we integrating Dynamics AX with other systems, we might need to call REST services in Dynamics AX to Pull data in AX (or) Push data out of AX to other systems.
REST services are the easiest and very useful way to provide the interface between two systems. 
Here you go the job written below is the example of how we can call REST service from within AX.

static void AccessingAPI(Args _args)
{
    str                                                   url;
    str                                                   postData;
    str                                                   returnValue;
    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse    response;
    System.Byte[]                                byteArray;
    System.IO.Stream                    dataStream;
    System.IO.StreamReader          streamReader;
    System.Net.ServicePoint         servicePoint;
    System.Net.ServicePointManager  servicePointManager;
    CLRObject                       clrObj;
    System.Text.Encoding            utf8;

    ;

    postData = strfmt('First_Name=%1&Id=%2', "DaxCustomer", "DAX-00001");

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

    url ="http://yoururl.com/api/services/add?app_id=''&app_key=''&token=''&secret=''&format=xml";

    clrObj = System.Net.WebRequest::Create(url);
    System.Net.ServicePointManager::set_Expect100Continue(false); 

    request = clrObj;
    request.set_Method("POST");
    utf8 = System.Text.Encoding::get_UTF8();
    byteArray = utf8.GetBytes(postData);
    request.set_ContentType("application/x-www-form-urlencoded");
    request.set_ContentLength(byteArray.get_Length());

    dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.get_Length());
    dataStream.Close();

    try
    {
        response = request.GetResponse();
    }
    catch (Exception::CLRError)
    {
    postdata = "";
    }

    dataStream = response.GetResponseStream();
    streamReader = new System.IO.StreamReader(dataStream);
    returnValue = streamReader.ReadToEnd();

    info(returnvalue);

    streamReader.Close();
    dataStream.Close();
    response.Close(); 


}

Sunday, 18 October 2015

Create a New Vendor through X++ code in Ax2009

Sometimes we need to new vendor's  into the system table VendTable, DirPartyTable,Address Tables. So that we need to simplify the processes of vendor creation....

Sample Code:


static void CreateVendors(Args _args)
{
    VendTable       vendTable;
    DirPartyTable   dirPartyTable;
    Address         addressTable;
    ;
    ttsbegin;
    vendTable.Name                = 'DAX Test DAX123';
    vendTable.AccountNum    = NumberSeq::newGetNum(NumberSequenceReference::find(typeid2extendedTypeId(typeid(VendAccount)))).num();
    vendTable.PartyId             = NumberSeq::newGetNum(NumberSequenceReference::find(typeid2extendedTypeId(typeid(DirPartyId)))).num();
    vendTable.VendGroup     = '10000';
 
    vendTable.Currency         = 'USD';
    vendTable.PartyType       = DirPartyType::Organization;
    vendTable.LanguageId    = 'en';
    if(!vendTable.validateWrite())
    {
        throw error('Check Your Mendatory Fields');
    }
   
    vendTable.insert();
   
   
    dirPartyTable.PartyId = vendTable.PartyId;
    dirPartyTable.insert();
   
    select firstonly dirPartyTable
        where dirPartyTable.PartyId == vendTable.PartyId;
   
    if(dirPartyTable)
    {
        addressTable.AddrRecId = dirPartyTable.RecId;
        addressTable.AddrTableId = dirPartyTable.TableId;
        addressTable.type = AddressType::Home;
        addressTable.IsPrimary = NoYes::Yes;
        addressTable.insert();
    }
   
    ttscommit;
 

}


Number Sequence Issue

Sometimes we need to get number sequence through code that time we get following errors
like    "System does not support setup 'continuous' of number sequence AP_001.
Number selection is canceled."

Solutions:

Put the Number Sequence code between the ttsbegin and ttscommit.

ttsbegin;

// Your code
vendTable.AccountNum    =   NumberSeq::newGetNum(NumberSequenceReference::find(typeid2extendedTypeId(typeid(VendAccount)))).num();

ttscommit;

info(strfmt('%1',vendTable.AccountNum));

Friday, 16 October 2015

ClrObject static method invocation error

    When we deleting file by using WinAPIServer class we get following issue ClrObject static method invocation error.

Solution:

             Deleting file does not exist in the particular location. So the error occured..
                         i) We need to check file exist or not by using System.IO.File::Exists("FileName") method

Sample Code:

static void Delfile(Args _args)
{
    FilePath            filePath;
    FileIOPermission    fileIOPermission;
    ;

    filePath = @'C:\customer.xml';
    fileIOPermission = new FileIOPermission(filePath, 'w');
    CodeAccessPermission::revertAssert();
 

    //Here we adding File Exists method
    if(System.IO.File::Exists(filePath)) 
    {
        WinAPIServer::deleteFile(filePath);
    }
}
                     

Friday, 14 August 2015

CIL Error :Duplicate type with name ‘Dynamics.Ax.application.’ in assembly ‘Dynamics.Ax.application.tablename, version=6.0.9, culture… In Ax2012

Solving  this issue to perform the follow the instructions:
1) Full  Compile  Ax
2) Stop AOS Services.
3) Go to the Server Path: C:\Program Files\Microsoft Dynamics AX\60\Server\InstanceName\bin\XppIL \ delete all DLL and netModule files.
4) Truncate the records in the SysXppAssembly table in the Model database. 
     syntax: Truncate table SysXppAssembly .
5) Start the AOS.
6) Perform Full CIL Compilation.

Monday, 8 June 2015

Reading AIF outbound xml with multiple child nodes via jobs in dynamics ax 2009

static void XMLReadList(Args _args)
{
    XMLDocument     doc;
    XMLNode         rootNode,NodeAccount;
    XMLNodeList     xmlRootNodeList;
    XmlNodeList     xmlRecordList;
    XMLParseError   xmlError;
    XmlElement      xmlBodyField,xmlMessageField,xmlbbbField,xmlCustTableField;
    XmlNodeList     xmlBodyFieldList,xmlMessageBodyChildFieldList,xmlbbbaxdcustomerChildFieldList,xmlCustTableFieldList,xmlDirTableFieldList,xmlAddFieldList,xmlDirFieldList;
    XmlElement      xmlRecord,xmlMessageChildRecord,xmlbbbaxdcustomerChildRecord,xmlCustTableRecord,xmlDirTableRecord,xmlAddRecord;
    str             custAccount,cellularPhone,phone,email,street,state,city,zipcode,fname,lname,bbb_birthday,bbb_spousename,birthdate,anniversaryDate;
    int             i,j,k,l,m,n,p,fieldId;
    CustTable       custTable;

    ;
    // Read the XML Document
    doc = new XMLDocument();
    //doc.async(FALSE);
    doc.load(@"E:\\demo.xml");
    // Verify Document Structure
    xmlError  = doc.parseError();
    if(xmlError && xmlError.errorCode() != 0)
    {
        throw error(strFmt("Error: %1",xmlError.reason()));
    }
    // Parsing document contents
    rootNode = doc.documentElement();
    xmlRootNodeList = doc.documentElement().selectNodes("//Envelope");
    // Get all Customer information from XML document tags (and remove it)
    NodeAccount = doc.getNamedElement('Envelope');
    xmlRootNodeList = NodeAccount.childNodes();
    if(doc.getElementsByTagName('CustTable').length() > 0)
    {
        for(i=0;i<xmlRootNodeList.length();i++)
        {
            xmlRecord = xmlRootNodeList.item(i);
            if(i==1)
            {
                xmlBodyFieldList = xmlRecord.childNodes();

                for (j=0; j<xmlBodyFieldList.length(); j++)
                {
                    xmlBodyField = xmlBodyFieldList.item(j);
                    xmlMessageBodyChildFieldList = xmlBodyField.childNodes();

                    for(k=0;k<xmlMessageBodyChildFieldList.length();k++)
                    {
                        xmlMessageChildRecord = xmlMessageBodyChildFieldList.item(k);
                        xmlbbbaxdcustomerChildFieldList = xmlMessageChildRecord.childNodes();
                        if(xmlbbbaxdcustomerChildFieldList.length() > 0)
                        {
                            for(j=0;j<xmlbbbaxdcustomerChildFieldList.length();j++)
                            {
                                xmlbbbaxdcustomerChildRecord = xmlbbbaxdcustomerChildFieldList.item(j);
                                xmlCustTableFieldList = xmlbbbaxdcustomerChildRecord.childNodes();
                                custAccount      = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('AccountNum').text();


                                if(xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('CellularPhone'))
                                {
                                    cellularPhone    = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('CellularPhone').text();
                                }
                                if(xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('Email'))
                                {
                                    email            = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('Email').text();
                                }
                                if(xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('Phone'))
                                {
                                    phone = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('Phone').text();
                                }
                                xmlDirTableFieldList = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('DirPartyTable').childNodes();
                                fname ='';
                                lname ='';
                                for(m=0;m<xmlDirTableFieldList.length();m++)
                                {
                                    if( xmlDirTableFieldList.item(m).baseName() == 'FirstName')
                                    {
                                        fname = xmlDirTableFieldList.item(m).text();
                                    }
                                    if( xmlDirTableFieldList.item(m).baseName() == 'LastName')
                                    {
                                        lname = xmlDirTableFieldList.item(m).text();
                                    }
                                    xmlDirFieldList = xmlDirTableFieldList.item(m).childNodes();

                                    birthday = '0000-00-00 00:00:00';
                                    spousename = '';
                                    birthdate = '0000-00-00 00:00:00';
                                    AnniversaryDate = '0000-00-00 00:00:00';
                                    for(p=0;p<xmlDirFieldList.length();p++)
                                    {

                                         if(xmlDirFieldList.item(p).baseName()=='Spouse_Birthday')
                                         {
                                            birthday = xmlDirFieldList.item(p).text();
                                         }

                                         if(xmlDirFieldList.item(p).baseName()=='Spouse_Name')
                                         {
                                            spousename = xmlDirFieldList.item(p).text();
                                         }

                                         if(xmlDirFieldList.item(p).baseName()=='BirthDate')
                                         {
                                            birthdate = xmlDirFieldList.item(p).text();
                                         }

                                         if(xmlDirFieldList.item(p).baseName()=='AnniversaryDate')
                                         {
                                            anniversaryDate = xmlDirFieldList.item(p).text();
                                         }
                                    }

                                }
                                xmlAddFieldList = xmlbbbaxdcustomerChildFieldList.item(j).getNamedElement('Address_1').childNodes();
                                city    ='';
                                state   ='';
                                street  ='';
                                zipcode ='';
                                for(n=0;n<xmlAddFieldList.length();n++)
                                {
                                    if(xmlAddFieldList.item(n).baseName() == 'City')
                                    {
                                        city = xmlAddFieldList.item(n).text();
                                    }
                                    if(xmlAddFieldList.item(n).baseName() == 'State')
                                    {
                                        state = xmlAddFieldList.item(n).text();
                                    }
                                    if(xmlAddFieldList.item(n).baseName() == 'Street')
                                    {
                                        street = xmlAddFieldList.item(n).text();
                                    }
                                    if(xmlAddFieldList.item(n).baseName() == 'ZipCode')
                                    {
                                        zipcode = xmlAddFieldList.item(n).text();
                                    }
                                }
                            }
                        }
                        else
                        {
                            info("Xml File is Empty");
                        }
                    }
                }
            }
        }
     }
     else
     {
        info("Xml File is Empty");
     }
}