24 Dec 2015

Time in seconds,minutes and hours + AX2012

Execute the code in job

static void Job39(Args _args)
{
    TimeOfDay  time= timeNow();
    int  hour;
    Minutes  minutes;

    minutes = time/60;  //minutes
    hour = minutes/60;  //hours

    info(strFmt("second:%1, Minutes :%2 hour:%3 ",time,minutes, hour));
}
You will get output like

O/P
second:64490, Minutes :1074 hour:17

Note::Output as per my current time.

1 Dec 2015

Finding primary key in a table + AX 2012


DictTable dictTable;
DictField dictField;
;
dictTable = new SysDictTable(tableNum(CustTable));
dictField = new SysDictField(dictTable.id(), dictTable.primaryKeyField());
info(dictField.name());

5 Nov 2015

Sorting Data in containers + AX 2012


Sorting the elements in the container .

Wrote this code in Job.

static void LegendContainerSort(Args _args)
{
container con = [999,9,9999,"Suresh",99, "Legend", "Bala", NoYes::No];
str temp1;
str temp2;
int i;
int j;
container sorCon;
;

sorCon = con;

// Sort the container
for (i = 1; i <= conlen(sorCon); i++)
 {
      for (j = i + 1; j <= conlen(sorCon); j++)
        {
             temp1 = conpeek(sorCon, j);
             temp2 = conpeek(sorCon, i);
            if (temp1 < temp2)
                {
                     sorCon = condel(sorCon, j, 1);
                     sorCon = conins(sorCon, j, temp2);
                     sorCon = condel(sorCon, i, 1);
                     sorCon = conins(sorCon, i, temp1);
                }
        }
  }
 conview(sorCon);
}

27 Oct 2015

Delete enum value at run time + AX 2012

Example:: ENUM has 3 values like

Enum::value1
Enum::value2
Enum::value3
combobox:enter()
{
super();
this.delete(enum2str(Enum::value2));
}

13 Oct 2015

Report empty display message like "No data found in SSRS" + AX 2012

In the property window  Visual studio (SSRS) check 'NoRowsMessage' property for tablix. You can set this property to show a custom message when no row is returned.
NORowsMessage = "No data available for current filter selection" //user defined msg that is to be displayedYou can also specify the specific font style like size, color, format etc.
Add a text box with expression =IIF(Count(<SomeId Field>,"DataSet1")=0,"No Data Returned", nothing)

                                                      (OR)

In the table header (header fields), use expression for each of the column headers to Set the visibility to false 
so that the end user won’t be able to see the table header when there is no data.
set the visibility of this textbox as =IIF(Count(<SomeId Field>,"DataSet1")=0,False,True)

24 Sept 2015

How to give null/ space if values is zero in SSRS + AX 2012

 Just enter the expression in SSRS


=iif(Fields!FieldName.Value > 0,  Fields!FieldName.Value,  space(0))

24 Aug 2015

languageBasedDateFormat + AX 2012

static void LegenderlangBaseDateFormat(Args _args)

{

    int     sequence;

    int     dayformat;

    int     separator1;

    int     monthformat;

    int     separator2;

    int     yearFormat;

    LanguageId  lanId;


    lanId = CompanyInfo::languageId();

    

    switch (lanId)

    {

        case "en-us":

            sequence = 123;

            dayformat =  DateDay::Digits2;

            separator1 = DateSeparator::Slash;

            monthformat = DateMonth::Digits2;

            separator2 = DateSeparator::Slash;

            yearFormat = DateYear::Digits4;

        break;


        case  "en-gb":

            sequence = 321;

            dayformat =  DateDay::Digits2;

            separator1 = DateSeparator::Slash;

            monthformat = DateMonth::Digits2;

            separator2 = DateSeparator::Slash;

            yearFormat = DateYear::Digits4;

        break;

    }



    print systemDateGet();

    print date2Str(systemDateGet(), sequence, dayformat, 

                   separator1,monthformat, separator2, 

                   yearFormat);

    pause;



}

21 Jul 2015

