Tuesday, December 28, 2010

Creating a SalesOrder through .net applications or BC classes

Sometimes it would be necessary for us to create the SalesOrder through the .net application or some third party application at that time we need to make use of BC classes to create SalesOrder. Here is a small snipeet for creating the salesOrder through AXBC classes.

static void salesOrder(Args _args)
{   

       AxSalesTable axSalesTable;
       AxSalesLine axSalesLine;
       AxInventDim_SalesLine axInventDim;
       NumberSequenceReference numberSequenceReference;
       NumberSeq numSeq;
       SalesTable salesTable;
       SalesId salesId;
       ;
       ttsbegin;
       numberSequenceReference = SalesParameters::numRefSalesId();
       numSeq = new NumberSeq();
       numSeq = NumberSeq::newGetNum(numberSequenceReference,true);
       salesId = numSeq.num();
       axSalestable = AxSalesTable::construct();
       axSalesTable.parmCustAccount('100123');
       axSalesTable.salesTable().initFromCustTable();
       axSalesTable.salesTable().initValue();
       axSalesTable.salesTable().initFromContactInfo();
      axSalesTable.parmSalesId(salesId);
       if(!axSalesTable.salesTable().validateWrite())
       {
            numSeq.abort();
            break;
       }
       else
       {
           numSeq.used();
           axSalesTable.save();
        }
        SalesTable = SalesTable::find(salesId);
        axSalesLine = AxSalesLine::construct();
        axSalesLine.parmSalesId(salesId);
        axSalesLine.salesLine().initValue();
        axSalesLine.salesLine().initFromSalesTable(SalesTable);
        axSalesLine.parmItemId('1121');
        axSalesLine.salesLine().initfrominventTable();
        axInventDim = AxInventDim_SalesLine::newAxSalesLine(axSalesLine);
        axInventDim.parmInventSizeId('42');
        axInventDim.parmInventLocationId("21");
        axInventDim.parmConfigId("HD");
        axInventDim.parmInventColorId('01');
        axInventDim.parmInventSiteId('2');
        axInventDim.setInventDimId();
        axSalesLine.axInventDim(axInventDim);
        axSalesLine.save();
        ttscommit;
    
}

Getting the list of datasource from the form

Sometimes may be there would be need to get the names of the datasources used in the form . Here is a small snippet that would get you the list of the data source 

static void datasources(Args _args)
{
        FormRun formRun;
        FormBuildDataSource fbds;
        Args args = new Args();
        Counter i;
         ;
         args.name('Salestable'); //FormName
         formRun = classFactory.formRunClass(args);
         for (i = 1; i <= formRun.form().dataSourceCount(); i++)
         {
          fbds = formRun.form().dataSource(i);
          info(new DictTable(fbds.table()).name());
          }
}

The output of the following code is

Thursday, December 23, 2010

Creating a new form using code

