4 Jun 2014

TO get a current User Id and User Role assignment through X++


// TO get a current User Id and User Role assignment through X++ in ax 2012

http://arsalanax.blogspot.in/2012/02/role-based-security-in-ax.html

static void UserRoleAssigninfo(Args _args)
{
     SecurityRole        role;
     SecurityUserRole    userRole;
     UserInfo            userInfo;
     ;

 
    select firstonly  role
    exists join userRole
    where role.RecId     == userRole.SecurityRole
          && userRole.User == curUserId();
 
    info(strFmt("%1  -  %2", role.Name,curUserId()));
 
}

Open a Development Workspace directly from X++ code.


//Open a Development Workspace directly from X++ code. For example, you can add a customized button in the Application Workspace to open a Development Workspace. The following X++ code can be used to open a Development Workspace.
X++

static void OpenDevWorkspace(Args _args)
{     int hWorkspace;     hWorkspace = infolog.createDevelopmentWorkspaceWindow();
}

Report SSRS DP,COntract,Controller class


//DP class

[
    SRSReportParameterAttribute(classstr(PurchContractClass))
]
public class PurchDPClass extends SRSReportDataProviderBase
{
    PurchTmp    purchTmp;
}


Method :

[SRSReportDataSetAttribute('PurchTmp')]
public purchTmp getpurchTmp()
{
    select * from purchTmp;
    return purchTmp;
}

Method  1:
[SysEntryPointAttribute(false)]
public void processReport()
{
    PurchTable  purchTable;
    PurchLine   purchLine;
    PurchContractClass purchContractClass;
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;

    purchContractClass = this.parmDataContract() as PurchContractClass;
    purchId = purchContractClass.parmPurchId();
    //purchStatus = purchContractClass.parmPurchStatus();
    //inclTax = purchContractClass.parmInclTax();

     while select purchTable where purchTable.PurchId == purchId
    {
        purchTmp.PurchId = purchTable.PurchId;
        purchTmp.InvoiceAccount = purchTable.InvoiceAccount;
        purchTmp.PurchName = purchTable.PurchName;
        purchTmp.InclTax = purchTable.InclTax;
        purchTmp.PaymMode = purchTable.PaymMode;
        purchTmp.PurchStatus = purchTable.PurchStatus;
        purchTmp.CurrencyCode = purchTable.CurrencyCode;
     
        select purchId from purchLine where purchLine.PurchId == purchTable.PurchId;
     
        purchTmp.itemid = purchLine.ItemId;
        purchTmp.VendGroup = purchLine.VendGroup;
        purchTmp.LineNumber = purchLine.LineNumber;
        purchTmp.PurchQty = purchLine.PurchQty;
     
        purchTmp.insert();
    }
}

//Contract Class:

[DataContractAttribute]
public class PurchContractClass
{
    PurchId     purchId;
    PurchStatus purchStatus;
    InclTax     inclTax;
}

Method 1:
[DataMemberAttribute("PurchId")]
public PurchId parmPurchId(PurchId _purchId = purchId)
{
    purchId = _purchId;
    return purchId;
}

Method 2:
[DataMemberAttribute("InclTax")]
public InclTax parmInclTax(InclTax _inclTax = inclTax)
{
    inclTax = _inclTax;
    return inclTax;
}

Method 3:

[DataMemberAttribute("PurchStatus")]
public PurchStatus parmPurchStatus(PurchStatus _purchStatus = purchStatus)
{
    purchStatus = _purchStatus;
    return purchStatus;
}


// Controller Class

class PurchControllerClass extends SrsReportRunController
{
     RecordSortedList       journalList;


     PurchView      purchview;
     //CWBProjInvoiceContract CWBProjInvoicecontract;
}

protected void initArgs(Args _args)
{
    args = new Args();

     if (_args.object() &&
        _args.object() is RecordSortedList)
    {
        journalList = _args.object();
    }
    else if (_args.record())
    {
        journalList = new RecordSortedList(tableNum(PurchView));
        journalList.ins(_args.record());
    }

    journalList.first(purchview);

    this.parmReportName("PurchReport.PurchReportDesign");
    this.parmShowDialog(false);

    this.parmArgs(_args);
}

