How to get salesline taxes in ax 2012

How to get salesline taxes in ax 2012

Description : If we customize Sales Invoice and Free Tax Invoice report for AX2012, we may need to get sales tax information. But how to get it. They are quite several ways to get it, and it depends only type of document you print also.

If you need go to until every line level, you can use.

static void CalcTaxForSalesLine(Args _args)
{
    TaxOnItem       TaxOnItem;
    TaxGroupData    TaxGroupData;
    real            TaxAmount;
    TaxValue        TaxValue;
    SalesLine       SalesLine
    ;
    
    select firstOnly salesLine where salesLine.SalesId == 'YourSalesOrderId';
    if(salesLine.TaxItemGroup && salesLine.TaxGroup && salesLine.LineAmount != 0)
    {
        while select TaxOnItem
            where TaxOnItem.TaxItemGroup == salesline.TaxItemGroup
        {
            if(TaxOnItem)
            {
                while select TaxGroupData
                    where TaxGroupData.TaxGroup == Salesline.TaxGroup
                        && TaxGroupData.TaxCode  == TaxOnItem.TaxCode
                {
                    if(TaxGroupData)
                    {
                        TaxValue  =  TaxData::find(TaxOnItem.TaxCode, Systemdateget(), 0).TaxValue;
                        TaxAmount = (Salesline.LineAmount * TaxValue) / 100;
                        info(strFmt("Rate = %1, Tax Amount = %2",TaxValue,TaxAmount));
                        
                    }
                }
            }
        }
    }
}

How to calculate GST for Sales order Confirmation


Description: How to calculate the GST taxes on sales order confirmation. Here i am sharing some code to get Taxes details (IGST/CGST/SGST) in AX.

static void GSTForSOLineWise(Args _args)
{
    CustConfirmJour                     CustConfirmJour;
    PurchLineAllVersions                ObjPurchLineAllVersions;
    ITaxDocument                        taxDocument;
    ITaxDocumentComponentLineEnumerator componentLineEnumerator;
    ITaxDocumentComponentLine           componentLineObject;
    ITaxDocumentMeasureEnumerator       measureEnumerator;

    ITaxDocumentLine                    line;
    ITaxDocumentLineEnumerator          lineEnumerator;

    TaxAmount                           taxAmount,taxValue;
    TaxComponent_IN                     taxComponent;
    ;
    //Find RecId through table method-1
    CustConfirmJour =   CustConfirmJour::findRecId(CustConfirmJour::find("APPL-000534-1").RecId);
    //Find RecId through table method-2
    //CustConfirmJour =   CustConfirmJour::findRecId(CustConfirmJour::findFromCustConfirmTrans("APPL-000534","APPL-000450",29\07\2017).RecId);    
    taxDocument = TaxBusinessService::getTaxDocumentBySource(CustConfirmJour.TableId, CustConfirmJour.RecId);
    //Tax Document not null,GST Apply start
    if(taxDocument != null)
    {
        componentLineEnumerator = taxDocument.componentLines();
        lineEnumerator = taxDocument.lines();
        //Tax Document not null,GST Apply start-1
        if (taxDocument)
        {
            //lineEnumerator for Current line taxDocument start
            lineEnumerator = taxDocument.lines();
            while(lineEnumerator.moveNext())
            {
                //Getting Current line RecId for GST start
                line = lineEnumerator.current();
                line.setTaxDocument(taxDocument);
                if(line.originSourceRecId() != 0 && line.getInvoiceTax().value() != 0)
                {   
                    //componentLineEnumerator for Getting GST Rate,Amount start
                    while(componentLineEnumerator.moveNext())
                    {
                        componentLineObject = componentLineEnumerator.current();
                        taxComponent = componentLineObject.metaData().taxComponent();
                        
                        //GST Calculation start
                        if(taxComponent == "CGST")
                        {   
                            info(strFmt("%1",CustConfirmTrans::findRecId(line.sourceRecId()).LineNum));
                            
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,CustConfirmTrans::findRecId(line.sourceRecId()).RecId,CustConfirmTrans::findRecId(line.sourceRecId()).ItemId));
                        }
                        if(taxComponent == "SGST")
                        {
                            //info(strFmt("%1",CustConfirmTrans::findRecId(line.sourceRecId()).LineNum));
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,CustConfirmTrans::findRecId(line.sourceRecId()).RecId,CustConfirmTrans::findRecId(line.sourceRecId()).ItemId));
                            break;
                        }
                        if(taxComponent == "IGST")
                        {
                            info(strFmt("%1",CustConfirmTrans::findRecId(line.sourceRecId()).LineNum));
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,CustConfirmTrans::findRecId(line.sourceRecId()).RecId,CustConfirmTrans::findRecId(line.sourceRecId()).ItemId));
                            break;
                        }
                        //GST Calculation end
                    }
                    //componentLineEnumerator for Getting GST Rate,Amount end
                }
                //Getting Current line RecId for GST end
            }
            //lineEnumerator for Current line taxDocument end
        }
        //Tax Document not null,GST Apply end-1
    }
    //Tax Document not null,GST Apply end
}