static void CreateForm_usingCode(Args _args)
{
    Form form;
    FormRun formRun;
    Args args;
    FormBuildDesign formBuildDesign;
    FormBuildControl formBuildControl;
    FormBuildTabControl formBuildTabControl;
    FormBuildTabPageControl formBuildTabPageControl;
    FormBuildGridControl formBuildGridControl;
    FormBuildDatasource formBuildDatasource;
    FormBuildStringControl formString;
    ;
    form = new Form();
    formBuildDatasource = form.addDataSource(tableStr(CustTable));
    formBuildDesign = form.addDesign('design');
    formBuildTabControl = formBuildDesign.addControl(FormControlType::Tab, 'Tab1');
    formBuildTabPageControl = formBuildTabControl.addControl(
                                                    FormControlType::TabPage,  TabPage');
    formBuildGridControl = formBuildTabPageControl.addControl(FormControlType::Grid, 'Grid');
    formString = formBuildGridControl.addDataField(formBuildDatasource.id(),
                                                                                      fieldNum (CustTable,           Accountnum));
    formString.label("Customer Account");
    args = new Args();
    args.object(form);
    formRun = classFactory.formRunClass(args);
    formRun.init();
    formRun.run();
    formRun.wait();
}

Getting the List of Private and Shared projects from the Projects node using X++.

For retreiving the list of projects we cannot use Treenode. We should first use infolog.projectrootnode() to get the root node for projects and then proceed with the treenode iterator to get the list of the rest. Below is the code that will display the list of Private and Shared Projects from the project node.

static void GetProjects(Args _args)
{
     ProjectListNode projectListNode;
     treenodeIterator iterator,projectiterator;
     TreeNode treenodeprivate,treenodeprivateprojects,treenodeShared,treenodesharedprojects;
     int i;
     ;
     projectListNode = infolog.projectRootNode();
     treenodeprivate = projectListNode.AOTfirstChild();
     iterator =treenodeprivate.AOTiterator();
    setprefix("Private projects");
    for(i = 1; i<=treenodeprivate.AOTchildNodeCount();i++)
    {
            treenodeprivateprojects = iterator.next();
            info(findproperty(treenodeprivateprojects.AOTgetProperties(),"Name"));
     }
     treenodeshared = infolog.projectRootNode().AOTfindChild('Shared');
     projectiterator = treenodeshared.AOTiterator();
     setprefix("Shared Projects");
     for(i=1; i<= treenodeshared.AOTchildNodeCount();i++)
     {
            treenodesharedprojects = projectiterator.next();
            info(findproperty(treenodesharedprojects.AOTgetProperties(),"Name"));
      }
}
Attached is the Output of the following Job:


It has been some time I have not updated my blog....Well was bit busy... Here we go....I am back ...Watch Out Intresting Posts coming your way....Happy DAXing... :)

Tuesday, November 16, 2010

Reading an XML file in AX 2009

These days there are lot of requirements on Integration with other systems like in import data and export data. One of the means is XML .
Here is a small job to read an XML file in AX

static void ReadingXMLFile(Args _args)

{
         XMLDocument XMLdoc
                        = XMLDocument::newFile      (@"C:\Users\nikhil.pujar\Desktop\Items.xml");
         int i,CountItemtags;
         ;
         XMLdoc.load(XMLdoc.toString());
         info(XMLdoc.getElementsByTagName("number").item(0).text());
         info(XMLdoc.getElementsByTagName("name").item(1).toString());
         countItemTags = xmldoc.getElementsByTagName('number').length();
         info (strfmt('Number of tags with name Item - %1', countItemTags));
        for (i = 0 ; i < countItemTags; i++)
       {
                info ("Item number :" + xmldoc.getElementsByTagName('number').item(i).text());
                info ("Item Name :" + xmldoc.getElementsByTagName('name').item(i).text());
        }
}

Creating a new Item through Code

For Creating a new Item in AX 2009 we have to make a entry in four imp tables
they are
1) InventTable
2) InventTableModule
3) InventItemLocation
4) InventTxt

Below is a simple job which will create a new Item in AX 2009

static void Item(Args _args)
{
     InventTable inventTable;
     InventTableModule inventTableModule;
     InventItemLocation inventItemLocation;
     InventTxt inventTxt;
     int counter;
     ;
     ttsbegin();
     inventTable.initValue();
     inventTable.ItemId = "NIK-1000";
     inventTable.ItemGroupId = "Television";
     inventTable.ItemName = "LCD Plasma";
     inventTable.ModelGroupId = "STD Cost";
     inventTable.DimGroupId = "N-W";
     inventTable.ItemType = ItemType::Item;
     if(inventTable.validatewrite())
    {
         inventTable.insert();
    }
    for(counter=0; counter<=3; counter++)
   {
       inventTableModule.ItemId = inventTable.ItemId;
       inventTableModule.ModuleType = counter;
       inventTableModule.initValue();
       if(inventTableModule.validatewrite())
      {
          inventTableModule.insert();
      }
   }
   inventItemLocation.ItemId = inventTable.ItemId;
   inventItemLocation.inventDimId = InventDim::inventDimIdBlank();
   inventItemLocation.initValue();
   if(inventItemLocation.validatewrite())
  {
       inventItemLocation.insert();
  }
  inventTxt.ItemId = inventTable.ItemId;
  inventTxt.Txt = "LCD Plasma Television";
  if(inventItemLocation.validatewrite())
 {
     inventTxt.insert();
 }
 ttscommit();
 info(" New Item created succesfully");
}

