blog for Dynamics Axapta

Archive for August, 2010

Creating Number Sequence for a New Module

Creating Number Sequence for a New Module

Say you want to create a new module called Pre Purchase, and for simplicity, we will create just One new Number sequence.
Here’s what to do:-
 

1. Edit the baseEnum NumberSeqModule, adding a reference for your new module (Pre Purchase)

 

2. Create a new EDT say PurchaseRequisitionId which will be used in the module

 

3. Create new class NumberSeqReference_PrePurchase that extends NumberSeqReference

Add 3 methods to that class

public class NumberSeqReference_PrePurchase extends NumberSeqReference

{

}

———————————————————————

protected void loadModule()

{
NumberSequenceReference numRef;

;

/* Setup PurchaseRequisitionId */

numRef.dataTypeId = typeid2extendedtypeid (typeid (PwC_PurchaseRequisitionId));
numRef.referenceHelp = literalStr("Unique key for Purchase Requisition identification. The key is used when creating new Purchase Requisitions."); // Use Labels here
numRef.wizardContinuous = true;
numRef.wizardManual = NoYes::No;
numRef.wizardAllowChangeDown = NoYes::No;
numRef.wizardAllowChangeUp = NoYes::No;
numRef.sortField = 1;
this.create(numRef);
}

———————————————————————

static NumberSeqModule numberSeqModule()

{
return NumberSeqModule::PrePurchase;
}

 

4. Modify the NumberSeqReference Class for the following methods

 

\Classes\NumberSeqReference\moduleList

 

Add the following code

 

// PrePurchase Begin

 

moduleList += NumberSeqReference_PrePurchase::numberSeqModule();

 

// PrePurchase End

 ———————————————————————

\Classes\NumberSeqReference\construct

 

 Add the following code  

// Pre Purchase addition begin

 

case (NumberSeqReference_PrePurchase::numberSeqModule()):

return new NumberSeqReference_PrePurchase(_module);

 

// Pre Purchase addition end

———————————————————————

 

5.  Create a parameters table and form

You should create a parameters table and form for your new module. The easiest way is generally to duplicate an existing Parameters table and modify it as required.

The important elements on the new parameter table are the numberSeqModule() and numberSeqReference() methods.

client server static NumberSeqModule numberSeqModule()
{
    return NumberSeqReference_ PrePurchase::numberSeqModule();
}
---------------------------------------------------------------------
client server static NumberSeqReference numberSeqReference()
{
    return NumberSeqReference::construct(NSParameters::numberSeqModule());
}

In the parameters form, you must ensure that the code in the numberSeqPreInit(), numberSeqPostInit() and NumberSequenceType.executeQuery() methods correctly reflect your new number sequence elements. 

 
6. Calling a number sequence
 
Add this code into this TableParameters
 
static client server NumberSequenceReference numRefSomeMethodID()
{
return NumberSeqReference::findReference(typeId2ExtendedTypeId(typeid(Your EDT)));
}
 
7. Add this declaration in the form ClassDeclaration



public class FormRun extends ObjectRun
{
NumberSeqFormHandler numberSeqFormHandler;
}
 
8. Add this method to the form where you want Number sequences



NumberSeqFormHandler numberSeqFormHandler()
{
if

(!numberSeqFormHandler)
{
numberSeqFormHandler=
NumberSeqFormHandler::newForm(YourTableParameters::numRefSomeMethodID().NumberSequence,
element,
YourTable_DS,
fieldnum(YourTable,YourField));
}
return numberSeqFormHandler;
}

 9. Add Create, Write and Delete methods to the Data source in the Form:

 

Create:

 

void create(boolean append = false)

           // If created externally

{

    ;

    element.numberSeqFormHandler().formMethodDataSourceCreatePre();

 super(append);

     element.numberSeqFormHandler().formMethodDataSourceCreate();

}

 

 

Write:

 

void write()

{

 

 

    ttsbegin;

 

    element.numberSeqFormHandler().formMethodDataSourceWrite();

 

    super();

 

    ttscommit;

}

 

Delete:

 

void delete()

{

    ttsbegin;

    element.numberSeqFormHandler().formMethodDataSourceDelete();

 

    super();

    ttscommit;

}


10. Create a new Number Sequence in BASIC module and Run Wizard

 