protected void preRunModifyContract()
{
    PurchContractClass contract;
    contract = this.parmReportContract().parmRdpContract() as PurchContractClass;

    contract.parmPurchId(purchview.PurchId);
    contract.parmVendAccount(purchview.InvoiceAccount);
    ////contract.parmPurchStatus(purchview.PurchStatus);
    //contract.parm(purchview.PurchId);
}

public static void main(Args _args)
{
   PurchControllerClass controller = new PurchControllerClass();
    ;


   controller.parmReportName("PurchReport.PurchReportDesign");
   //controller.parmArgs(_args);
    controller.initArgs(_argsssssss);

    controller.startOperation();
}

Import Customer from XLs fiile through X++ code


// Import Customer from XLs fiile through X++ code


error

public void customer()
{
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;
 FileName                    filename;
    //DialogField                 dialogFileName;
    //int row;
    ImportCSV    Importquality;
    ImportNewCustomer       customer;
    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filename
    #endmacro

    DirPartyTable               dirPartyTable;
    CustTable                   custTable,cust;
    LogisticsPostalAddress      logisticsPostalAddress;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    Name                            name;

    str AccountNo,Address,CurrencyC,custGrp,Location,PaymTerm,Paymode,city,StreetNo,country,zip,LocationName;
    str phone;

        //int row =2;
    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 "";
    }

DialogRunbase       dialog = super();
    DialogField          dialogFileName;
     #Excel


    dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
    dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS100852","*.csv"]);
    dialog.filenameLookupTitle("Upload from EXCEL/CSV");
    dialogFilename.value(filename);
    filename                = dialogFilename.value();


    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    //specify the file path that you want to read

    try
    {
    workbooks.open(filename);
    }
    catch (Exception::Error)
    {
    throw error("File cannot be opened.");
    }

    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1); //Here 3 is the worksheet Number
    cells = worksheet.cells();
    //row =1;
     ttsBegin;
    custTable.initValue();
    do
    {
        row++;
                AccountNo   =  COMVariant2Str(cells.item(row,1).value());
                custGrp     =  COMVariant2Str(cells.item(row,2).value());
                CurrencyC   =  COMVariant2Str(cells.item(row,3).value());
                PaymTerm    =  COMVariant2Str(cells.item(row,4).value());
                Paymode     =  COMVariant2Str(cells.item(row,5).value());
                Address     =  COMVariant2Str(cells.item(row,6).value());
                city        =  COMVariant2Str(cells.item(row,7).value());
                StreetNo       =  COMVariant2Str(cells.item(row,8).value());
                country     =  COMVariant2Str(cells.item(row,9).value());
                zip         =  COMVariant2Str(cells.item(row,10).value());
                Phone       =  COMVariant2Str(cells.item(row,11).value());
                LocationName=  COMVariant2Str(cells.item(row,12).value());
                Location   = COMVariant2Str(cells.item(row,13).value());
                name        = COMVariant2Str(cells.item(row,14).value());

                custTable.AccountNum    = AccountNo;
                custTable.CustGroup     = custGrp;
                custTable.Currency      = CurrencyC;
                custTable.PaymTermId    = PaymTerm;
                custTable.PaymMode      = Paymode;
                dirPartyTable.Name      = name;


                custTable.insert(DirPartyType::Person,dirPartyTable.Name);

                /* Creates a new instance of the DirParty class from an address book entity
                   that is represented by the custTable parameter. */

                dirParty = DirParty::constructFromCommon(custTable);

                dirPartyPostalAddressView.LocationName     = Location;
                dirPartyPostalAddressView.City              = city;
                dirPartyPostalAddressView.Street            = Address;
                dirPartyPostalAddressView.StreetNumber      = StreetNo;
                dirPartyPostalAddressView.CountryRegionId   = country;

                dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

                dirPartyContactInfo.LocationName    = LocationName;
                dirPartyContactInfo.Locator         = (Phone);
                dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
                dirPartyContactInfo.IsPrimary       = NoYes::Yes;


                dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

                type = cells.item(row+1, 1).value().variantType();
         ttsCommit;
    }
     while (type != COMVariantType::VT_EMPTY);
                application.quit();

}

