Pages

Monday, 19 October 2015

The number of arguments provided is different from the number of arguments accepted by the method Issue

Creating Excel File Through X++ Code in dynamics ax 2009 or ax 2012

In Microsoft Dynamics Ax developers need to export the table data's from Ax Table to Excel...So here i have sample code for how to write data into excel in Dynamics ax 2009.


Sample Code:

static void AxTableToExcel(Args _args)
{
    CustTable custTable;

    int row;

    SysExcelApplication excelApp;

    SysExcelWorkbooks workbooks;

    SysExcelWorkbook workbook;

    SysExcelWorksheets worksheets;

    SysExcelWorksheet worksheet;

    SysExcelCells cellsHeader, cellsData;

    SysExcelCell cellAccNum, cellName;

    excelApp = SysExcelApplication::construct();

    workbooks =excelApp.workbooks();

    workbook = workbooks.add();

    worksheets = workbook.worksheets();

    worksheet = worksheets.itemFromNum(1);

    worksheet.name("Customers");

    cellsHeader = worksheet.cells();

    cellsData = worksheet.cells();

    cellsHeader.range('A:A').numberFormat('@');

    cellAccNum = cellsHeader.item(1, 1);

    cellAccNum.value("Account Num");

    cellName = cellsHeader.item(1, 2);

    cellName.value("Name");

    row = 1;

    while select custTable

    {

        if(row != 1550)
       
        {
            row++;

            cellAccNum = cellsData.item(row, 1);

            cellAccNum.value(custTable.AccountNum);

            cellName = cellsData.item(row, 2);

            cellName.value(custTable.Name);
        }
        else
        {
            break;
        }
    }

    worksheet.columns().autoFit();

    excelApp.visible(true);
}

Get Data from Rest API In Dynamics Ax 2009 or Ax2012

In this post will explain about how to receive data from Rest API.. Here you i attached some sample code receiving data from Rest API in Dynamics ax 2009...

Sample Code:

Public  void receiveClientFromCrm()
{
    System.Net.HttpWebRequest webReq;
    System.Net.HttpWebResponse webRes;
    CLRObject clrObj;

    System.IO.Stream stream;
    System.IO.StreamReader streamRead;
    System.IO.StreamWriter streamWrite;
    System.Net.ServicePoint servicePt;

    xml responseXml;
 

    ;
   

        //This line gives the user control to run unmanaged and managed code
        CodeAccessPermission::revertAssert();
        new InteropPermission(InteropKind::ClrInterop).assert();




clrObj =


System.Net.WebRequest::Create('your api url with accesskey");

        webReq = clrObj;

        //Set Method Type

        webReq.set_Method('GET');

        webReq.set_KeepAlive(true);

        // Set Content type

        webReq.set_ContentType('application/xml');

        //Get Service Point

        servicePt = webReq.get_ServicePoint();

        servicePt.set_Expect100Continue(false);

        //Gets the response object

        webRes = webReq.GetResponse();

        //Get Stream

        stream = webRes.GetResponseStream();
        // BP Deviation documented
        streamRead = new System.IO.StreamReader(stream);

        responseXml = streamRead.ReadToEnd();

        //writing the xml from info  to file using streamwrite


        // BP Deviation documented
        streamWrite = new System.IO.StreamWriter("File Directory Location for saving with particular file pattern");

        streamWrite.WriteLine(responseXml);
        // BP Deviation documented
        codeAccessPermission::revertAssert();
        streamWrite.Flush();

        streamWrite.Close();

        streamWrite.Dispose();
 


}

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);
    }
}