Wednesday, June 16, 2010

Getting the names of all the tables in AX

Getting the names of the TABLES


static void FindTables(Args _args)
{
    Dictionary      dictionary;
    TableId         tableId;
    ;
    dictionary = new Dictionary();
    tableId = dictionary.tableNext(0);
    while (tableId)

    {
        info(tableid2Name(tableId));
        tableId = dictionary.tableNext(tableId);
    }
}
The Output will be as follows



Displaying the names of the files in the directory

To display names of the files in directory

static void ShowFileNameinDirectory(Args _args)
  {
      int           handle;
      FilePath      filePath;
      FileName      FileName;
      ;
      filepath = "D:\\Cole Hersee Reports";
      [handle,filename] =
       WinAPI::findFirstFile(filepath + \\*.xls);
      while (filename)
      {
          info(filepath + "\\" + filename);
          filename = WinAPI::findNextFile(handle);
      }

      WinAPI::findClose(handle);
  }

How to find the mandatory fields in the table manually

USING SYSDICTTABLE CLASS

static void mandatoryFieldsOfATable(Args _args)
{
    SysDictTable sysDictTable;
    SysDictField sysDictField;
    TableId tableId;
    Counter counter;
    ;
    sysDictTable = new SysDictTable(tablenum(CustTable));
    for(counter = 1;counter <= sysDictTable.fieldCnt(); counter++)
   {
        sysDictField = new sysDictField(sysDictTable.id(), sysDictTable.fieldCnt2Id(counter));

       if(sysDictField.mandatory())
                 info(sysDictField.name());
    }
}

The output of the above code will be


Friday, May 14, 2010

Finding OnHand Info of an Item

 OnHand Info of an Item

static void FindingOnHandInfo(Args _args)
{
    ItemId itemId;
    InventDim inventDimCriteria;
    InventDimParm inventDimParm;
    InventOnhand inventOnhand = new InventOnhand();
    ;
    // Specify the item to get onhand info on
    itemId = "1001";
    // Specify the dimensions you want
    // to filter the onhand info on
    inventDimCriteria.InventColorId = "02";
    // Set the parameter flags active
    // according to which of the dimensions
    // in inventDimCriteria that are set
    inventDimParm.initFromInventDim(inventDimCriteria);
    // Specify the inventDim,
    // inventDimParm and itemId
    inventOnhand.parmInventDim(inventDimCriteria);
    inventOnhand.parmInventDimParm(inventDimParm);
    inventOnhand.parmItemId(itemId);
    // Retrieve the onhand info
    info(strfmt("Available Physical: %1",
    inventOnhand.availPhysical()));
    info(strfmt("On order: %1",inventOnhand.onOrder()));
}





The Output of the following Job will be as follows




Only one Post today Coz was really busy with the work   :(
But Still keep on checking the blogs many more to come

Till then keep on DAXing.......Happy DAX-ing     :)
 and yes Happy Weekend too...........................

Friday, May 7, 2010

Using Some of the basic objects of the Query Framework in X++ or AX2009

Using the basic objects in the query framework like Query, QueryBuildDataSource, QueryBuildFieldList, QueryBuildRange, QueryRun