How to calculate GST for Purchase order Confirmation


Description: How to calculate the GST taxes on purchase order confirmation. Here i am sharing some code to get Taxes details (IGST/CGST/SGST) in AX.

static void GSTForPOLineWise(Args _args)
{
    vendPurchOrderJour                  vendPurchOrderJour;
    PurchLineAllVersions                ObjPurchLineAllVersions;
    ITaxDocument                        taxDocument;
    ITaxDocumentComponentLineEnumerator componentLineEnumerator;
    ITaxDocumentComponentLine           componentLineObject;
    ITaxDocumentMeasureEnumerator       measureEnumerator;

    ITaxDocumentLine                    line;
    ITaxDocumentLineEnumerator          lineEnumerator;

    TaxAmount                           taxAmount,taxValue;
    TaxComponent_IN                     taxComponent;
    ;

    vendPurchOrderJour = vendPurchOrderJour::findRecId(VendPurchOrderJour::findByPurchId("PurchaseOrderId").RecId);
    taxDocument = TaxBusinessService::getTaxDocumentBySource(vendPurchOrderJour.TableId, vendPurchOrderJour.RecId);
    //Tax Document not null,GST Apply start
    if(taxDocument != null)
    {
        componentLineEnumerator = taxDocument.componentLines();
        lineEnumerator = taxDocument.lines();
        //Tax Document not null,GST Apply start-1
        if (taxDocument)
        {
            //lineEnumerator for Current line taxDocument start
            lineEnumerator = taxDocument.lines();
            while(lineEnumerator.moveNext())
            {
                //Getting Current line RecId for GST start
                line = lineEnumerator.current();
                line.setTaxDocument(taxDocument);
                if(line.originSourceRecId() != 0 && line.getInvoiceTax().value() != 0)
                {
                    //componentLineEnumerator for Getting GST Rate,Amount start
                    while(componentLineEnumerator.moveNext())
                    {
                        componentLineObject = componentLineEnumerator.current();
                        taxComponent = componentLineObject.metaData().taxComponent();
                        //GST Calculation start
                        if(taxComponent == "CGST")
                        {
                            //info(strFmt("%1",VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).LineNum));
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).RecId,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).ItemId));
                        }
                        if(taxComponent == "SGST")
                        {
                            //info(strFmt("%1",VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).LineNum));
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).RecId,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).ItemId));
                            break;
                        }
                        if(taxComponent == "IGST")
                        {
                            //info(strFmt("%1",VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).LineNum));
                            taxValue = componentLineObject.getMeasure("Rate").value().value() * 100;
                            taxAmount = componentLineObject.getMeasure("Tax Amount").value().value();

                            info(strFmt("Component %1 ,Rate %2, Amount%3, RecId %4, ItemId %5",taxComponent,taxValue,taxAmount,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).RecId,VendPackingSlipTrans::findInventTransId_RU(PurchLine::findRecId(line.originSourceRecId()).InventTransId).ItemId));
                            break;
                        }
                        //GST Calculation end
                    }
                    //componentLineEnumerator for Getting GST Rate,Amount end
                }
                //Getting Current line RecId for GST end
            }
            //lineEnumerator for Current line taxDocument end
        }
        //Tax Document not null,GST Apply end-1
    }
    //Tax Document not null,GST Apply end
}
Get Customer GSTIN from Sales order in ax 2012

Get Customer GSTIN from Sales order in ax 2012

Description: Here I have get Customer GSTIN number from Sales order number. It’s simple to get from table but we need to fire query for that instead of Sql query we can use table method to get GSTIN number for Customer or Customer.

Use below code to get Customer GSTIN number from Sales order number.

info(strFmt("%1",TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CustTable::find(SalesTable::find("SalesOrderId").CustAccount).Party).PrimaryAddressLocation).GSTIN).RegistrationNumber));

How to print sales tax table in Sales Invoice and Free Text Invoice report

Description:-

In order to print sales tax as detail table in Sales Invoice and Free Text Invoice report in AX2012, we need to enable the Sales Tax Specification and set the value other than None. It can be found at
Account receivable -> Setup -> Forms -> Form setup -> General -> Sales tax -> Sales tax specification.

 