Basic -> Setup -> NumberSequences -> Number Sequences

 

Create New Number Sequence code and assign the format. Click "Wizard" button and choose your number sequence in the next screen.

 

Now open your form to see the Number Sequence you created.



Inserting Values to Invent Table from Text File

Hi Everyone,

Here I posted the X++ code for Inserting Text File values into Invent Table.

Inserting Values to Invent Table from Text File

    FilenameOpen               filename;
    dialogField                     dialogFilename;
    Dialog                            dialog;
    TextIO                           file;
    container                       con;
    InventTable                   inventTable1,inventTable2;
    InventTableModule       inventTableModule;
    InventItemGroup           inventItemGroup,inventItemGroup1;
    ItemGroupId                  itemGroupId,itemGroupId1;
    ItemId                            itemId;
    str                                  conItem,conItemGroup;
    #File
    ;
 
 
    dialog                     =   new Dialog("ISIS Bulk Upoad");
    dialogFilename      =   dialog.addField(typeId(FilenameOpen));
 
    dialog.filenameLookupFilter(["@SYS15896",#Mactxt]);  //Create a macro in #File to open all text files(*.txt)
    dialog.filenameLookupTitle("Upload from Text File");
    dialog.caption("Upload from text file");
 
    dialogFilename.value(filename);
 
    if(!dialog.run())
        return;
 
    filename            =   dialogFilename.value();
 
    try
    {
   
    file                = new TextIO(filename, #IO_READ);
 
    if (!file)
    throw Exception::Error;
 
    file.inRecordDelimiter(‘\n’);  //For Next Record
    file.inFieldDelimiter(‘\t’);  //For Next Column value 
 
    ttsbegin;
 
        while(file.status() == IO_STATUS::OK)
        {
            con                   = file.read();
 
            conItem           = conpeek(con,1);
            conItemGroup = conpeek(con,3);
 
            if(conItem!="0")
            {
 
            itemId                   = substr(conItem,1,8);
            ItemGroupId         = substr(conItemGroup,2,13);
 
            //Item Group Table Insert
 
            inventItemGroup1    = inventItemGroup::find(ItemGroupId);
 
                if(inventItemGroup1)
                {
                    info(strfmt("ItemGroup (%1) already exist",ItemGroupId));
                }
                else
                {
                    inventItemGroup.ItemGroupId = ItemGroupId;
                    inventItemGroup.insert();
                    info(strfmt("ItemGroup (%1) Inserted Successfully",ItemGroupId));
                }
                //Item Group Table Insert End
 
                //Invent Table Insert
 
                inventTable1     = inventTable::find(ItemId);
                itemGroupId1    = inventTable::find(ItemId).ItemGroupId;
 
 
                if(inventTable1)
                {
                   if(itemGroupId1 != ItemGroupId)
                   {
                        inventTable2.ItemGroupId = ItemGroupId;
                        inventTable2.update();
                        info(strfmt("ItemGroup for Item (%1) Updated successfully",itemId));
                   }
                   else
                   {
                        info(strfmt("Item (%1) and ItemGroup (%2) already exist",itemId,itemGroupId));
                   }
                }
                else
                {
                    //Invent Table Insert
                    inventTable2.initValue();
                    inventTable2.ItemId              = itemId;
                    inventTable2.ItemGroupId    = ItemGroupId;
                    inventTable2.DimGroupId     = "N – W";
                    inventTable2.ModelGroupId = Enum2str(InventModel::FIFO);
                    inventTable2.insert();
 
                    select forupdate inventTableModule;
                    // Cost
                    inventTableModule.initValue();
                    inventTableModule.ItemId              = ItemId;
                    inventTableModule.ModuleType    = ModuleInventPurchSales::Invent;
                    inventTableModule.insert();
                    // Purchase order
                    inventTableModule.initValue();
                    inventTableModule.ItemId              = ItemId;
                    inventTableModule.ModuleType    = ModuleInventPurchSales::Purch;
                    inventTableModule.insert();
                    // Sales order
                    inventTableModule.initValue();
                    inventTableModule.ItemId              = ItemId;
                    inventTableModule.ModuleType    = ModuleInventPurchSales::Sales;
                    inventTableModule.insert();
 
                    //Invent Item Location Insert
                    inventItemLocation.ItemId           = ItemId;
                    inventItemLocation.inventDimId  = InventDim::inventDimIdBlank();
                    inventItemLocation.insert();
 
                    info(strfmt("Item and ItemGroup for Item (%1) Inserted successfully",itemId));
                }
            }//Null check
        }//While
    ttscommit;
    }
    catch(Exception::Error)
    {
        Error("Upload Failed");
    }

Text File Format that I used for Upload :

Insert Values to Item Group Table from Excel

Insert Values to Item Group Table from Excel

Hi Everyone,

Here I published  the X++ code for Inserting Excel Data in to ItemGroup Table.

Condition: If the importing values are same as the values in the table then the values will not be uploaded, if the description of the item differs then the description only updated in the table.

 

Void Clicked()

{

    SysExcelApplication              application;

    SysExcelWorkbooks              workbooks;

    SysExcelWorkbook                workbook;

    SysExcelWorksheets             worksheets;

    SysExcelWorksheet               worksheet;

    SysExcelCells                        cells;

    COMVariantType                  type;

    System.DateTime                 ShlefDate;

 

    FilenameOpen                     filename;

    dialogField                           dialogFilename;

 

    Dialog                                  dialog;

    InventItemGroup                 inventItemGroup1;

    ItemGroupId                        itemGroupId;

    Name                                  itemGroupName,itemGroupName1;

    int                                        row;

    #Excel

 

    // convert into str from excel cell value

    str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)

    {

        switch (_cv.variantType())

        {

            case (COMVariantType::VT_BSTR):

                return _cv.bStr();

 

            case (COMVariantType::VT_R4):

                return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);

 

            case (COMVariantType::VT_R8):

                return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);

 

            case (COMVariantType::VT_DECIMAL):

                return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);

 

            case (COMVariantType::VT_DATE):

                return date2str(_cv.date(),123,2,1,2,1,4);

 

            case (COMVariantType::VT_EMPTY):

                return "";

 

            default:

                throw error(strfmt("@SYS26908", _cv.variantType()));

        }

        return "";

    }

 

    ;

 

 

    dialog                       =   new Dialog("Upoad from Excel");

    dialogFilename        =   dialog.addField(typeId(FilenameOpen));

 

    dialog.filenameLookupFilter(["@SYS28576",#XLS,"@SYS28576",#XLSX]);

    dialog.filenameLookupTitle("Upload from Excel");

    dialog.caption("Upload from Excel");

 

    dialogFilename.value(filename);

 

    if(!dialog.run())

        return;

 

    filename                =   dialogFilename.value();

 

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

 

    try

    {

       ttsbegin;

 

        do

        {

            row++;

            itemGroupId                  =   COMVariant2Str(cells.item(row, 1).value());

            itemGroupName           =   COMVariant2Str(cells.item(row,2).value());

 

            if(row>1)

            {

                if(substr(itemGroupId,1,1) ==’6′)

                {

                    itemGroupId           = substr(itemGroupId,2,strlen(itemGroupId));

                    inventItemGroup    = inventItemGroup::find(itemGroupId);

                    itemGroupName1   = inventItemGroup::find(itemGroupId).Name;

 

                    if(inventItemGroup)

                    {

                        if(itemGroupName1!=itemGroupName)

                        {

 

                        select forupdate inventItemGroup1 where inventItemGroup1.ItemGroupId == itemGroupId;

                        inventItemGroup1.Name = itemGroupName;

                        inventItemGroup1.update();

                        info(strfmt("Item Description for Item GroupId (%1) Updated succesfully",ItemGroupId));

                        }

 

                    }

                    else

                    {

                        inventItemGroup1.ItemGroupId    = itemGroupId;

                        inventItemGroup1.Name              = itemGroupName;

                        inventItemGroup1.insert();

                        info(strfmt("Item GroupId (%1) uploaded succesfully",ItemGroupId));

                    }

                }

            }

 

            type = cells.item(row+1, 1).value().variantType();

 

        }while (type != COMVariantType::VT_EMPTY);

 

        application.quit();

 

        ttscommit;

 

    }

    catch

    {

        Error("Upload Failed");

        application.quit();

    }

}

Excel Format that I used for Upload :

Hiding Content pane of AX 2009

Hiding Content pane of AX 2009

Here i posted the code to hide the content pane of Dynamics Ax2009

The below code is to hide the content pane of Ax 2009

static void hideContentPaneWindow(Args _args)

{

     #WinApi

     HWND contentPane = WinApi::findWindowEx(WinAPI::findWindowEx(infolog.hWnd(), 0, ‘MDIClient’, ”),0,’ContentFrame’,” );

     ;

    if (contentPane)

    WinApi::ShowWindow(contentPane,#SW_HIDE); // To restore use #SW_RESTORE

}

Creating Number Sequence for Existing Module in AX

Creating Number Sequence for Existing Module in AX

Suppose you have created a new Form in  Existing Module and want to set up NumberSequences on that form just like the base module from the MODULENAMEParameters Form.


Here is what you do:
Step 1:

Assume you have created a new EDT called AX_myEDT which is the Primary Key in the Form Datasource Table.
 

Step 2:

Append \Classes\NumberSeqReference_MODULENAME\loadModule() method and add the following code at the end

//==========================================
numRef.DataTypeId = typeId2ExtendedTypeId(typeid(AX_myEDT)); // The new EDT you made
numRef.ConfigurationKeyId = configurationkeynum(Your Config Key); // Any Configuration key you made
numRef.ReferenceHelp = literalstr("Your label."); // Label you want to appear on the Parameters Form
numRef.WizardContinuous = true;
numRef.WizardManual = NoYes::No;
numRef.WizardAllowChangeDown = NoYes::No;
numRef.WizardAllowChangeUp = NoYes::No;
numRef.SortField = 12; // Sorting on the Parameters Form
numRef.WizardHighest = 999999;
this.create(numRef);
//==========================================

 

Step 3:
 

Create a new Method in the MODULENAMEParameters table
\Data Dictionary\Tables\
MODULENAMEParameters\Methods\ numRefSomeMethodID

 

 

Add the below methods to the respective form:

 

In Class Declaration :

 

NumberSeqFormHandler    numberSeqFormHandler;

 

——————————————————————————————————————–

 

Create new method:

 

NumberSeqFormHandler numberSeqFormHandler()

{

    if (!numberSeqFormHandler)

    {

        numberSeqFormHandler = NumberSeqFormHandler::newForm(MODULENAMEParameters::numRefVas_NewNumSeq().NumberSequence,

                                                             element,

                                                             datasoruce_DS,

                                                             fieldnum(DataSoruce,Fieldname)

                                                            );

    }

    return numberSeqFormHandler;

}
 
Step 5:
 

Add Create, Write and Delete methods to the Data source in the Form:

 

Create:

 

void create(boolean append = false)

           // If created externally

{

    ;

    element.numberSeqFormHandler().formMethodDataSourceCreatePre();

    super(append);

    element.numberSeqFormHandler().formMethodDataSourceCreate();

}

 

 

Write:

 

void write()

{

 

 

    ttsbegin;

 

    element.numberSeqFormHandler().formMethodDataSourceWrite();

 

    super();

 

    ttscommit;

}

 

Delete:

 

void delete()

{

    ttsbegin;


    element.numberSeqFormHandler().formMethodDataSourceDelete();

 

    super();


    ttscommit;

}

 

Step 6:

 

Run NumberSequence Wizard

 

Basic -> Setup -> NumberSequences -> Number Sequences

 

Create New Number Sequence code and assign the format. Click "Wizard" button and choose your number sequence in the next screen.

 

Now open your form to see the Number Sequence you created.

Import Excel Data into Dynamics AX 2009

Here i post code for Import Excel Data into Dynamics using X++ code.

Here the code written in Command Button clicked event, and also i  added the Excel format below of this post which i used.

void clicked()
{
SysExcelApplication             application;
SysExcelWorkbooks               workbooks;
SysExcelWorkbook                workbook;
SysExcelWorksheets              worksheets;
SysExcelWorksheet               worksheet;
SysExcelCells                        cells;
COMVariantType                 type;
System.DateTime                  ShlefDate;

FilenameOpen                     filename;
dialogField                          dialogFilename;

Dialog                               dialog;

//Table Declarations Starts

InventSize                      _InventSize;
InventBatch                    _InventBatch;
InventSerial                    _InventSerial;
InventTable                   _InventTable;
VendParameters              _vendParameters;

//Table Declartions Ends

InventBatchId                   batchNumber;
InventBatchExpDate              expdate;
itemId                          itemid;
TransDate                       poddate;
CertificatesofSterilization  Certs;
CertificatesofAnalysis     CertiAnalysis;
InventSizeId                    InventSize;
ConfigId                        _ConfigId;
InventColorId                   _InventColorId;
InventSiteId                    _InventSiteId;
WMSLocationId                   _WMSLocationId;
InventLocationId                _InventLocationId;
WMSPalletId                     _WMSPalletId;
NoYesId                         ClosedTransactions;
NoYesId                         ClosedTransQty;
str                             pONo;
str                             srNo;
real                            quantity;
int                             row;
InventBatchExpDate              ShelfLifeDate;

#Excel

// convert into str from excel cell value

str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
{
switch (_cv.variantType())
{
case (COMVariantType::VT_BSTR):
return _cv.bStr();

case (COMVariantType::VT_R4):
return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_R8):
return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_DECIMAL):
return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_DATE):
return date2str(_cv.date(),123,2,1,2,1,4);

case (COMVariantType::VT_EMPTY):
return “”;

default:
throw error(strfmt(“@SYS26908″, _cv.variantType()));
}
return “”;
}