Import Xls file via Code Class: X++


// Import Xls file via Code Class:


class ImportNewCustomer extends RunBaseBatch
{

    FileName                    filename;

    DialogField                 dialogFileName;
    int row;
     ImportCSV    Importquality;
    ImportNewCustomer       customer;

     #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filename
    #endmacro
}


static void main(Args _args)
{

   ImportNewCustomer     customer = new ImportNewCustomer();
        if (customer.prompt())
    {
        customer.run();
    }
}

public boolean unpack(container _packedClass)
{
    Integer     version     = conpeek(_packedClass,1);
    ;
    switch (version)
    {
    case #CurrentVersion:
    [version,#CurrentList]      = _packedClass;
    break;

    default :

    return false;
    }
    return true;
}


public container pack()
{
    return [#CurrentVersion,#CurrentList];
}

public void run()
{
     this.customer();
    super();
}

public void new()
{
    super();
    row =1;
}

public boolean getFromDialog()
{
    filename                = dialogFilename.value();
    return true;
}

public Object dialog()
{
   DialogRunbase       dialog = super();
    //DialogField          dialogFileName;
     #Excel


    dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
    dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS100852","*.csv"]);
    dialog.filenameLookupTitle("Upload from EXCEL/CSV");
    dialogFilename.value(filename);


    return dialog;
}

public void customer()
{
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;

    DirPartyTable               dirPartyTable;
    CustTable                   custTable,cust;
    LogisticsPostalAddress      logisticsPostalAddress;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    Name                            name;

    str AccountNo,Address,CurrencyC,custGrp,Location,PaymTerm,Paymode,city,StreetNo,country,zip,LocationName;
    str phone;


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




    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    //specify the file path that you want to read

    try
    {
    workbooks.open(filename);
    }
    catch (Exception::Error)
    {
    throw error("File cannot be opened.");
    }

    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1); //Here 3 is the worksheet Number
    cells = worksheet.cells();
    //row =1;
     ttsBegin;
    custTable.initValue();
    do
    {
        row++;
                AccountNo   =  COMVariant2Str(cells.item(row,1).value());
                custGrp     =  COMVariant2Str(cells.item(row,2).value());
                CurrencyC   =  COMVariant2Str(cells.item(row,3).value());
                PaymTerm    =  COMVariant2Str(cells.item(row,4).value());
                Paymode     =  COMVariant2Str(cells.item(row,5).value());
                Address     =  COMVariant2Str(cells.item(row,6).value());
                city        =  COMVariant2Str(cells.item(row,7).value());
                StreetNo       =  COMVariant2Str(cells.item(row,8).value());
                country     =  COMVariant2Str(cells.item(row,9).value());
                zip         =  COMVariant2Str(cells.item(row,10).value());
                Phone       =  COMVariant2Str(cells.item(row,11).value());
                LocationName=  COMVariant2Str(cells.item(row,12).value());
                Location   = COMVariant2Str(cells.item(row,13).value());
                name        = COMVariant2Str(cells.item(row,14).value());

                custTable.AccountNum    = AccountNo;
                custTable.CustGroup     = custGrp;
                custTable.Currency      = CurrencyC;
                custTable.PaymTermId    = PaymTerm;
                custTable.PaymMode      = Paymode;
             
                custTable.insert(DirPartyType::Organization,name);

                /* Creates a new instance of the DirParty class from an address book entity
                   that is represented by the custTable parameter. */

                dirParty = DirParty::constructFromCommon(custTable);

                dirPartyPostalAddressView.LocationName     = Location;
                dirPartyPostalAddressView.City              = city;
                dirPartyPostalAddressView.Street            = Address;
                dirPartyPostalAddressView.StreetNumber      = StreetNo;
                dirPartyPostalAddressView.CountryRegionId   = country;

                dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

                dirPartyContactInfo.LocationName    = LocationName;
                dirPartyContactInfo.Locator         = (Phone);
                dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
                dirPartyContactInfo.IsPrimary       = NoYes::Yes;


                dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

                type = cells.item(row+1, 1).value().variantType();
         ttsCommit;
    }
     while (type != COMVariantType::VT_EMPTY);
                application.quit();

}

To create Purchase Requisition Through X++


// To create Purchase Requisition Through X++

static void CreatePurchReqJob(Args _args)

{

    PurchReqTable   purchReqTable;
    PurchReqLine    purchReqLine;
    ProjTable       projTable = projTable::find("???10009");
    SalesLine       salesLine = SalesLine::findInventTransId("00000304_068");
    ;

    purchReqTable.clear();
    purchReqTable.initValue();
    purchReqTable.PurchReqId = NumberSeq::newGetNum(PurchReqTable::numRefPurchReqId()).num();
    purchReqTable.PurchReqName = "Testname";
    purchReqTable.ProjId = projTable.ProjId;
    purchReqTable.ProjIdDataArea = projTable.dataAreaId;
    purchReqTable.insert();

    purchReqLine.clear();
    purchReqLine.initValue();
    purchReqLine.InventDimId = salesLine.InventDimId;
    purchReqLine.initFromPurchReqTable(purchReqTable);
    purchReqLine.ItemId = '1001';//salesLine.ItemId;
    purchReqLine.ActivityNumber = 'AO-3456789';//salesLine.ActivityNumber;
    purchReqLine.BuyingLegalEntity = CompanyInfo::find().RecId;
    purchReqLine.InventDimIdDataArea = salesLine.dataAreaId;
    purchReqLine.initFromProjTable(projTable);
    purchReqLine.insert();

    info(purchReqTable.PurchReqId);

}

To create new customer through X++


// To create new customer through X++

static void JobCreateCustomer (Args _args)
{
    CustTable                    custTable;
    NumberSeq                    numberSeq;
    Name                         name ='SouthSide Street LTDA';

    DirParty                        dirParty;
    DirPartyPostalAddressView       dirPartyPostalAddressView;
    DirPartyContactInfoView         dirPartyContactInfo;
    ;

    /* Marks the beginning of a transaction.
       Necessary to utilize the method numRefCustAccount() */
    ttsBegin;
    custTable.initValue();

   try
    {
       //CustTable
        numberSeq               = NumberSeq::newGetNum(CustParameters::numRefCustAccount());
        custTable.AccountNum    = numberSeq.num();
        custTable.CustGroup     ='020';
        custTable.Currency      ='BRL';
        custTable.PaymTermId    ='10DD';
        custTable.PaymMode      ='CHEQUE-01';

        custTable.insert(DirPartyType::Organization, name);

        //DirParty

        /* Creates a new instance of the DirParty class from an address book entity
           that is represented by the custTable parameter. */
        dirParty = DirParty::constructFromCommon(custTable);

        dirPartyPostalAddressView.LocationName      ='HeadQuarters ';
        dirPartyPostalAddressView.City              ='São Paulo';
        dirPartyPostalAddressView.Street            ='4th Avenue';
        dirPartyPostalAddressView.StreetNumber      ='18';
        dirPartyPostalAddressView.CountryRegionId   ='BRA';
        dirPartyPostalAddressView.State             ='SP';

        // Fill address
        dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

        dirPartyContactInfo.LocationName    ='SouthStreet Contact Phone';
        dirPartyContactInfo.Locator         ='551291165341';
        dirPartyContactInfo.Type            = LogisticsElectronicAddressMethodType::Phone;
        dirPartyContactInfo.IsPrimary       = NoYes::Yes;

        // Fill Contacts
        dirParty.createOrUpdateContactInfo(dirPartyContactInfo);

        // Marks the beginning of a transaction.
        ttsCommit;
    }
    catch(Exception::Error)
    {
       ttsAbort;
       throwException::Error;
    }
}