For purchase tax, it can be enable using similar way. Just changed AR to AP.
How to get current company tax information and address detail in ax 2012

How to get current company tax information and address detail in ax 2012

Description:

Here I have create demo job for getting current company tax information and address details in dynamics Ax 2012.

static void CompayInfo(Args _args)
{
    info(strFmt("COMPANY NAME-%1",DirPartyTable::findRec(CompanyInfo::Find().recid).Name));
    
    info(strFmt("ZIPCODE-%1",LogisticsPostalAddress::findByLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).ZipCode));
    info(strFmt("STREET-%1",LogisticsPostalAddress::findByLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).Street));
    info(strFmt("CITY-%1",LogisticsPostalAddress::findByLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).City));
    info(strFmt("STATE-%1",LogisticsPostalAddress::findByLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).State));
    info(strFmt("COUNTRYREGIONID-%1",LogisticsPostalAddress::findByLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).CountryRegionId));
    info(strFmt("PHONENO-%1",LogisticsElectronicAddress::findRecId(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryContactPhone).Locator));
    info(strFmt("EMAIL-%1",LogisticsElectronicAddress::findRecId(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryContactEmail).Locator));
    info(strFmt("FAX-%1",LogisticsElectronicAddress::findRecId(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryContactFax).Locator));    
    
    info(strFmt("GSTIN - %1",TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).GSTIN).RegistrationNumber));
    info(strFmt("PAN - %1",substr(TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).GSTIN).RegistrationNumber,3,strLen(TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).GSTIN).RegistrationNumber)-5)));
    info(strFmt("VAT-%1",TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).TIN).RegistrationNumber));
    info(strFmt("CST-%1",TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).SalesTaxRegistrationNumber).RegistrationNumber));
    info(strFmt("ECC-%1",TaxRegistrationNumbers_IN::find(TaxInformation_IN::findDefaultbyLocation(DirPartyTable::findRec(CompanyInfo::Find().recid).PrimaryAddressLocation).ManECCRegistrationNumberTable).RegistrationNumber));
    info(strFmt("CIN-%1",CompanyInfo::Find().CoRegNum)); 
}
How to get PAN From GSTIN in ax 2012

How to get PAN From GSTIN in ax 2012

What is Goods and Services Identification number (GSTIN)?

All the business entities registering under GST will be provided a unique identification number known as GSTIN or GST Identification Number.

Currently any dealer registered under state value added tax (VAT) law has a unique TIN number assigned to him by state tax authorities. Similarly, Service Tax Registration Number is assigned to a service provider by Central Board of Excise and Customs (CBEC).

Under GST regime, all these parties will come under one single authority and the different identification numbers(IN) that will be replaced by a single type of registration number for everyone i.e.,  Goods and Services Identification number (GSTIN). This will ensure better administration by the authority and greater compliance by taxpayers and hopefully improve tax collection.

The first 2 digits of the 15 digit GSTIN will represent the state code.
The next 10 digits will be the PAN number of person or firm engaged in Business.
As proposed the State Code as defined under the Indian Census 2011 would be adopted In the GSTIN. As per the terms of the Indian Census 2011, every State has been allotted a unique two digit code. For 01 for Jammu and Kashmir, 02 for Himachal Pradesh, 03 for Punjab.
The 13th would represent the number of registrations an entity has with in a state under the same PAN. It will be an alpha-numeric number (first 1-9 and then A-Z) and will be assigned on the basis of a number of registrations a legal entity (having the same PAN) in the same state.

What is Permanent account number ( PAN )

Permanent Account Number (PAN) is a ten-digit alphanumeric number, issued in the form of a laminated tamper proof card, by the Income Tax Department of India.

The Permanent Account Number (PAN) is unique to an individual or entity and it is valid across India. Permanent Account Number once allotted to an individual or entity is unaffected by a change of name, address within or across states in India or other factors.

Meaning of PAN card

A typical Permanent Account Number is would look like AFZPK7190K... The logic behind the array of numbers and alphabets is as follows:

First three characters i.e. "AFZ" in the above PAN are alphabetic series running from AAA to ZZZ.
Fourth character i.e. "P" in the above PAN represents the status of the PAN holder.

"P" stands for Individual.
"F" stands for Firm.
"C" stands for Company.
"H" stands for HUF.
"A" stands for AOP.
"T" stands for TRUST etc.

Fifth character i.e. "K" in the above PAN represents first character of the PAN holder's last name/surname.
Next four characters i.e. "7190" in the above PAN are sequential number running from 0001 to 9999.
Last character i.e. "K" in the above PAN is an alphabetic check digit.

