Thursday, July 31, 2014

Loading NumberSequence for a module

static void loadNumSeq(Args _args)
{
    NumberSeqModuleHRM numhrm=new NumberSeqModuleHRM();
    ;
    numhrm.load();
    info("Done");
}

to generate number sequence

info(NumberSeq::newGetNum(Purchparameters::numRefPurchInvoiceId(),true).num());

Friday, July 18, 2014

Save File As CSV From Excel through X++

static void SaveAsCSVFileFromExcel(Args _args)
{
    #Excel
      SysExcelApplication excel;
      SysExcelWorkBooks books;
      Filename excelFileName;
      Filename csvFileName;
      ;
    /*
      csvFileName = 'C:\\LedgerData.csv';
      excelFileName = ' C:\\LedgerData.xls';
      excel = SysExcelApplication::construct( );
      excel.displayAlerts (false);
      books = excel.workbooks( );
      books.open(csvFileName,0,false,2,"","",false,#xlWindows,",",false,false,1,false,false,1,false);

      books.item(1).saveAs(excelFileName);
      excel.quit();*/

      csvFileName = 'D:\\LedgerData.csv';
      excelFileName = 'C:\\LedgerData.xlsx';
      excel = SysExcelApplication::construct();
      excel.displayAlerts (false);
      books = excel.workbooks( );
      books.open(excelFileName,0,false,2,"","",false,#xlWindows,",",false,false,1,false,false,1,false);

      books.item(1).saveAs(csvFileName);
      excel.quit();
}

Thursday, July 17, 2014

Cross company in X++

static void crossCompanyUse(Args _args)
{
    AddressCountryRegion addressCountryRegion,_addressCountryRegion;
    Dialog      dialog;
    DialogField dialogField;
    ;
    dialog = new Dialog();
    dialogField=dialog.addField(typeId(DataareaId));
    dialog.run();
    select * from _addressCountryRegion;

    If(!_addressCountryRegion)
    {
         while Select crossCompany CountryRegionId,Name,Type,AddrFormat,ISOcode
         from addressCountryRegion where addressCountryRegion.dataAreaId == dialogField.value()
         {
            _addressCountryRegion.clear();
            _addressCountryRegion.initValue();
            _addressCountryRegion.CountryRegionId = addressCountryRegion.CountryRegionId ;
            _addressCountryRegion.Name = addressCountryRegion.Name ;
            _addressCountryRegion.Type = addressCountryRegion.Type;
            _addressCountryRegion.AddrFormat = addressCountryRegion.AddrFormat;
            _addressCountryRegion.ISOcode = addressCountryRegion.ISOcode;
            _addressCountryRegion.insert();
         }
         info("Records Imported");
         // insert_recordset _addressCountryRegion(CountryRegionId) Select crossCompany  CountryRegionId  from addressCountryRegion where addressCountryRegion.dataAreaId == dialogField.value();
   }
   else
   {
        info("Records alredy exists");
   }

}


static void crossCompanyUseModify(Args _args)
{
    AddressCountryRegion addressCountryRegion,_addressCountryRegion;
    Dialog      dialog;
    DialogField dialogField;
    CompanyId   currentCompany,newCompany;
    ;
    dialog = new Dialog();
    dialogField=dialog.addField(typeId(DataareaId));

    if(dialog.closedOk())
    {
        dialog.run();
        currentCompany = curext();
        newCompany = dialogField.value();
        select * from _addressCountryRegion;
        If(!_addressCountryRegion)
        {
            select * from _addressCountryRegion;
             while Select crossCompany CountryRegionId,Name,Type,AddrFormat,ISOcode
             from addressCountryRegion where addressCountryRegion.dataAreaId == dialogField.value()
             {
                _addressCountryRegion.clear();
                _addressCountryRegion.initValue();
                _addressCountryRegion.CountryRegionId = addressCountryRegion.CountryRegionId ;
                _addressCountryRegion.Name = addressCountryRegion.Name ;
                _addressCountryRegion.Type = addressCountryRegion.Type;
                _addressCountryRegion.AddrFormat = addressCountryRegion.AddrFormat;
                _addressCountryRegion.ISOcode = addressCountryRegion.ISOcode;
                _addressCountryRegion.insert();
             }
             info("Records Imported");
             // insert_recordset _addressCountryRegion(CountryRegionId) Select crossCompany  CountryRegionId  from addressCountryRegion where addressCountryRegion.dataAreaId == dialogField.value();
       }
       else
       {
            info("Records alredy exists");
       }
    }
}

xml creation

// Changed on 09 Dec 2013 at 16:47:30 by malle
void AsnXmlCreation()
{
    XmlDocument xmlDoc;
    XmlElement xmlRoot;
    XmlElement xmlField;
    XmlElement xmlRecord,xmlRecord1,xmlRecord2;
    XMLWriter xmlWriter;
    CustPackingSlipTrans custPackingSlipTrans;
    SalesLine salesLine_1;
    CustPackingSlipJour custPackingSlipJour;
    DictTable dictTable_1 = new DictTable(tablenum(SalesLine));
    DictTable dictTable_2 = new DictTable(tablenum(CustPackingSlipJour));
    DictTable dictTable_3 = new DictTable(tablenum(CustPackingSlipTrans));
    DictField dField;
    int i, fieldId,fieldid_1;
    str value;
    FileIoPermission _perm;
    PackingSlipId _packingSlipId;
    ;

    xmlDoc = XmlDocument::newBlank();
    xmlRoot = xmlDoc.createElement("CustPackingSlip");
    _packingSlipId = "PS-101729";

    select custPackingSlipJour where  custPackingSlipJour.PackingSlipId == _packingSlipId;

    while select salesline_1 where salesLine_1.SalesId == custPackingSlipJour.SalesId
    {
        select CustPackingSlipTrans
            where CustPackingSlipTrans.PackingSlipId == custPackingSlipJour.PackingSlipId && CustPackingSlipTrans.SalesId == salesLine_1.SalesId && CustPackingSlipTrans.InventTransId == salesLine_1.InventTransId;

        xmlRecord1 = xmlDoc.createElement("SalesLine");
            for (i=1; i<=5; i++)
            {
                switch(i)
                {
                    case 1:
                        fieldId = fieldname2id(salesLine_1.TableId,"LineNum");
                        break;
                    case 2:
                        fieldId = fieldname2id(salesLine_1.TableId,"ItemId");
                        break;
                    case 3:
                        fieldId = fieldname2id(salesLine_1.TableId,"SalesQty");
                        break;
                    case 4:
                        fieldId = fieldname2id(salesLine_1.TableId,"SalesUnit");
                        break;
                    case 5:
                        fieldId = fieldname2id(salesLine_1.TableId,"RemainSalesPhysical");
                        break;

                }
                dField = dictTable_1.fieldObject(fieldId);
                xmlField = xmlDoc.createElement(dField.name());
                value = salesLine_1.(fieldId);
                xmlField.innerText(value);
                xmlRecord1.appendChild(xmlField);
            }
       xmlRecord2 = xmlDoc.createElement("CustPackingSlipJour");
       xmlRecord = xmlDoc.createElement("CustPackingSlipTrans");
            for (i=1; i<=3; i++)
            {
                switch(i)
                {
                    case 1:
                        fieldId = fieldname2id(CustPackingSlipTrans.TableId,"PackingSlipId");
                        break;
                    case 2:
                        fieldId = fieldname2id(CustPackingSlipTrans.TableId,"Remain");
                        break;
                    case 3:
                        fieldId = fieldname2id(CustPackingSlipTrans.TableId,"Qty");
                        break;
                }

            dField = dictTable_3.fieldObject(fieldId);
            xmlField = xmlDoc.createElement(dField.name());
            switch (dField.baseType())
            {
                case Types::Int64 :
                    value = int642str(CustPackingSlipTrans.(fieldId));
                    break;
                case Types::Integer :
                    value = int2str(CustPackingSlipTrans.(fieldId));
                    break;
                default :
                    value = CustPackingSlipTrans.(fieldId);
                break;
            }
            xmlField.innerText(value);
            xmlRecord.appendChild(xmlField);

            if(value != "" && fieldId == fieldname2id(CustPackingSlipTrans.TableId,"PackingSlipId"))
            {
                fieldId_1 = fieldname2id(custPackingSlipJour.TableId,"Qty");
                dField = dictTable_2.fieldObject(fieldId_1);
                xmlField = xmlDoc.createElement(dField.name());
                value = custPackingSlipJour.(fieldId_1);
                xmlField.innerText(value);
                xmlRecord2.appendChild(xmlField);

            }
            else if((value == "" && fieldId == fieldname2id(CustPackingSlipTrans.TableId,"PackingSlipId")))
            {
                fieldId_1 = fieldname2id(custPackingSlipJour.TableId,"Qty");
                dField = dictTable_2.fieldObject(fieldId_1);
                xmlField = xmlDoc.createElement(dField.name());
                value = custPackingSlipJour.(fieldId_1);
                xmlRecord2.appendChild(xmlField);

            }
            }
        xmlrecord2.appendChild(xmlRecord);
        xmlrecord1.appendChild(xmlRecord2);
        xmlRoot.appendChild(xmlRecord1);
    }
    xmlDoc.appendChild(xmlRoot);
    info(xmlDoc.toString());
   // _perm = new FileIoPermission(@"D:\"+custPackingSlipJour.PackingSlipId".xml",'W');
    xmlWriter = XMLWriter::newFile(@"D:\Malleswaran_Data\"+custPackingSlipJour.PackingSlipId+".xml");
    xmlDoc.writeTo(xmlWriter);
   // _perm.assert();
}

AIF Document services operations

static void AifSample_CustomerService(Args _args)
{

    /*
        All code used below is meant for illustration purposes only and not intended for use in production. The following disclaimer applied to all code used in this blog:

        Copyright (c) Microsoft Corporation. All rights reserved.  THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
        USE AND REDISTRIBUTION OF THIS CODE, WITH OR WITHOUT MODIFICATION, IS HEREBY PERMITTED.
    */


    /*
        This job demonstrates how to use AIF data objects to call an AIF service from X++.
        The CustCustomerService service class is used to call the CRUD + find service operations on customer data.
        The new service class delegates to the underlying Axd<Document> class for all operations.
    */

    // TODO: Before creating a customer, make sure that the Number sequence for the reference Directory ID is setup at the following location:
    //       Basic => Setup => Directory => Parameters => Number Sequences tab => Directory Id

    // TODO: The delete code has been commented out so that the created customer can actually be viewed from the CustTable form.  Uncomment this code to test the delete functionality.

    CustCustomerService     customerService;            // Customer Service class
    CustCustomer            customer;                   // Customer Document object
    CustCustomer            customerRead;               // Customer Document object
    CustCustomer_CustTable  custTable;                  // CustTable data object
    CustCustomer_CustTable  custTableRead;              // CustTable data object
    AifEntityKeyList        entityKeyList;              // Entity key list
    AifEntityKeyList        entityKeyListFind;          // Entity key list
    AifQueryCriteria        queryCriteria;
    AifCriteriaElement      criteriaElement;
    AccountNum              accountNum;
    Name                    name;
    ;

    // Create the service instance
    customerService =  CustCustomerService::construct();

    // Create the Customer document object
    customer = new CustCustomer();
    customer.createCustTable();                            // Create the CustTable list
    custTable = customer.parmCustTable().addNew();         // Add CustTable instance to CustTable list

    // Initialize the CustTable instance
   // custTable.parmName("Cust01");
    custTable.parmAccountNum("22220002");
    custTable.parmCustGroup("10");
    custTable.parmCurrency("USD");
    custTable.parmPartyType(DirPartyType::Organization);

    // Create Customer
    entityKeyList = customerService.create(customer);
    accountNum = entityKeyList.getEntityKey(1).parmKeyDataMap().lookup(fieldnum(CustTable, accountnum));
    info(strfmt("Created customer:  Account Number: %1.", accountNum));

    //Creating another Customer
    entityKeyList = customerService.create(customer);
    accountNum = entityKeyList.getEntityKey(2).parmKeyDataMap().lookup(FieldNum(Custtable,accountNum));
    info(strfmt("Created another Customer :  Account Number : %1. ",accountNum));


    // Read Customer using returned entity key
    customerRead = customerService.read(entityKeyList);
    custTableRead = customerRead.parmCustTable().get_Item(0);
    info(strfmt("Read customer: Account Number: %1, Name: %2.", custTableRead.parmAccountNum(), custTableRead.parmName()));

    // Update Customer
    custTableRead.parmName(custTableRead.parmName() + ": Updated Name");
    customerService.update(entityKeyList, customerRead);
    info (strfmt("Updated Customer: Account Number: %1.", custTableRead.parmAccountNum()));

    // Call Read to check update
    customer = customerService.read(entityKeyList);
    custTable = customerRead.parmCustTable().get_Item(0);
    info(strfmt("Read updated customer: Account Number: %1, Name: %2.", custTable.parmAccountNum(), custTable.parmName()));

    // Call FindKeys to find entity keys of matching customer entity keys
    queryCriteria = new AifQueryCriteria();
    criteriaElement = AifCriteriaElement::newCriteriaElement('CustTable', 'CustGroup', AifCriteriaOperator::Equal, '10');
    queryCriteria.addCriteriaElement(criteriaElement);
    entityKeyListFind = customerService.findKeys(queryCriteria);
    info(strfmt("Find customer keys: Result count: %1", entityKeyListFind.getEntityKeyCount()));

    // Call Find to find matching customers
    queryCriteria = new AifQueryCriteria();
    criteriaElement = AifCriteriaElement::newCriteriaElement('CustTable', 'CustGroup', AifCriteriaOperator::Equal, '10');
    queryCriteria.addCriteriaElement(criteriaElement);
    customerRead = customerService.find(queryCriteria);
    info(strfmt("Find customer: Result count: %1", customerRead.existsCustTable()?customerRead.parmCustTable().get_Count():0));

    info("TO DO: To test delete, uncomment delete code in the job.");
    // TODO: UNCOMMENT TO DELETE CUSTOMER
    /*
    // calling deleting customer
    customerService.delete(entityKeyList);
    info(strfmt("Deleted customer:  Account Number: %1.", accountNum));
    */
    pause;
}

Adding OR condition to queryrange

static void AddORRangeToQuery(Args _args)
{
    Query q = new Query();  // Create a new query.
    QueryRun qr;
    CustTable ct;
    QueryBuildDataSource qbr1;
    str strTemp;
    ;

    // Add a single datasource.
    qbr1 = q.addDataSource(tablenum(CustTable));
    // Name the datasource 'Customer'.
    qbr1.name("Customer");

    // Create a range value that designates an "OR" query like:
    // customer.AccountNum == "4000" || Customer.CreditMax > 2500.

    // Add the range to the query data source.
    qbr1.addRange(fieldNum(CustTable, AccountNum)).value(
    strFmt('((%1.%2 == "4000") || (%1.%3 > 2500))',
        qbr1.name(),
        fieldStr(CustTable, AccountNum),
        fieldStr(CustTable, CreditMax)));

    // Print the data source.
    print qbr1.toString();
    info(qbr1.toString());

    // Run the query and print the results.
    qr = new QueryRun(q);

    while (qr.next())
    {
        if (qr.changedNo(1))
        {
            ct = qr.getNo(1);
            strTemp = strFmt("%1 , %2", ct.AccountNum, ct.CreditMax);
            print strTemp;
            info(strTemp);
        }
    }
    pause;
}

Enable Paging in Ax 2009

static void ABTest(Args _args)
{
 Query query = new Query(Querystr('ABTest'));
 salestable salestable;

//query query = new Query();
QueryBuildDataSource qbds;
QueryRun qr;
tableid tableid;



qbds = query.dataSourceTable(tablenum(salestable));
//Order by item id
qbds.addOrderByField(fieldnum(salestable,salesid));
//Instantiate a Queryrun class
qr = new QueryRun(Query);
//Enable Ordering
qr.literals(true);
// Enable position paging for the queryrun object
qr.enablePositionPaging(true);
//Add a range by providing the parameters as starting record number and number of records
qr.addPageRange(10,20);
while(qr.next())
{
salestable = qr.get(tablenum(salestable));
info(salestable.SalesId);
}

}

Monday, July 14, 2014

Document handling Edit Notes

public void docHandlingEditNotes(RefRecId _recId, Notes _notes,Description _strDescription)
{
DocuRef docuref;
;
ttsbegin;
select forupdate firstonly docuref where docuref.RecId == _recId;
docuref.Notes = _notes;
docuref.Name = _strDescription;
docuref.update();
ttscommit;
}

Generic job for testing AIF Read operation

static void GenericReadServiceCall(Args _args)
{
    DictClass dictClass;
    anytype objEntityValue;
    anytype objValue;
    Object object;
    ExecutePermission permission;
    str strClassName="KT_ActivitiesViewService";
    str strTableName="smmActivities";
    str strRecordValue="S450247";

    str strTableMethodName="find";
    str strServiceMethodName="read";
    aifcriteriaElement criteriaElements;
    aifQueryCriteria objqueryCriteria;
    container objContainer;
    SysDictTable objSysDictTable;

    AifEntityKey           entityKey     = new AifEntityKey();
    AifEntityKeyList      entityKeyList = new AifEntityKeyList();



    objSysDictTable=new SysDictTable(tableName2Id(strTableName));
    objEntityValue=objSysDictTable.callStatic(strTableMethodName,strRecordValue); //,"CANONIMAGERUNNER");

     entityKey.parmKeyDataMap(SysDictTable::getKeyData(objEntityValue));
        entityKeyList.addEntityKey(entityKey);
    // Grants permission to execute the DictClass.callObject method.
    // DictClass.callObject runs under code access security.
    permission = new ExecutePermission();
    permission.assert();

    dictClass = new DictClass(className2Id(strClassName));
    object = dictClass.makeObject();

    if (dictClass != null)
    {
    //If it is static method
    //dictClass.callStatic(methodName);
     objValue = dictClass.callObject(strServiceMethodName, object,entityKeyList);
    }

    // Closes the code access permission scope.
    CodeAccessPermission::revertAssert();
}

Generic Job for testing AIF Find operation with criteria

static void GenericFindServiceCall(Args _args)
{
    DictClass dictClass;
    anytype objValue;
    Object object;
    ExecutePermission permission;
    str strClassName="KT_ActivitiesListService";
    str strTableName="smmActivities";
    str strMethodName="find";
    aifcriteriaElement criteriaElements,criteriaElement1,criteriaElement2;
    aifQueryCriteria objqueryCriteria;
    container objContainer;
    aifQueryCriteria queryCriteria;

    objContainer=[1,strTableName,"KTPAGING",1,1,10];

    /* = conins(c,1,"SalesTable");
    c = conins(c,2,"SalesId");
    c = conins(c,3,salesIdValue);*/
    //info(tableid2name(2303));
    //info(tableid2name(8152));
    //pause;

//    criteriaElements = aifCriteriaElement::create(objContainer)


criteriaElements = AifCriteriaElement::newCriteriaElement(tablestr(smmActivities),
                                                                                          "KTPAGING",
                                                                                          AifCriteriaOperator::Range,
                                                                                          "1","10");

    /*criteriaElements[0] = new CriteriaElement();
    criteriaElements[0].DataSourceName = "SalesTable";
    criteriaElements[0].FieldName = "SalesId";
    criteriaElements[0].Value1 = salesIdValue;*/

    objqueryCriteria = new aifQueryCriteria();


    criteriaElement1 = AifCriteriaElement::newCriteriaElement(tablestr(smmActivities),
                                                                                          fieldstr(smmActivities, Closed),
                                                                                         AifCriteriaOperator::Equal,
                                                                                          enum2str(noyes::No));
/*    criteriaElement2 = AifCriteriaElement::newCriteriaElement(tablestr(smmActivities),
    fieldstr(docuref, RefRecId),
    AifCriteriaOperator::Equal,
    "5637666290");
*/
    objqueryCriteria.addCriteriaElement(criteriaElements);
       //objqueryCriteria.addCriteriaElement(criteriaElement1);
             //   objqueryCriteria.addCriteriaElement(criteriaElement2);
    // Grants permission to execute the DictClass.callObject method.
    // DictClass.callObject runs under code access security.
    permission = new ExecutePermission();
    permission.assert();

    dictClass = new DictClass(className2Id(strClassName));
    object = dictClass.makeObject();


    if (dictClass != null)
    {
    //If it is static method
    //dictClass.callStatic(methodName);
     objValue = dictClass.callObject(strMethodName, object, objqueryCriteria);
    }

    // Closes the code access permission scope.
    CodeAccessPermission::revertAssert();

}

Generic job for testing AIF Find operation

static void GenericFindServiceCal(Args _args)
{
    DictClass dictClass;
    anytype objValue;
    Object object;
    ExecutePermission permission;
  //  str strTableName;
    str strClassName="KT_ActivitiesListService";
   // str strClassName="SalesViewQService";
    str strTableName="smmActivities";
//str strTableName="SalesLine";
    str strMethodName="find";
    aifcriteriaElement criteriaElements;
    aifQueryCriteria objqueryCriteria;
    container objContainer;
    aifQueryCriteria queryCriteria;

    objContainer=[1,strTableName,"KTPAGING",1,1,10];
   // objContainer=[1,strTableName,"Salesid",1,1,10];

    /* = conins(c,1,"SalesTable");
    c = conins(c,2,"SalesId");
    c = conins(c,3,salesIdValue);*/
    //info(tableid2name(2303));
    //info(tableid2name(8152));
    //pause;

    criteriaElements = aifCriteriaElement::create(objContainer);

    /*criteriaElements[0] = new CriteriaElement();
    criteriaElements[0].DataSourceName = "SalesTable";
    criteriaElements[0].FieldName = "SalesId";
    criteriaElements[0].Value1 = salesIdValue;*/

    objqueryCriteria = new aifQueryCriteria();
///
    objqueryCriteria.addCriteriaElement(criteriaElements);

    // Grants permission to execute the DictClass.callObject method.
    // DictClass.callObject runs under code access security.
    permission = new ExecutePermission();
    permission.assert();

    dictClass = new DictClass(className2Id(strClassName));
    object = dictClass.makeObject();


    if (dictClass != null)
    {
    //If it is static method
    //dictClass.callStatic(methodName);
     objValue = dictClass.callObject(strMethodName, object, objqueryCriteria);
    }

    // Closes the code access permission scope.
    CodeAccessPermission::revertAssert();

}

Getting document path in document handling

public str getDocPath(str type)
{
    docutype doc= docutype::find(type);
    return doc.ArchivePath;
}

Adding notes to record in document handling

public void docHandlingAddNotes(notes _notes='testNotes',RefTableId objRefTableId,RefRecId objRefRecId,Description strDescription='',str strDateAreId)
{

    docuref                         docuref;
    form                            form2;

    filename                        file, docuFilename;
    recid                           docuvaluerecid;
    docuvalue                       docuvalue;
    int                             hwnd;//wfs ctodd 6/21/2012

    docutype                        docutype;
    DocuActionArchive archive;
    System.IO.FileInfo fileInfo;
    int size;

    Filename    onlyFilename;
    Filename    curFileType;
    ;


       if(_notes)
        {
            ttsbegin;
            docuref.TypeId = "Note";
            docuref.Name   = strDescription;
            docuref.Notes  = _notes;
            docuRef.Restriction  = DocuRestriction::External;
            docuref.RefCompanyId = strDateAreId;

            docuref.RefTableId   = objRefTableId;
            docuref.RefRecId     = objRefRecId;
            docuref.insert();

/*           docuvalue.initValue();
           docuvalue.insert();
           docuref.ValueRecId = docuvalue.RecId;
           docuref.update();
           docuvaluerecid = docuvalue.RecId;
  */
           //select forupdate docuvalue where docuvalue.recid == docuvaluerecid;
           //docuvalue =  docuvalue::writeDocuValue(docuref,file);

            /*fileInfo = new System.IO.FileInfo(file);
            size = fileInfo.get_Length();
            info(strfmt("%1",size));*/

           //archive = new DocuActionArchive();
           //archive.add(docuRef, file);
           /*
           docutype = docutype::find(docuref.TypeId);
           numSeq = NumberSeq::newGetNum(DocuParameters::numRefDocuNumber(),true);
           [onlyFilename,curFileType]  = Docu::splitFilename(file);
            if(docuType.filePlace == DocuFilePlace::Archive)
            {
                docuFilename = docuRef.path()
                                + smmDocuments::getNonExistingFileName(numSeq,docuRef.path(),curFileType)
                                + '.'
                                + curFileType; //new Filename
                                //uses curFileType
                WinAPI::copyFile(filename, docuFilename);
            }
            else
            {
                docuFilename = filename;
            }

            this.insertDocuValue(docuRef,docuFilename);*/

           ttscommit;

      }
}

Using the above method
------------------------
//adding notes
    AIF_DOCHandCustomService_add.docHandlingAddNotes("Testing data......",8152,5637144709,"Testing data","ceu");

Getting file content of a record from document handling and return to device / base64 code

public notes ArchiveBlob(str strFilePath="C:\\Users\\hemamalinib\\Downloads\\T&L-TDD-V1.2.docx")
{
    Set permissionSet;
    //Hold the instance of table....
//    docuValue objdocuRef;
    //This class is used to process the blob data....
    BinData bin = new BinData();

    //Hold the instance of the encoded string format...

   System.IO.FileStream outFile;
   System.Byte[] arrByte;
   str content;
   System.Int32 j;
   container temp;
    ;
    // Assert permission.
    permissionSet =  new Set(Types::Class);
    permissionSet.add(new FileIOPermission(strFilePath ,"rw"));
    permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
   //FileIOPermission fioPermission;
   //InteropPermission permission = new InteropPermission(InteropKind::ClrInterop);
   //permission.assert();
    //getting file
   //objdocuRef= docuValue::find(_valueRecId); //5637145107);

// Assert permission.
    //fioPermission = new FileIOPermission(strFilePath ,"RW");
    //fioPermission.assert();

    //arrByte= System.IO.File::ReadAllBytes(strFilePath);

    //content =System.Convert::ToBase64String(arrByte);
     //  j =  outFile.Read(arrByte, 0,outFile.
    //CodeAccessPermission::revertAssert();


    //return content;
    // outFile.Close();
  //creating BinData object from Container in the CompanyImage object
    //bin.setData(objdocuRef.File);

    CodeAccessPermission::assertMultiple(permissionSet);
    //temp = this.Job_File_IO_TextIo_Write_Read(strFilePath);
    content = this.Job_File_IO_TextIo_Write_Read(strFilePath);//con2str(temp);
    //temp = WINAPI::findFirstFile(strFilePath);
    //bin.setData(temp);
    //bin.setData(tobjdocuRef.File);
    //encoding the image to base64
    //content = bin.base64Encode();
    // Create the base64 encoded string

    //This is for testing purpose
    //arrByte =System.Convert::FromBase64String(content);
    //outFile = new System.IO.FileStream(strFilePath,System.IO.FileMode::Create,
                             //System.IO.FileAccess::Read);
    //outFile.Read(arrByte, 0, arrByte.get_Length());
    //outFile.Close();
    return content;
}

using the above method
------------------------
//getting file content and return to device
notes filedet;
   filedet = AIF_DOCHandCustomService_add.ArchiveBlob(file);


Another Way
-------------
public notes Blob(RefRecId _valueRecId)
{
    //Hold the instance of table....
    docuValue objdocuRef;
    //This class is used to process the blob data....
    BinData bin = new BinData();
    //Hold the instance of the encoded string format...
    str content;
   System.IO.FileStream outFile;
   System.Byte[] arrByte;
    //getting file
   objdocuRef= docuValue::find(_valueRecId); //5637145107);

  //creating BinData object from Container in the CompanyImage object
    bin.setData(objdocuRef.File);
    //encoding the image to base64
    content = bin.base64Encode();
    // Create the base64 encoded string
    /*
    //This is for testing purpose
    arrByte =System.Convert::FromBase64String(content);
      outFile = new System.IO.FileStream(@"D:\DocHandling\test1.docx",System.IO.FileMode::Create,
                                 System.IO.FileAccess::Write);
      outFile.Write(arrByte, 0, arrByte.get_Length());
      outFile.Close();
    */
    return content;
}

Adding file/document to record

public void docHandlingAdd(filename filename)
{
    Args                            args = new args();
    formrun                         FormRun;
    //filenameSave                    filename;
    Args                            args1 = new args();
    //wfsEMSalesOrderDocumentation    wfsEMSalesOrderDocumentation;
    docuref                         docuref;
    form                            form2;
    FilenameFilter                  _conFilter;
    filename                        file, docuFilename;
    recid                           docuvaluerecid;
    docuvalue                       docuvalue;
    int                             hwnd;//wfs ctodd 6/21/2012
    salestable                      salestable = salestable::find('SO-101342');
    docutype                        docutype;
    DocuActionArchive archive;
    System.IO.FileInfo fileInfo;
    int size;

    Filename    onlyFilename;
    Filename    curFileType;
    ;

    if(SalesTable)
    {
        _conFilter = ['All FIles','*.*'];
         //hWnd = this.hWnd();
        //file = WinAPI::getOpenFileName(infoLog.hWnd(),_conFilter,'','Select Document Path');
        file = filename;

        if(file)
        {
            ttsbegin;
            docuref.TypeId = "Test";
            docuref.Name   = "T&L-TDD-V1.2";
            docuref.Notes  = docuRef.Notes;
            docuRef.Restriction  = DocuRestriction::External;
            docuref.RefCompanyId = SalesTable.dataAreaId;
            //docuref.WfsExportType = wfsexporttype::CommercialInv;
            docuref.RefTableId   = tablenum(SalesTable);
            docuref.RefRecId     = SalesTable.RecId;
            docuref.insert();

           docuvalue.initValue();
           docuvalue.insert();
           docuref.ValueRecId = docuvalue.RecId;
           docuref.update();
           docuvaluerecid = docuvalue.RecId;

           //select forupdate docuvalue where docuvalue.recid == docuvaluerecid;
           //docuvalue =  docuvalue::writeDocuValue(docuref,file);

            /*fileInfo = new System.IO.FileInfo(file);
            size = fileInfo.get_Length();
            info(strfmt("%1",size));*/

           archive = new DocuActionArchive();
           archive.add(docuRef, file);
           /*
           docutype = docutype::find(docuref.TypeId);
           numSeq = NumberSeq::newGetNum(DocuParameters::numRefDocuNumber(),true);
           [onlyFilename,curFileType]  = Docu::splitFilename(file);
            if(docuType.filePlace == DocuFilePlace::Archive)
            {
                docuFilename = docuRef.path()
                                + smmDocuments::getNonExistingFileName(numSeq,docuRef.path(),curFileType)
                                + '.'
                                + curFileType; //new Filename
                                //uses curFileType
                WinAPI::copyFile(filename, docuFilename);
            }
            else
            {
                docuFilename = filename;
            }

            this.insertDocuValue(docuRef,docuFilename);*/

           ttscommit;

           //docuFilename = docutype.ArchivePath + "\\";
           //WinAPI::copyFile(file, docuFilename);
      }
      }
}

Using the above method
--------------------------
filename file = "C:\\Users\\hemamalinib\\Downloads\\Tips_for_Creating_Services_in_Microsoft_Dynamics_AX_2009.pdf";
    KT_DocuHandlingService AIF_DOCHandCustomService_add = new KT_DocuHandlingService();
    //adding new file/document to record
    AIF_DOCHandCustomService_add.docHandlingAdd(file);