;

dialog              =   new Dialog(“Excel Upoad”);
dialogFilename      =   dialog.addField(typeId(FilenameOpen));

dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS28576",#XLS]);
dialog.filenameLookupTitle(“Upload from Excel”);
dialog.caption(“Excel Upload”);

dialogFilename.value(filename);

if(!dialog.run())
return;

filename            =   dialogFilename.value();

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

try
{
ttsbegin;

do
{
row++;

pONo                    =   COMVariant2Str(cells.item(row, 1).value());
itemid                  =   COMVariant2Str(cells.item(row,2).value());
InventSize              =   COMVariant2Str(cells.item(row, 3).value());
batchNumber             =   COMVariant2Str(cells.item(row, 4).value());
poddate                 =   cells.item(row, 5).value().date();
expdate                 =   cells.item(row, 6).value().date();
srNo                    =   COMVariant2Str(cells.item(row, 7).value());
Certs                =   str2enum(Certs,cells.item(row, 8).value().bStr());
CertiAnalysis        =   str2enum(CertiAnalysis,cells.item(row, 9).value().bStr());
quantity                =   cells.item(row, 10).value().double();
_ConfigId               =   COMVariant2Str(cells.item(row, 12).value());
_InventColorId          =   COMVariant2Str(cells.item(row, 13).value());
_InventSiteId           =   COMVariant2Str(cells.item(row, 14).value());
_WMSLocationId          =   COMVariant2Str(cells.item(row, 15).value());
_InventLocationId       =   COMVariant2Str(cells.item(row, 16).value());
_WMSPalletId            =   COMVariant2Str(cells.item(row, 17).value());
ClosedTransactions      =   str2enum(ClosedTransactions,cells.item(row, 18).value().bStr());
ClosedTransQty          =   str2enum(ClosedTransQty,cells.item(row, 19).value().bStr());

if(row > 1)
{

//Insert into InventSize Table

select firstonly _InventSize where _InventSize.ItemId == itemid && _InventSize.InventSizeId == InventSize;

if(!_InventSize)
{
_InventSize.InventSizeId     =      InventSize;
_InventSize.ItemId           =      itemid;
_InventSize.insert();
}
else
{
warning(strfmt(“Item Id and InventSize (%1   –   %2) already exists”,itemid,InventSize));
}

// Insert into InventBatch Table

_InventBatch.inventBatchId      =       batchNumber;
_InventBatch.itemId             =       itemid;
_InventBatch.prodDate           =       poddate;
_InventBatch.expDate            =       expdate;
_InventBatch.insert();

// Insert into InventSerial Table

_InventSerial.InventSerialId    = srNo;
_InventSerial.ItemId            = itemid;
_InventSerial.ProdDate          = poddate;
_InventSerial.insert();

info(strfmt(“Item(%1) uploaded successfully”,itemid));

}

type = cells.item(row+1, 1).value().variantType();

}while (type != COMVariantType::VT_EMPTY);

application.quit();

ttscommit;
}
catch
{
Error(“Upload Failed”);
}

}

These are the details i used to import from Excel.