static void Query(Args _args)
{
    Query                   query = new Query();   //Creating a Object of Query Framework
    QueryBuildDataSource    queryBuild;
    QueryBuildFieldList     queryList;
    QueryBuildRange         qbr;
    QueryRun                qr;
    CustTable               custTable;
    ;

    queryBuild  = query.addDataSource(tableNum(CustTable));//Adding Datasource to Query
    queryList   = queryBuild.fields(); //Adding fields to Datasource of Query

    queryList.addField(fieldNum(CustTable, AccountNum));
    queryList.addField(fieldNum(CustTable, CustGroup));   // Adding the fields to querybuildfieldlist
    queryList.addField(fieldNum(CustTable, Currency));
    qbr         =   querybuild.addRange(fieldnum(CustTable,AccountNum)); // Adding Range to the        Datasource of Query
    qbr.value("1000..1300");//Adding value to the range of the Datasource
   

    qr  = new QueryRun(query);//Creating the Object of the Queryrun and passing the query object to excute the Query
    while (qr.next())
    {
        custTable = qr.get(tableNum(CustTable)); // Getting the value of the Query in the relevant buffer
        //custTable = qr.getNo(1);   You can also write this commented code instead of the above one
        info(strfmt("%1, %2, %3", custTable.AccountNum, custTable.CustGroup, custTable.Currency));
    }
}

The Output will be as follows



As you all most be knowing that the CustTable in Dynamics AX is having so many entries but then also the Query is displaying only 8 records that is because we have applied the range on query and the value of the range in the query is 1000..1300 . It means that it will only fetch those records who have account numbers between 1000 and 1300


Keep on DAX- ing !!! Its fun

And watch out for more DAX-Ideas Coming up your way      :)

Transfer Journal for an Item in AX2009

Posting the Transfer Journal for a Item using X++ code in AX2009

static void CreateTransferJournal(Args _args)
{
    InventJournalTable      inventJournalTable;
    InventJournalTrans      inventJournalTrans;
    InventJournalCheckPost  inventJournalCheckPost;
    NumberSeq               num;
    boolean                 _throwserror=true;
    boolean                 _showinforesult=true;
    InventDim               frominventDim,ToinventDim;
    ;
    ttsbegin;

    inventJournalTable.clear();
    num                                 =   new NumberSeq();
    num                                 =   NumberSeq::newGetNum(InventParameters::numRefTransferId());
    inventJournalTable.initFromInventJournalName(InventJournalName::find(InventParameters::find().TransferJournalNameId));
    inventJournalTable.Description      =   "Inventory Transfer Journal";
    inventJournalTable.SystemBlocked    =   true;
    inventJournalTable.insert();
    info("Entry Inserted");
    info(strfmt("The Voucher generated is %1",inventJournalTable.JournalId));

    inventJournalTrans.clear();
    inventJournalTrans.initFromInventJournalTable(inventJournalTable);
    inventJournalTrans.ItemId            =   "1101";
    frominventDim.InventLocationId="21";
    //frominventDim.configId        = "02";
    frominventDim.inventSiteId    ="2";
    ToinventDim.InventLocationId = "34";
    ToinventDim.InventSiteId     = "3";
   // ToinventDim.configId        =  "02";
    ToinventDim                 =  InventDim::findOrCreate(ToinventDim);


    frominventDim = InventDim::findOrCreate(frominventDim);
    inventJournalTrans.InventDimId  =   frominventDim.inventDimId;
    inventJournalTrans.initFromInventTable(InventTable::find("1101"));
    inventJournalTrans.Qty               =   10;
    inventJournalTrans.ToInventDimId     =   ToinventDim.inventDimId;
    inventJournalTrans.TransDate         =   SystemDateget();
    inventJournalTrans.insert();

    inventJournalCheckPost               =  InventJournalCheckPost::newJournalCheckPost(JournalCheckpostType::Post,inventJournalTable);
    inventJournalCheckPost.parmThrowCheckFailed(_throwserror);
    inventJournalCheckPost.parmShowInfoResult(_showinforesult);
    inventJournalCheckPost.run();

    inventJournalTable.SystemBlocked    =   false;
    inventJournalTable.update();

    ttscommit;
    }