static void GetPANFromGSTIN(Args _args)
{
    str RegistrationNumber;

    RegistrationNumber ="24AACHA6869P1ZA";
    RegistrationNumber = substr(RegistrationNumber,3,strLen(RegistrationNumber)-5);
    info(strFmt("%1",RegistrationNumber));
}
How to Get Sales order exchange rate in ax 2012

How to Get Sales order exchange rate in ax 2012

What is an 'Exchange Rate'?

The price of a nation’s currency in terms of another currency. An exchange rate thus has two components, the domestic currency and a foreign currency, and can be quoted either directly or indirectly. In a direct quotation, the price of a unit of foreign currency is expressed in terms of the domestic currency. In an indirect quotation, the price of a unit of domestic currency is expressed in terms of the foreign currency. An exchange rate that does not have the domestic currency as one of the two currency components is known as a cross currency, or cross rate. Also known as a currency quotation, the foreign exchange rate or forex rate.

static void GetExcRate(Args _args)
{
    container  displayFields;
    Common     orderTable;
    real        ExcRate;
    SalesTable _ObjSalesTable;

    select * from _ObjSalesTable where _ObjSalesTable.SalesId == "SalesOrderId";

    orderTable = _ObjSalesTable;
    displayFields = SalesTotals::displayFieldsServer(orderTable, 0, _ObjSalesTable.CurrencyCode);
    ExcRate = conpeek(displayFields, TradeTotals::posExchRate());
    info(strFmt("%1",ExcRate/100));
}

Field 'fieldname' in table 'tablename' has not been explicitly selected


Stack trace: Field 'Weight' in table 'EcoResDistinctProductVariant' has not been explicitly selected.

I am getting this error when I try to Open BOM Lines. Because of in this table “EcoResDistinctProductVariant” I have added customer field “Weight” and after opening table I’m getting field value “Unretrieved”.

Solution-1:

When it is Unretrieved, you have to correct the data. I have done that before by opening the table EcoResDistinctProductVariant using SQL management studio and search for the records related to the legal entities. When the value is 'NULL' you have to make it {empty} or fill a value 0. This depends on the field type. The field IsConsolidation account should be filled with a zero.

Solution-2:
 
You have to update that table field value to ‘0’ instead of ‘null’.
 
Clear previously added data source and ranges in a query in ax 2012

Clear previously added data source and ranges in a query in ax 2012

Description:-

In this article we will see how to remove previously added querybuildrange in query or else in datasource in ax 2012.

Code:-

void QueryRange(boolean _enabled)
{
    QueryBuildDataSource    qbds, qbds1, qbds2;
    QueryBuildRange         qbr1, qbr2, qbr3;
    int                     i;
    ;  
    qbds = journalTable_ds.query().dataSourceNo(1);

    // clear any previously added ds
    for (i = 1; i <= qbds.childDataSourceCount(); i++)
    {
        qbds2 = qbds.childDataSourceNo(i);
        qbds2.clearDynalinks();
        qbds2.clearLinks();
        qbds2.clearRanges();
        qbds2.enabled(false);
    }  

    // create the new ds
    if (_enabled)
    {
        qbds1 = qbds.addDataSource(tablenum(workflowWorkItemTable));
        qbds1.enabled(_enabled);
        qbds1.relations(false);
        qbds1.joinMode(joinMode::ExistsJoin);
        qbds1.addLink(fieldNum(LedgerJournalTable, recId), fieldNum(workflowWorkItemTable, RefRecId), qbds.name ());
        qbr1 = sysQuery::findOrCreateRange(qbds1,fieldnum(workflowWorkItemTable, userId), curuserid());
        qbr2 = sysQuery::findOrCreateRange(qbds1, fieldnum(workflowWorkItemTable, status), enum2str(workflowWorkItemStatus::Pending));
        qbr3 = sysQuery::findOrCreateRange(qbds1, fieldnum(workflowWorkItemTable, RefTableId), int2str(tablenum(LedgerJournalTable)));
    }
}

Note:-

You can simply use clearRange() instead of clearRanges(). If a class offers one useful operation, it's always useful to check whether there isn't more useful stuff.
Another approach is to leave the range in place and change its value to SysQuery::valueUnlimited().

How to Generate Template From Table in Ax 2012


Description:

In this article I have export table data to excel file or else you can dynamically export table header to excel file using X++ code.
Here I have created sample code to dynamically generate excel template for import data into table in ax 2012.
For that you have to create table “CustGroup_Custom”. Here I have given our custom table name like that you can give what you want.
Add fields like SrNo, Description both should be in String data type.
  1. CustGroup_Custom
  • SrNo
  • Description 