Increment Linenum field + AX 2012


 Step::1 Drag LineNum EDT to the fields node of your table.




Step::2  Create an index on your table and drag the LineNum field to this index


Step::3 While defining the datasource on your form,
  1. Set Table to your table
  2. Set Index to the index you created which contains the LineNum field
  3. Set CounterField to LineNum

Step::4 Override the create() method on your form’s datasource and set the default value of append parameter to be False.




That's it....now you can check Output.

17 Jul 2015

Color window + AX 2012

Write this code in job.

static void colors(Args _args)

{
    #DEFINE.COLORVALUE (64)
    int             r, g, b;
    container       chosenColor;
    Binary          customColors        = new Binary(#COLORVALUE);
    CCColor         colorValue;
    chosenColor = WinAPI::chooseColor(infolog.hWnd(), r, g, b, customColors, true);
    if (chosenColor)
    {
        [r, g, b] = chosenColor;
        colorValue  = WinAPI::RGB2int(r, g, b);
        print (colorValue);
        pause;
    }
}

24 Jun 2015

How and use close method in a form + AX 2012

Called when a form is closed.

 when closing a form according to records in a grid of a table we update records in another table.

public void close()
{
    ThyProjForcasTable          ProjForcasTable;
    ;
    super();
    ttsbegin;
    while select ProjForcasTable
        where ProjForcasTable.ProjId == ThyProjForcasTable.ProjId
    {
        if (ProjForcasTable.NoYesId == NoYes::No)
        {
            select forupdate projTable
                where projTable.ProjId == ThyProjForcasTable.ProjId;
        Projtable.Status = ProjStatus::Created;
        Projtable.update();
        }
    }
    ttscommit;
}

18 May 2015

Creating Ledger Dimension Using a segmented entry control + ax 2012

  • Segmented entry control can simplify the task of entering complex main account and dimension combinations. 
  • The control consists of a dynamic number of elements named segments. The number of segments may vary, depending on the setup, and their lookup values may be dependent on the values specified in other segments in the same control. 
  • The segmented entry control always uses the controller class, which handles the entry and display in the control.
Example 
  • LedgerParameters table and create a new field with the following properties (click on Yes to automatically add a foreign key relation once asked):


  • Find the table's relation named DimensionAttributeValueCombination, and change its property as follows:


  • In  LedgerParameters form, and add the following code to its classdeclaration():
            LedgerDimensionAccountController ledgerDimensionAccountController;


  • following code to the bottom of the form's init() method.




  • Locate the General_LedgerDimension segmented entry control located in Tab | LedgerTab | LedgerTabBody | LedgerTabFastTab | GeneralTabPage | General, and override methods.




public void loadAutoCompleteData(LoadAutoCompleteDataEventArgs _e)
{
super(_e);
ledgerDimensionAccountController.loadAutoCompleteData(_e);
}

public void loadSegments()
{
super();
ledgerDimensionAccountController.parmControl(this);
ledgerDimensionAccountController.loadSegments();
}

public void segmentValueChanged(SegmentValueChangedEventArgs _e)
{
super(_e);
ledgerDimensionAccountController.segmentValueChanged(_e);
}






On the same form, in its LedgerParameters data source, locate the
LedgerDimension field, and override three of its methods with the following code:


public Common resolveReference(
FormReferenceControl _formReferenceControl)
{
return ledgerDimensionAccountController.resolveReference();
}

public void jumpRef()
{
super();
ledgerDimensionAccountController.jumpRef();
}

public boolean validate()
{
boolean ret;
ret = super();
ret = ledgerDimensionAccountController.validate() && ret;
return ret;
}






Output




4 May 2015

Get Dimensions(Department) in SSRS Report + AX 2012

public Name GetDepartmentName (DimensionDefault _dimension)
{
      Name                                 displayName;
      DimensionAttributeValueSetItem      valueSetItem;
      DimensionAttribute                  dimAttribute;
      DimensionAttributeValue             dimAttributeValue;
      //CustInvoiceLine                        _custInvoiceLine;
      //CustInvoiceTable                       CustInvoiceTable;


     select DimensionAttributeValueSet from valueSetItem
            where valueSetItem.DimensionAttributeValueSet == _dimension
                    join RecId from dimAttributeValue
                        where valueSetItem.DimensionAttributeValue == dimAttributeValue.RecId
                            join RecId from dimAttribute
                                where dimAttributeValue.DimensionAttribute == dimAttribute.RecId
                                      && dimAttribute.Name == enum2str(sysdimension::Department);

     displayName = DimensionAttributeValue::find(dimAttributeValue.RecId).getName();
    return displayName;
}

10 Apr 2015

Restrict user login + AX 2012

Following Code in startupPost method of info class in AOT


void startupPost()
{
// To restrict user login form second login
xSession session;
SysClientSessions SysClientSessions;
UserId currentUserId;
int counter;

;

currentUserId = curUserId();

if(currentUserId!="Admin")// Allow Admin User to login multiple time
{
while select SysClientSessions
where SysClientSessions.userId == currentUserId &&
SysClientSessions.Status == 1 // 1 : Login 0 : Logout
{
session = new xSession(SysClientSessions.SessionId, true);
if (session && session.userId())
{
counter++;
}
}

if(counter>=2)
{
Box::stop("Already Logged-in : The same user id can't log in twice.");
infolog.shutDown(true);
}
}
}

30 Mar 2015

Open table through code + ax 2012

static void OpenTableShareing(Args _args)

{
SysTableBrowser sysTableBrowser = new SysTableBrowser();
;

sysTableBrowser.run(tablenum(HCMWorker));
}

17 Mar 2015

Select statement using as a function + AX 2012

public static Name name(ProjId _projId)
{
ProjName projName = ”;
if ( _projId )
{
    projName = (select projTable where projTable.ProjId == _projId).Name;
}
return projName;
}

3 Mar 2015

Few Features AX 2012 R3


  • A completely new, HTML5 based mobile Point-of-Sale (mPOS or New POS as it is sometimes called) has been developed, that runs on Windows, IOS and Android.
  •  A completely new, HTML5 based mobile client ling platform has been developed which again runs on Windows, IOS and Android.
  • A new, sophisticated ecommerce platform has been developed through SharePoint.
  • Enhancements and features have been added to Analysis, Business Intelligence and Reporting. 
  • Integration and Electronic Data Interchange (EDI) sees a new, even more flexible framework that further extends integration, performance and reliability when working with external systems. 
  • The Dynamics AX Sure Step implementation methodology will support Agile. 
  • The development platform is receiving new features that make more modern development practices such as Continuous Integration a possibility.

17 Feb 2015

Filtering data in a grid based on parameter passed from one form to another form


You need to override the init method of the data source of your form following this way for example:

public void init()
{

    SysDimension        SysDimension;
    ;
    super();

    if( element.args().parm())

    {

        SysQuery::findOrCreateRange(this.query().dataSourceTable(tablenum(Dimensions)),      fieldnum(Dimensions, DimensionCode)).value(queryValue(element.args().parm()));

    }

    else

    {

        SysQuery::findOrCreateRange(this.query().dataSourceTable(tablenum(Dimensions)), fieldnum(Dimensions, DimensionCode)).value(queryValue(SysDimension::Department));
    }
}

28 Jan 2015

Pass values between form and report +AX

Here is for example the code of the button that calls the report:

void clicked()
{
Args args;
ReportRun reportRun;
;
super();
args = new Args();
args.name(Reportstr(HistoryHolidays));
args.parm( LogId );
reportRun = classfactory.reportRunClass(args);
reportRun.init();
reportRun.run();
reportRun.wait();
args.parmObject( args );
}

in the init method of your report try this:

public void init()
{
if( element.args() )
{
logId = element.args().parm();
}
super();
}

then you can use this parameter in your report form example:

public void executeSection()
{
;

if ( employee_1.LogId == logId)
{
emplId = employee_1.empId;
super();
}
if ( logid == "1")
{
emplId = DropHoliday_1.EmpId;
super();
}

}

Pass parameters between class and report +AX

Suppose that you have a RunBase class that call for a report .
You can use methods and parameters from this class into your report.
then in the init method of your report use this :

public void init()
{
// NoYes test;
super();
myCaller = this.args().caller();

if (myCaller)
{
if (myCaller.parmPayrollJobTable())
{
if(!myCaller.parmPayrollJobTable().PayrollClosed)
{
//BP Deviation Documented
payslipJour.setTmp();
//BP Deviation Documented
payslipTrans.setTmp();
payslipJour.setTmpData(myCaller.parmTmpPayslipJour());
payslipTrans.setTmpData(myCaller.parmTmpPayslipTrans());
thisEmplQueryRun = new QueryRun(myCaller.queryRun().query());
}
emplSet = myCaller.parmEmplSet();
}
}
else
{
throw error("@PAY3089");
}
}

5 Jan 2015

Incremental CIL and Full CIL - AX 2012

 what is CIL? CIL stands for Common Intermediate Language and it works together with the CLI or Common Language Infrastructure, which is basically a set of rules on programming languages that will compile with the CIL. I created a diagram to help me understand this concept on a visual way.


When you write code in Visual Studio (VS) you can write in many different languages, Visual Basic, C#, F# - there are lots of choices. In VS when you build or compile your project

those languages are all mapped down to a different language - the Common Intermediate Language. That means if you are writing in Visual Basic your if/else statement in Visual Basic becomes whatever the equivalent is in CIL. The Common Language Runtime (CLR) that ships with .NET understands the Common Intermediate Language and knows how to execute that code. The CLR does not need to understand all of the different languages (like C#, VB or F#) it needs to only understand the one language they all get mapped down to, CIL.


In AX you program in X++ and the equivalent of AX's CLR is the kernel. When you build or compile your X++ code it traditionally gets mapped down to a p-code language that the kernel understands and knows how to execute. In AX 2012 for certain classes that is what has changed. Now when you compile the X++ code gets mapped down to the Common Intermediate Language. Then the CLR understands what the code says and executes it - the kernel is not needed.


Please note that I took the diagram from a book, but I modified it to my own needs.







As you can see, now we have the ability to compile P-Code to CIL, and therefore AX 2012 is able to run X++ code directly into the CIL, which is much faster the P-Code compiler we had before.


n AX 2012 there are two different kinds of compiles you can run: a full or an incremental compile. A full compile goes through all of the X++ code in your AX environment and compiles the classes that run in batch and service classes down to CIL. A full IL compile takes a lot of memory! You'll need at least 4 gig of memory free on the machine and I'd get more if you can. If you are trying to run a full IL compile and your system keepscrashing, you need more memory. An incremental compile maps all of the service classes and classes running in batch to CIL that have changed since you last ran a IL compile. While you are doing development work you generally only need to do an incremental compile since when your system was installed part of the checklist involves running a full compile.


Clearly incremental CIL and the full CIL compilation. The major difference between the two of them is that the incremental CIL would compile only the objects that were modified since the last incremental compilation. For what I have learned, the full CIL generation is mandatory when we do modify anything on the XppIL folder.


If you are having problems doing an incremental compile I would dig into whatever errors the compiler is giving you, you probably have something wrong in your code. When you build your code with the X++ compiler (the compile button on the toolbar) that compiler is less stringent about what qualifies as a compile error than the IL compiler is. If the X++ compiler compiles successfully but when you go to the Build > Generate Incremental CIL option it fails, you likely have an issue in your code. Look at which line the error message says is wrong in the description field of the output and not at the line field.


if you get IL compilation errors you should stop and figure them out before you proceed. If your code does not compile, you will run into issues where you have modified a class but your modifications are not being used or when you call a service it does not see your changes.
Your changes are not being seen because they have not yet been compiled down to IL code and therefore the CLR does not see them and is not trying to execute them.


On the XppIL folder, I noticed that we have a bunch of files there. These files are NetModule type files and they only contain type metadata and compiled code. It is important not to confuse a NetModule type file with .NET assemblies, as these contain and assembly manifest and managed code.






Now the really interesting portion of this is that within the XppIL folder there is a folder named “source”, and within this folder we find a bunch of files with the .xpp extension, which have x++ source code and are used to debug CIL code in Visual Studio when working with services and batches.









Further, another interesting point to this is that the “existence” of the source folder is directly related to our server configuration when choosing to enable debugging on the server.


2 Jan 2015

Terms and Explanation Models + ax 2012

Terms and Explanations for each term.
Term
Definition
Metadata
Information about the properties or structure of data in the Application Object Tree (AOT) that is not part of the data values. Everything in the AOT is metadata.
Application layer
A single layer of the Microsoft Dynamics AX 2012 application within a model store. Elements in higher layers override elements in lower layers.
Model
A named set of elements in a given application layer. Each layer consists of one or more models, of which one is a system-generated layer model.
Model element
A single piece of metadata. For instance, a table definition is a model element. Any one element in a layer belongs to exactly one model; that is, no element can belong to two different models nor can it belong to any model.
Model file (.axmodel)
A model that has been exported from a model store. This file is the chief vehicle of metadata deployment in Microsoft Dynamics AX 2012.
Model store file (.axmodelstore)
A complete model store that has been exported from the database. The file includes all metadata, compiled artifacts, CIL code, and security artifacts. The file is used for moving consistent metadata between environments with minimum downtime.
Model store
A collection of tables in the Microsoft Dynamics AX 2012 database that house the application metadata. The model store is analogous to the AOD file share in Microsoft Dynamics AX 2009.
Generated data
Data that is generated by Microsoft Dynamics AX during development.
Transactional data
Data that describes business transactions and the state of the business.
Configuration data
Data concerning how Microsoft Dynamics AX 2012 is configured. This data includes the following subcategories:
Environment: Computer-environment–specific data. An example of environment data is the list of servers running Microsoft SQL Server® Reporting Services that Microsoft Dynamics AX 2012 is configured to use. If this data is moved, it needs to be corrected to account for new server locations.
System: Parameter settings for the Application Object Server (AOS) such as which database to connect to, or for Enterprise Portal forms.
Application: Number sequences, invoicing profiles, or other data that relates directly to the application.
Reference data
Data that is characterized by shared read operations and infrequent changes. Examples of reference data include flight schedules and product catalogs. Windows Server® AppFabric offers the local cache feature for storing this type of data.
Master data
The critical data of a business, such as customer, product, location, employee, and asset. Master data falls generally into four groupings: people, things, places, and concepts. It also can be further categorized. For example, within people, there are customer, employee, and salesperson categories. Within things, there are product, part, store, and asset categories. Within concepts, there are categories like contract, warrantee, and licenses. Finally, within places, there are office location and geographic division categories.
Definition group
A collection of tables that defines what will be exported by using the data export feature.
Common Intermediate Language (CIL)
The Common Intermediate Language instruction set is part of the specification of the Common Language Infrastructure from Microsoft and is more widely known as .NET. An older name for CIL was Microsoft intermediate language (MSIL).

Table names and Total number of record of AOT + AX 2012

Table names and Total number of record of AOT in axapta you can write following code in job .

#AOT Name TableName;
NumberOf TotalRecord;
TrNode TrNode;
SysDictTable SysDictTab;
;
TrNode = TrNode::findNode(#TablesPath);
TrNode = TrNode.AOTfirstChild();
while (TrNode)
{
TableName = TrNode.AOTname();
SysDictTab = SysDictTable::newTableId(TrNode.applObjectId());
TotalRecord = SysDictTab.recordCount(false);
if (TotalRecord)
info (strfmt("Table Name - Record count", TableName, TotalRecord));
TrNode = TrNode.AOTnextSibling();
}

Create number sequence in D365 FO

Create the data type. Add code in the loadModule method of the appropriate NumberSeqModule subclass. Add a method to the module’s paramet...