Thursday, April 29, 2010

Copying a file from one location to other location using X++

 Copying a file using WINAPI Classes in AX2009

static void WinApiClassestocopythefile(Args _args)
{
    #avifiles
    boolean     present;
    SysOperationProgress    simpleProgress;
    int i;
    ;

   // startlengthyoperation();
    SimpleProgress = SysOperationProgress::newGeneral(#aviupdate, 'Simple', 100);
    if(WinAPI::fileExists("C:\\Documents and Settings\\nikhil.pujar\\My Documents\\Downloads\\ganatharva.pdf"))
    {
    for (i=1; i<=100; i++)
    {
        simpleProgress.incCount();
        simpleprogress.setText(strfmt("%1% Of File is being Copied",i));
        sleep(200);
    }
    WinAPI::copyFile("C:\\Documents and Settings\\nikhil.pujar\\My Documents\\Downloads\\ganatharva.pdf","C:\\Documents and Settings\\nikhil.pujar\\My Documents\\Morphx\\ganatharva.pdf",true);
    Simpleprogress.kill();
    }
    else
    {
        info("This file does not exist");
    }
    info("The file has been Copied :)");
    info(strfmt("The filesize is %1",WinApi::fileSize("C:\\Documents and Settings\\nikhil.pujar\\My Documents\\Morphx\\ganatharva.pdf")));
    info(WinAPI::getComputerName());
    //endlengthyoperation();
}

Tuesday, April 27, 2010

Check Credit Limit for a Sales Order

Credit Limit for a particular Sales Order can be checked as follows through the code

static void CreditLimit(Args _args)
{
    CustCreditLimit     custCreditLimit;
    SalesTable          salesTable;
    ;
    salesTable  =   SalesTable::find("SO-101297");
    info(strfmt("The SalesId is %1",salesTable.SalesId));
    custCreditLimit =   custCreditLimit::construct(salesTable);
    if(custCreditLimit.check())
    {
        info("Credit limit is OKZ");
    }
    info("Job Completed");
}

The Output is :


Emailing Techniques in Dynamics AX or Emailing through X++

E-mailing in Axapta

static void EmailSendingthroughSmmoutlook(Args _args)
{
   SmmOutlookEmail      smmOutlookEmail =   new     SmmOutlookEmail();
   str                  email;
   ;
   if (smmOutlookEmail.createMailItem())
   {
        smmOutlookEmail.addEMailRecipient('pujar.nikhil@gmail.com');
        smmOutlookEmail.addEMailRecipient('lincen_louis@yahoo.com');
        smmOutlookEmail.addSubject("Test Message from Axapta");
        smmOutlookEmail.isHTML(true);
        smmOutlookEmail.addBodyText('Hi Was just tryin to Send Email through Axapta           :)');
        smmOutlookEmail.sendEMail(smmSaveCopyofEmail::No);

    }
}

The above technique will use Microsoft Outlook and create a Email for you but will not send it Problematically you will have to hit send button if you want to send the email.

Here is another technique which will not only create an E-mail but will send also....    :)

    static void emailThruSysInetMail(Args _args)
    {
        SysInetMail mail = new SysInetMail();
        ;
        mail.sendMailAttach('lincen_louis@yahoo.com ', 'pujar.nikhil@gmail.com', 'Test mail from Axapta',         'Hi  There Was tryin to Send email through Axapta :)', false,"");
        SysInetMail::sendEMail('Alerts', 'en-us', 'nikhil.pujar@Solugenix.com');


    }

Thursday, April 22, 2010

Calculating the Sales Tax for a particular SalesOrder

Job for calculating SalesTax amount for particular Sales-Order