Now in SrNo field you can give your Number Sequence and in Description Field you can give what you want in Header.
Example:
SR No
Description
1
Customer Group
2
Name
3
PaymTermId
4
TaxGroupId
Now you are ready to Generate Template for Export into excel file.Here I have set for Path so where you can by default save your excel file or else you can open directly.
Here I have also add some header format so you can see when your excel file generate.

static void BlankTemplate(Args _args)
{
    SysExcelApplication application;
    SysExcelWorkbooks   workbooks;
    SysExcelWorkbook    workbook;
    SysExcelWorksheets  worksheets;
    SysExcelWorksheet   sysExcelWorkSheetToBeDeleted;
    SysExcelWorksheet   worksheet;
    SysExcelCells       cells;
    SysExcelCell        cell;
    SysExcelFont        font;
    #define.STYLE_BOLD('AX_Bold')
    SysExcelInterior    interior;
    SysExcelStyles      styles;
    SysExcelStyle       style;
    int                 row,column;
    str                 filepath;
    COM                 comg,comfont;
    str                 dateValue, dateFormat;
    DialogButton        dialogButton;
    CustGroup_Custom    ObjCustGroup_Custom;
    
    
    dialogButton= Box::yesNo("ARE YOU SURE WANT TO GENERATE CUSTOMER GROUP TEMPLATE", DialogButton::No,"CONFIRMATION FOR CUSTOMER GROUP TEMPLATE");
    if (dialogButton == DialogButton::Yes)
    {
        startLengthyOperation();
        //Filename start
        dateValue   = date2str( systemDateGet(),123,DateDay::Digits2,DateSeparator::None,DateMonth::Digits2,DateSeparator::None,
                            DateYear::Digits4,
                            DateFlags::FormatAll);
        dateFormat = strFmt("%1%2%3",dateValue, '_',subStr( strRem(time2Str(timeNow(), TimeSeparator::Space, TimeFormat::Auto), ' '),0,4));

        filepath = @"PATH" + "ALL CUSTOMER GROUP TEMPLATE " + dateFormat + ".xlsx";
        //Filename end

        application     = SysExcelApplication::construct();
        workbooks       = application.workbooks();
        workbook        = workbooks.add();
        worksheets      = workbook.worksheets();
        worksheet       = worksheets.itemFromNum(1);
        cells           = worksheet.cells();
        cells.range('A:A').numberFormat('@');
        row=1;
        column=1;

        while select ObjCustGroup_Custom order by ObjCustGroup_Custom.SrNo asc
        {
            cell = cells.item(row, column);
            cell.value(ObjCustGroup_Custom.Description);
            font = cell.font();
            font.bold(true);
            comg = cell.comObject();
            comfont=comg.font();
            comfont.bold(2);
            comg.style("Note");
            comfont.color(WINapi::RGB2int(0,0,0));
            column++;
        }
        application.visible(false);
        if (application.workbooks().count()>1)
        {
            application.workbooks().close();
        }
        while(worksheets.count() > 1)
        {
            sysExcelWorkSheetToBeDeleted = worksheets.itemFromNum(2);
            sysExcelWorkSheetToBeDeleted.delete();
        }
        worksheet.columns().autoFit();
        //workbook.saveAs(filepath);
        application.visible(true);
        //workbook.close();
        endLengthyOperation();
    }
}
How to Delete report file from your local drive in Ax 2012

How to Delete report file from your local drive in Ax 2012

Description:- 

SQL Server Reporting Services is the primary reporting platform for Microsoft Dynamics AX. Reporting Services is a server-based reporting platform that includes a complete set of tools to create, manage, and deliver reports, and APIs that enable you to integrate or extend data and report processing in custom applications. Reporting Services tools work within the Microsoft Visual Studio environment and are fully integrated with SQL Server tools and components.

In a Visual Studio reporting project for Microsoft Dynamics AX, you can define a report in a report model. A report consists of a collection of items, such as datasets, parameters, images, and report designs. A model can contain more than one report.

To add a report

In Solution Explorer, right-click the reporting project that you want to add a report to, point to Add, and then click Report. The report model displays in Model Editor, and the node for the report appears expanded in Model Editor.

The next steps are to define the elements that make up the report. The following list provides links to topics that describe how to define the report elements using the Visual Studio tools for Microsoft Dynamics AX.

1. Add detail to the report. You can work with data regions, display an image, and add a report or style template.
2. Add interactive features like the following:

    1. Drill down and drill up actions
    2. Document map
    3. Report parameters
    4. Dynamic filters
    5. Report filters
    6. Link to another report
    7. Link to a URL or a form
    8. Specify a chart axis value

3. Localize the report by using labels for localizable text.   
4. Deploy the report to the report server.
5. View the report in Report Manager using the URL: http://[MachineName]/reports
6. View the report in Microsoft Dynamics AX by creating a menu item for the report.

To delete a report

1. In Solution Explorer or Model Editor, right-click the report that you want to delete, and then click Delete.

public void deleteReportFile(str _ReportPath)
{
    str         ReportPath = _ReportPath;
    if(!ReportPath)
        warning("No file in local to remove");
    else
        WinAPI::deleteFile(@ReportPath);
}

Customizing Editor Control of AjaxControltoolKit in Asp.Net

Description:- 

As you can know in Ajaxcontroltoolkit lots of tools available in the editor. But sometime we require only few tools to be displayed in this editor. For that we can change the editor and override FillTopToolbar () and FillBottomToolbar () methods of editor control.

For that in the App_code folder we have to add one .cs file. And then add the namespace AjaxControlToolkit.HTMLEditor.

protected override void FillTopToolbar()
{
    TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.Bold());
    TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.Italic());
}

protected override void FillBottomToolbar()
{
    BottomToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.DesignMode());
    BottomToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.PreviewMode());
    BottomToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.HtmlMode());
}

As you can see here in the bottom toolbar we have added all three modes that is design, preview and html. But from the top we just add bold and italic.

We can use this control in asp.net page same as we use the usercontrol.

Html:-

<div>
   <asp:ScriptManager ID="ScriptManager1" runat="server">
   </asp:ScriptManager>
   <div>
      <custom:customeditor id="CustomEditor1" width="500px" height="200px" runat="server" />
   </div>
</div>

And Register MyControls in Webpage.

<%@ Register Namespace="MyControls" TagPrefix="custom" %>


Create New Webpage in that Register Ajaxcontroltoolkit and Drag ScriptManager and Editor Control.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor" TagPrefix="cc2" %>

<div>
   <asp:ScriptManager ID="ScriptManager1" runat="server">
   </asp:ScriptManager>
   <cc2:Editor ID="Editor1" Height="200" Width="450" runat="server" />
</div>
How to Convert Amount to word in Ax 2012

How to Convert Amount to word in Ax 2012

Description:- Here I have given simple demonstration to create amount to word in ax 2012. Here I have create method for return word value what you are passing amount. Create below method in your class or form and pass parameter you will get word value.

Code:-