static void Calculatingtax(Args _args)
{
    SalesTotals     salesTotals;
    SalesTable              salesTable;
    TaxAmountCur        Amount;
    ;
    salesTable  =   SalesTable::find("SO-101242");
    salesTotals  = SalesTotals::construct(salesTable);
    Amount      = salesTotals.totalTaxAmount();
    info(Strfmt("The tax amount is %1",Amount));
}

The Output will be

Creating a Dialog in X++

Creating a Dialog in X++ or AX 2009

static void CreateDialog(Args _args)
{
  Dialog dailog= new Dialog("Nikhil");//(Created a object of Dialog class)
  Dialogfield field1,field2,field4,field3;//(objects of Dialog field Returns Dialogfield)
  DialogTabpage tab;//(object of DialogTabpage)
  ;
  field1=dailog.addField(typeid(Transdate));//(Parameter should be EDT or Enum)
  field2=dailog.addField(typeid(AccountName));
  field4=dailog.addField(typeid(CustName));

  tab   =dailog.addTabPage("Overview");//(Creates a new Tab Page )
  field3=dailog.addField(typeid(ABC)); //(Once you create Tab page All the fields after that will in     that )
  dailog.addGroup('Help');//(Creates a  Group)
  dailog.addField(typeid(ItemId));//(Now all the fields will be in Group Help)
  dailog.addText("I am Called"); //(adds text)

  if(dailog.run())//(Checks whether Dialog is running or not)
     {
    info(strfmt("%1,%2",field1.value(),field2.value()));//(Gives Value of field1 and field 2)
     }
}

The Output  will be as follows

Friday, April 16, 2010

Reading the SalesId from excel to post the SalesOrder using X++

Reading SalesId from Excel-sheet and then Posting it

static void ReadingSalesIdfromExcel(Args _args)
{
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;
    SalesPosting    salesposting;   //Wrote my own class having a method Post to post a Sales Order.
    int row;
    SalesId salesId;
    #define.Filename('D:\\SalesOrders.xlsx')
    ;
    salesposting    =   new Salesposting();
    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    try
    {
    workbooks.open(#Filename);
    }
    catch (Exception::Error)
    {
    throw error("File cannot be opened.");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    do
    {
    row++;
    salesId = cells.item(row, 1).value().bStr();
    salesposting.post(salesId);// Posting the Sales order with the help of SalesId from excel
    type = cells.item(row+1, 1).value().variantType();
    }
    while (type != COMVariantType::VT_EMPTY);
    application.quit();
}

Creating Sales order and Posting it through X++

Creating a Sales Order through X++

static void createsalesorder(Args _args)
{
    NumberSeq numberSeq;
    SalesTable salesTable;
    SalesLine salesLine;
    ;
    ttsbegin;
 numberSeq=NumberSeq::newGetNumFromCode(SalesParameters::numRefSalesId().numberSequence,true);
    salesTable.SalesId = numberSeq.num();
    salesTable.initValue();
    salesTable.CustAccount = '1301';
    salesTable.initFromCustTable();
    if(SalesTable.SalesId)
    {
    salesTable.insert();
    numberseq.used();
    }
    else
    {
    numberseq.abort();
    }
    salesLine.SalesId = salesTable.SalesId;
    salesLine.ItemId = '1101';
    salesline.SalesQty=100.00;
    salesLine.createLine(true, true, true, true, true, true);
    ttscommit;
}
And the next job is for Posting the above Sales Order Created


static void PostingsalesOrder(Args _args)
{
  SalesTable salesTable;
  SalesFormLetter salesFormLetter=salesFormLetter::construct(Documentstatus::Invoice);
  ;
  salesTable=salesTable::find("SO-101363");
  salesFormLetter.update(salesTable,SystemDateGet(),SalesUpdate::All,AccountOrder::None,false,false);
  info ("Invoice Successfully Generated");
}