Public str 1000 ConvertAmountInWords(real _num,str 30 subCurrency="")
{
    int     numOfPennies = frac(_num)*100 mod 100;
    int     test         = real2int(round(_num,0));
    int     paise;
    int     numOfTenths;
    str 20  ones[20], tenths[9], hundreds, thousands, lakhs, crores, millions, billions;
    str 40  textpaise;
    int     tmpnumofpennies;
    int     temp;
    str 200 returntxt;
    boolean Con2;
     int checkPower(int  _test, int _power)
     {
         int     numOfPower;

         if (_test >= _power)
         {
             Con2 = true;
             numOfPower = _test DIV _power;
             if (numOfPower >= 100)
             {
                 temp = numOfPower DIV 100;
                 returntxt = returntxt + ' ' + ones[temp] + ' ' + hundreds;
                 numOfPower = numOfPower MOD 100;
             }
             if (numOfPower >= 20)
             {
                 temp = numOfPower DIV 10;
                 returntxt = returntxt + ' ' + tenths[temp];
                 numOfPower = numOfPower MOD 10;
             }
             if (numOfPower >= 1)
             {
                 returntxt = returntxt + ' ' + ones[numOfPower];
                 numOfPower = numOfPower MOD 10;
             }
             switch(_power)
             {
                 case 1000000000 :
                 {
                     returntxt = returntxt + ' ' + billions;
                     _test = _test MOD 1000000000;
                     break;
                 }
                 case 10000000 :
                 {
                     returntxt = returntxt + ' ' + crores;
                     _test = _test MOD 10000000;
                     break;
                 }
                case 100000 :
                 {
                     returntxt = returntxt + ' ' + lakhs;
                     _test = _test MOD 100000;
                     break;
                 }
                 case 1000 :
                 {
                     returntxt = returntxt + ' ' + thousands;
                     _test = _test MOD 1000;
                     break;
                 }
                 case 100 :
                 {
                     returntxt = returntxt + ' ' + hundreds;
                     _test = _test MOD 100;
                     break;
                 }
             }
         }
         else if(_test == 0)
         {
             if(Con2 == false)
             {
                numOfPower = 20;
                returntxt = returntxt + ' ' + ones[numOfPower];// + ' ' + hundreds;
                 Con2 = true;
             }
            //break;
         }
         return _test;
     }

    ones[20] = "Zero";
    ones[1] = "@SYS26620";
    ones[2] = "@SYS26621";
    ones[3] = "@SYS26622";
    ones[4] = "@SYS26626";
    ones[5] = "@SYS26627";
    ones[6] = "@SYS26628";
    ones[7] = "@SYS26629";
    ones[8] = "@SYS26630";
    ones[9] = "@SYS26631";
    ones[10] = "@SYS26632";
    ones[11] = "@SYS26633";
    ones[12] = "@SYS26634";
    ones[13] = "@SYS26635";
    ones[14] = "@SYS26636";
    ones[15] = "@SYS26637";
    ones[16] = "@SYS26638";
    ones[17] = "@SYS26639";
    ones[18] = "@SYS26640";
    ones[19] = "@SYS26641";

    tenths[1] = 'Not used';
    tenths[2] = "@SYS26643";
    tenths[3] = "@SYS26644";
    tenths[4] = "@SYS26645";
    tenths[5] = "@SYS26646";
    tenths[6] = "@SYS26647";
    tenths[7] = "@SYS26648";
    tenths[8] = "@SYS26649";
    tenths[9] = "@SYS26650";

    hundreds    = "@SYS26651";
    thousands   = "@SYS26652";
    lakhs       = "Lakh";
    crores      = "Crore";
    millions    = "@SYS26653";
    billions    = "@SYS26654";

      test = checkPower(test, 1000000000);
     test = checkPower(test, 10000000);
     test = checkPower(test, 100000);
     test = checkPower(test, 1000);
     test = checkPower(test, 100);

     if (test >= 20)
     {
         numOfTenths = test DIV 10;
         returntxt = returntxt + ' ' + tenths[numofTenths];
         numOfTenths = numOfTenths MOD 10;
         test = test MOD 10;
     }
     if (test >= 1)
     {
         numOfTenths = test;
         returntxt = returntxt + ' ' + ones[numOfTenths];
     }
      if (numOfPennies)
     {
         returntxt = returntxt + ' ' + "@SYS5534" + "\n\n";
     }
     paise=numofPennies;
     if(paise)
     {
      if(paise >=20)
      {
       numofTenths= paise DIV 10;
       returntxt=returntxt + ' '+tenths[numofTenths];
       numofTenths = numofTenths MOD 10;
       paise=paise MOD 10;
      }
      if(paise >=1)
      {
       numOfTenths=paise;
       returntxt=returntxt+ ' '+ones[numOfTenths];
      }
      returntxt=returntxt+" Paise";
     }

    //Text =    returntxt + " Only";
    return returntxt ;}

Example:-

In my example like i m giving value of 1500.20 it will return.
"One Thousand Five Hundred And Twenty Paisa"

How to Display MasterDetail Data from a Database using ListView and GridView Control in Asp.Net

Description:-

In this post, I explain how to Display Master/Detail Data from a Database using List View and GridView Control in ASP.NET.

Step - 1: Create New Project.
Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.
Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database under Data > Enter Database name > Add.

Step-3: Create 2 table for Master Details Record.
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used table as below
-------------------------------------------------------------------------
CREATETABLE [dbo].[Table_1](
      [CID] [int] NOTNULL,
      [CustomerCode] [varchar](10)NOTNULL,
      [CustomerName] [varchar](50)NOTNULL,
      [ContactNo] [varchar](20)NOTNULL,
      [State] [varchar](50)NOTNULL,
      [City] [varchar](50)NOTNULL,
CONSTRAINT [PK_Table_1] PRIMARYKEYCLUSTERED
(
      [CID] ASC
)WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
)ON [PRIMARY]

GO
-------------------------------------------------------------------------
CREATETABLE [dbo].[Table_2](
      [OrderID] [int] NOTNULL,
      [CID] [int] NOTNULL,
      [OrderNo] [int] NOTNULL,
      [OrderDate] [datetime] NOTNULL,
      [Quantity] [int] NOTNULL,
      [UnitPrice] [numeric](12, 2)NOTNULL,
      [TotalAmount] [numeric](12, 2)NOTNULL,
CONSTRAINT [PK_Table_2] PRIMARYKEYCLUSTERED
(
      [OrderID] ASC
)WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
)ON [PRIMARY]

GO

ALTERTABLE [dbo].[Table_2]  WITHCHECKADDCONSTRAINT [FK_Table_2_Table_1] FOREIGNKEY([CID])
REFERENCES [dbo].[Table_1]([CID])
GO

ALTERTABLE [dbo].[Table_2] CHECKCONSTRAINT [FK_Table_2_Table_1]
GO
-------------------------------------------------------------------------

Step-4: Add Entity Data Model.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Choose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for show Master Details Record using List View& Gridview Control in Webpage.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

CSS Code:-

<style type="text/css">
.collapse
{
background-position: left-172px;
height: 14px;
width: 13px;
background-repeat: no-repeat;
background-image: url("DXR.png");
cursor: pointer;
}
.expand
{
background-position: -14px-187px;
height: 14px;
width: 13px;
background-repeat: no-repeat;
background-image: url("DXR.png");
cursor: pointer;
}
table
{
border: solid1pxblack;
}
tabletd
{
border-right: solid1pxblack;
border-bottom: solid1pxblack;
}
tableth
{
border-bottom: solid1pxblack;
}
.SUBDIVtable
{
border: 0px;
border-left: 1pxsolidblack;
}
</style>

Java Script Code:-
To download JQuery Refer this link http://code.jquery.com/jquery-1.7.1.js

<script src="jquery-1.7.1.js"type="text/javascript"></script>
<script language="javascript">
$(document).ready(function () {
// THIS IS FOR HIDE ALL DETAILS ROW
$(".SUBDIV table tr:not(:first-child)").not("trtr").hide();
$(".SUBDIV .btncolexp").click(function () {
$(this).closest('tr').next('tr').toggle();
//this is for change img of btncolexp button
if ($(this).attr('class').toString() == "btncolexp collapse") {
$(this).addClass('expand');
$(this).removeClass('collapse');
}
else {
$(this).removeClass('expand');
$(this).addClass('collapse');
}
});
});
</script>

Html Code:-

<div>
   <h3>
      Master Details Record using ListView & Gridview Control in ASP.NET
   </h3>
   <div>
      <asp:ListViewID="ListView1"runat="server"OnItemDataBound="ListView1_ItemDataBound">
      <LayoutTemplate>
         <tablewidth="100%"border="0"cellpadding="0"cellspacing="0">
         <tr>
            <thwidth="15px">
            </th>
            <thwidth="15%">
            Customer Code
            </th>
            <thwidth="25%">
            Customer Name
            </th>
            <thwidth="20%">
            Contact No
            </th>
            <thwidth="20%">
            State
            </th>
            <th>
               City
            </th>
         </tr>
         </table>
         <divrunat="server"id="itemPlaceHolder">
   </div>
   </LayoutTemplate>
   <ItemTemplate>
      <divid="Div1"class="SUBDIV"runat="server">
      <tablewidth="100%"border="0"cellpadding="0"cellspacing="0">
      <tr>
         <tdwidth="15px">
         <divclass="btncolexp collapse">
         &nbsp;
</div>
</td>
<tdwidth="15%">
<%#Eval("CustomerCode") %>
</td>
<tdwidth="25%">
<%#Eval("CustomerName") %>
</td>
<tdwidth="20%">
<%#Eval("ContactNo") %>
</td>
<tdwidth="20%">
<%#Eval("State") %>
</td>
<td>
<%#Eval("City") %>
</td>
</tr>
<tr>
<tdcolspan="6">
<divstyle="margin: 20px">
<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="false">
<Columns>
<asp:BoundFieldHeaderText="Order ID"DataField="OrderID"/>
<asp:BoundFieldHeaderText="Order No"DataField="OrderNo"/>
<asp:BoundFieldHeaderText="Order Date"DataField="OrderDate"/>
<asp:BoundFieldHeaderText="Quantity"DataField="Quantity"/>
<asp:BoundFieldHeaderText="UnitPrice"DataField="UnitPrice"/>
<asp:BoundFieldHeaderText="Total"DataField="TotalAmount"/>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:ListView>
</div>
</div>

Step-6: Write code in Page_Load event for fetch Master data from database and bind to List View Control for show master details record in webpage.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateData();
    }
}

private void PopulateData()
{
    using (UHEntities dc = newUHEntities())
    {
        var v = dc.Table_1.ToList();
        ListView1.DataSource = v;
        ListView1.DataBind();
    }
}

Step-7: Write code in ListView1_ItemDataBound event for fetch corresponding details record and bind it to the Gridview (inside ListView).

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItemlvItem = (ListViewDataItem)e.Item;
        Table_1cus = (Table_1)lvItem.DataItem;
        if (cus != null)
        {
            GridView gv1 = (GridView)e.Item.FindControl("GridView1");
            if (gv1 != null)
            {
                using (UHEntities dc = newUHEntities())
                {
                    var v = dc.Table_2.Where(a =>a.CID.Equals(cus.CID)).ToList();
                    gv1.DataSource = v;
                    gv1.DataBind();
                }
            }
        }
    }
}

Step-8: Run Application.