Thursday, November 30, 2017

JAVA - Hashtable, how to read java system properties

In java.lang.System class are accessible system properties. Data are saved internally in java.util.Hashtable class.

This sample code go through Hashtable and read all its keys and values.
import java.util.*;
...
/* -- get system properties */

Hashtable h = System.getProperties();

/* -- get keys */

Enumeration e = h.keys();

/* -- read and write all keys */

while( e.hasMoreElements() ) {

  /* key */
  Object k = e.nextElement();

  /* read key */
  System.out.print( k );
  /* read key value */
  System.out.println( "\t\t" + h.get( k ) );
}
The output could be (depending on installed JDK and current system):
java.runtime.name Java(TM) SE Runtime Environment
sun.boot.library.path C:\Program Files\Java\jdk1.7.0_07\jre\bin
java.vm.version 23.3-b01
java.vm.vendor Oracle Corporation
java.vendor.url http://java.oracle.com/
path.separator ;
java.vm.name Java HotSpot(TM) Client VM
...

DELPHI - How show modal form

TFMissing is class with form.
var
  FMissing : TFMissing;
begin
  FMissing := TFMissing.Create( self );
  
  { -- optional: here you can send some initial data to the form  
  FMissing.Prepare( DataColumn );
  }
  
  FMissing.ShowModal;

  { -- optional: here you have possibility read output from (closed) form   
  Grid.Cells[ _iCol, _iRow ] := pDataColumn.pMissings.GetAsString; 
  }

  FMissing.Free;
end;

DELPHI - How read image from .dll into TImageList

var
  FDLL : HMODULE;
  ImageMenu: TImageList;
begin
  { DLL preparation }
  FDLL := LoadLibrary( PChar( ExtractFilePath( Application.ExeName ) + gcsDllFile ) );
  if FDLL = 0 then
    begin
      doError( ERROR_FILE_NOT_EXIST, [ 'DLL file not found:', 'a9dll.dll' ] );
      Application.Terminate;
    end;
  ..
  { read images into ImageMenu }
  ImageMenu.Clear;
  ImageMenu.ResInstLoad( FDLL, rtBitmap, 'A_NEW16', clAqua );            {0}
  ImageMenu.ResInstLoad( FDLL, rtBitmap, 'A_OPEN16', clAqua );           {1}
  ImageMenu.ResInstLoad( FDLL, rtBitmap, 'A_SAVE16', clAqua );           {2} 
  ..
end;

SQL SERVER - select with having clause

When you need only rows, where their count in group is for example greater than 1, use this code with having clause:
select prodid, itemid, index, count(*)
from cieb_ivecofvvlabels
group by prodid, itemid, index
having count(*) > 1;
Output:
prodid               itemid                                   index       count
-------------------- ---------------------------------------- ----------- -----------
17-045164            5801-285-899_0_0000                      1           2
17-045164            5801-285-899_0_0000                      2           2
17-045164            5801-285-899_0_0000                      3           2
17-045164            5801-285-899_0_0000                      4           2
17-045165            5801-285-899_0_0000                      1           2
...
Another variant is to use subselect on base select.

Wednesday, November 29, 2017

JAVA - How to use ArrayList

Class java.util.ArrayList is very useful class for storing objects. It is replacement for Vector class. ArrayList supports null values and duplicates.
/* -- ArrayList creating  */

ArrayList ar = new ArrayList();

/* -- add items */

ar.add( "One" );
ar.add( "Two" );
ar.add( "Two" );
ar.add( null );
ar.add( "Three" );
ar.add( null );

/* -- get and write second item */

System.out.println( ar.get( 1 ).toString() );

/* -- write all items */

System.out.println( ar.toString() );
Output is:
Two
[One, Two, Two, null, Three, null]

DELPHI - How convert number to string

1) For conversion integer value to string:
var
  sValue : string;
begin
  sValue = IntToStr( 32 );
end;

2) For conversion float value to string. Last parameter is decimal point count.
FloatToStrF( FLocalData.PrepareTime / 1000, ffFixed, 15, 2 ) 

DELPHI - How format float value to string

EFreeMemory.Text := FormatFloat( '########,### KB', ms.dwAvailPhys / 1024 );

DELPHI - How properly close non-modal window

Override event FormClose:
procedure TFGauge.FormClose( Sender: TObject; var Action: TCloseAction );
begin
  Action := caFree;
  self   := nil;
end;

AX - How generate random int value

info( int2str( xGlobal::randomPositiveInt32() ) );

AX - How check if configuration key is enabled

info( xGlobal::isConfigurationkeyEnabled( configurationKeyName2Id( "Prod" ) ) ? "Yes" : "No" );

AX - Build-in functions for filters

For filters in AX you can use build-in functions:








  • (today()) - current day.
  • (day(-1)) - yesterday.
  • (day(1)) - tomorrow.
  • (day(-4)) - current day -4 days.
  • (dayrange(-7,7)) - date interval -7 days .. +7 days.
  • (monthrange(-1,-1)) - like previos, but months.
  • (yearrange(0,1)) - like previos, years.
  • (lessthandate(-5)) - less than current day -5 days.
  • (greaterthandate(5)) - greater than current day +5 days.

More advanced functions (class SysQueryRangeUtil):

  • (currentWorkerRecId()) - db recid of current user.
  • (getActiveMasterPlanVersionByPlanId( "MAINPLAN" )) - returns master plan.
  • (documentStatusPurchOrderOrGreater()) - purchase order status  DocumentStatus::PurchaseOrder or high.
  • (currentWorker()) - HcmWorkerRecId of current user.
  • (currentUserLanguage()) - language of current user.
  • (currentUserId()) - current user.

+ several more.

JAVA - How restart java application

public void restartApplication() throws URISyntaxException, IOException
{
  /* where is java and local app ? */    

  final String javaBin = System.getProperty( "java.home" ) + File.separator + 
                         "bin" + File.separator + "java";
  final File currentJar = new File( getClass().getProtectionDomain().getCodeSource()
                          .getLocation().toURI() );

  /* is it a jar file ? */

  if( !currentJar.getName().endsWith(".jar") ) return;

  /* build command: java -jar application.jar */

  final ArrayList command = new ArrayList();
  command.add( javaBin );
  command.add( "-jar" ); command.add( currentJar.getPath() );

  /* run it - and close current */

  final ProcessBuilder builder = new ProcessBuilder( command );
  builder.start();
  System.exit(0);
}

Tuesday, November 28, 2017

JAVA - How to make custom array sorting

In some situation is necessary make own custom sorting function. For this reason use class java.util.Comparator. In this class instance you must override compare() function.
/* -- array - one item with small first letter */

String[] array = { "one", "Two", "Three", "Four", "Fight" };

/* -- regular sorting */

Arrays.sort( array );

System.out.println( Arrays.toString( array ) );

/* -- sorting with own sorting function (ignoring letter size) */

Arrays.sort( array, new Comparator() {
  @Override
  public int compare( String s1, String s2 ) {
    return( s1.compareToIgnoreCase( s2 ) );
  }    
});

System.out.println( Arrays.toString( array ) );
The output is:
[Fight, Four, Three, Two, one]
[Fight, Four, one, Three, Two]
First output row is regular sorting. Second row is our custom sorting function that ignores letter case size.

JAVA - How to sort array elements in descending order

For sorting array elements use class java.util.Arrays. This class contains static methods for work with arrays.
String[] array = { "One", "Two", "Three", "Four", "Fight" };

Arrays.sort( array, Collections.reverseOrder() );

System.out.println( Arrays.toString( array ) );
For descending sorting use comparator Collections.reverseOrder().

Output is:
[Two, Three, One, Four, Fight]

AX - How get customer name in external SQL select

select a.accountnum, b.name from custTable a
join dirPartyTable b
on b.recid = a.party
where
a.accountnum like 'MINSK32680'
Output:
accountnum           name
-------------------- -------------------------
MINSK32680           MINSK WHEEL TRACTOR PLANT

(1 row(s) affected)

ORACLE - How use conditional logic in select, decode() statement

When is in field pos_dbf_ze value "HO" (=hour) is used pos_bdf_mz. In another case is pos_bdf_mz divided by value 60.
select sum( decode( pos_bdf_ze, 'HO', pos_bdf_mz, pos_bdf_mz/60 ) )
from aukabl
where 
arb_ord_nr like '16%'

SQL SERVER, ORACLE - How use conditional logic in select, case statement

Prevention zero divide error:
select b.inventlocationid, itemid, a.availphysical, a.postedqty, 
a.postedvalue / case 
                  when a.postedqty = 0 then 1 
                  else a.postedqty 
                end as cost_avg_mj
from inventsum a
join inventdim b
on b.inventdimid = a.inventdimid and
b.dataareaid = a.dataareaid
where
a.itemid like 'S-%' and
a.availphysical <> 0

Monday, November 27, 2017

JAVA - How to create multidimensional array

/* -- declaration and initialization of multidimensional 2D array */

int[][] doubleArray = 
{
  { 1, 3, 5 },
  { 2, 4, 6 }
};

/* -- go through multidimensional array (by rows) */

for ( int iRow = 0; iRow < doubleArray.length; iRow++ ) {   
  int[] iArray = doubleArray[ iRow ];          

  System.out.println( Arrays.toString( iArray ) );     
} 
Output:
[1, 3, 5]
[2, 4, 6]

DELPHI - How copy file

First parameter is source file, second parameter is target location.
_sFileName : string
..
copyfile( PChar( _sFileName ), PChar( IncludeTrailingPathDelimiter( EPath.Text ) + 
          ExtractFileName( _sFileName ) ), false );

SSRS - How define expression for background color

In BackgroundColor property set expression:
= IIF(Fields!COUNT_DELAY.Value > 0, "Red", "SeaGreen")

AX - Error "An error occurred rendering the report. Accessing the report server URL caused an error. The remote server returned an error: (500) Internal Server Error."

This error inform you that connection between AX and SSRS was lost.















The solution should be:
  1. Stop AOS.
  2. Restart SSRS Reporting Service.
  3. Start AOS.

AX - How generate datetime with to 23:59:59 PM

Use this code (1 hour = 3600 seconds):

utcDateTime dDate = DateTimeUtil::newDateTime( today(),  3600 * 24 - 1 );
    
info( datetime2str( dDate ) );


AX - How add (next) row to StringEdit control

Used for example for logs.
  1. Add StringEdit control to form.
  2. Set name and set Autodeclaration to Yes.
  3. Set Multiline to Yes.
void AddText( str _sValue ) {
  EOutput.text( EOutput.text() + _sValue + num2char(10) );
}

AX - How pass table (datasource) as param to form

In menu item on caller form you must define DataSource property:







This ProdTable will be passed as parameter to called (here) form.

In called form you override init() method:

FormRun callerForm;
FormDataSource callerDataSource;
...
public void init()
{
    super();

    if ( element.args() && element.args().caller() )
    {
        callerForm = element.args().caller();

        if ( callerForm && callerForm.dataSource() ) {

            /* -- save DataSource */

            callerDataSource = callerForm.dataSource();

            /* -- call check method */

            this.check();
        }

    }
}

Sunday, November 26, 2017

JAVA - How to go through an array

Several method:

Variant 1

String[] array = new String[3];

array[0] = "One";
array[1] = "Two";
array[2] = "Three";

for ( int i = 0; i < array.length; i++ )
  System.out.println( array[i] );
Output is:
One 
Two 
Three 
Variant 2

String[] array = new String[3];

array[0] = "One";
array[1] = "Two";
array[2] = "Three";

for ( String item : array )
  System.out.println( item );

NOTE: Every next loop is into item variable filled next array item.

Saturday, November 25, 2017

DELPHI - How to generate file with record based type

When you need save some complex record type to file you can use this code:

{ header of admin file }
TRecFileAdmin = record
  sIdent              : string[15] ;
  dDateTo             : TDateTime;
end;
...
{ ---------------------------------------------------------------------------
  Function generate admin file into _FileName file.
  -------------------------------------------------------------------------- }
function GenerateAdminFile( _sFileName : string ) : boolean;
var
  f : TFile;
  recFileAdmin : TRecFileAdmin;
begin
  result := false;

  try
    try
      { every time establish new }
      f := TFile.Create( _sFileName, true );

      { three day validity }
      FillChar( recFileAdmin, sizeof( recFileAdmin ), 0 );
      recFileAdmin.sIdent  := gcsIdent;
      recFileAdmin.dDateTo := Now + 3;  
      f.FileWrite( recFileAdmin, sizeof( recFileAdmin ) );
    except
      on E : exception do
        begin
          doError( ERROR_SAVE, [ 'A9Admin.GenerateAdmin()', E.Message ] );
          exit;
        end;
    end;
  finally
    f.free;
  end;

  result := true;
end;

DELPHI - How get total physical memory and memory in use

LPhysMem: TLabel;
LMemoryInUse: TLabel;
MS : TMemoryStatus;
...
GlobalMemoryStatus( MS );
LPhysMem.Caption := FormatFloat( '#,###" KB"', MS.dwTotalPhys / 1024 );
LMemoryInUse.Caption := Format( '%d %%', [ MS.dwMemoryLoad ] );

It shows for example:



Friday, November 24, 2017

JAVAFX - How to play (youtube) video

/* control on form for media video */
private MediaView mediaView;
..
MediaPlayer mediaPlayer = new MediaPlayer( 
  new Media( "https://www.youtube.com/watch?v=gvKgvW9ujHo" ) );
MediaView.setMediaPlayer( mediaPlayer );            
MediaView.getMediaPlayer().play();

JAVAFX - How get Stage from control

From control you can get Stage; here used for form closing:
@FXML Button btnClose;

@FXML private void btnCloseAction( ActionEvent event ) {
  Stage stage = (Stage) btnClose.getScene().getWindow();    
  stage.close();    
}

Thursday, November 23, 2017

JAVA - How to quickly list (all) array elements

For quickly list array elements use class java.util.Arrays. This class contains static methods for work with arrays.
String[] array = new String[3];

array[0] = "One";
array[1] = "Two";
array[2] = "Three";

System.out.println( Arrays.toString( array ) );
The output is:
[One, Two, Three]

JAVA - How to copy array values between arrays

For copy array values between two arrays use System.arraycopy():
String[] array = new String[3];  

array[0] = "One"; 
array[1] = "Two"; 
array[2] = "Three"; 

String[] array1 = { "1", "2", "3" };

System.arraycopy( array1, 1, array, 0, 2 );

for ( int i = 0; i < array.length; i++ ) System.out.println( array[i] ); 
In this example are copied values of array1 (first param) from index 1 (second param) into array (third param). First value is inserted into 0 index (fourth param), copied are two (fifth param) items.

The output is:
2 3 Three

ORACLE - How get info about table

desc himtbw

Result (⇒information about himtbw table):

SQLWKS> desc himtbw
Column Name                    Null?    Type
------------------------------ -------- ----
TL_NR                          NOT NULL VARCHAR2(20)
TL_FAM                         NOT NULL VARCHAR2(6)
TL_ATN                         NOT NULL VARCHAR2(6)
BEW_MNG_MZ                              NUMBER(10,3)
BEW_MNG_ME                              VARCHAR2(2)
LAG_ORT                                 VARCHAR2(16)
LAG_REIHE                               VARCHAR2(2)
...

AX - How get list of active AX users

select a.id, a.name, substring( a.networkdomain, 1, 25 ) as networkdomain,
substring( a.networkalias, 1, 25 ) as networkalias
from [dbinst].[dbo].userinfo a
where
a.enable = 1
order by a.id

AX - How get aggregate select value - max(), count()

For aggregate x++ select functions you can use this form:
calcDate = ( select maxof( calcdate ) from ProdParmBomCalc 
where ProdParmBOMCalc.ProdId == source.TransRefId ).calcdate;
Supported aggregate functions: sum, avg, minof , maxof, count.

For count function you can use this code:
int iCount;

iCount =
  ( select count(recId) from prodRoute
    where
    prodRoute.ProdId == source.ProdId &&
    prodRoute.OprPriority == RouteOprPriority::Primary 
  ).recId;
        
if ( iCount != 0 ) {
  bError = true;            
}

AX - How set number sequence generation to manual

When you don`t want automatically generate number sequence, you can set it to manual (= manual inserting).
  • In area setup part select preferences dialog and find number sequence. Click View details for it.
  • In sequence set generation type to Manual.

AX - How call form with param

Calling form with passing parameter - here it is one passed value (ProdId type):
void Check()
{
  Args args;

  FormRun formRun;

  /* -- call check form */

  args = new args();

  if ( jmgJobTable )
    args.parm( JmgJobTable.ModuleRefId );
  else
    args.parm( "" );

  ags.name( formstr( CheckBus ) );
  formRun = classFactory.formRunClass( args );
  formRun.init();
  formrun.run();
  formrun.wait();
}
..and here is receiving part - in form init() method:
public void init()
{
  ProdId prodId;

  super();

  if( element.args() )
  {
    /* -- get param value */

    prodId = element.args().parm();     
    EProdId.text( prodId );
    EOutput.text( "" );

    EProdId.setFocus();
  }
}

Wednesday, November 22, 2017

JAVA - How to sort array elements

For sorting array elements use class java.util.Arrays. This class contains static methods for working with arrays.
String[] array = { "One", "Two", "Three", "Four", "Fight" };

Arrays.sort( array );

System.out.println( Arrays.toString( array ) );
The output is:
[Fight, Four, One, Three, Two] 
NOTE: This is the most simplest variant of array sorting.

JAVA - How to create array

Exists several ways for creating java array.

Variant 1

/* creating */ 

String[] array = new String[3];

/* initialization */ 

array[0] = "One"; 
array[1] = "Two"; 
array[2] = "Three";

Variant 2

String[] array = { "one", "two", "three" };

NOTE: Arrays are indexed from zero [0]. When you use non-existed index is raised java.lang.ArrayIndexOutOfBoundsException exception.

AX - How check if current user is SysAdmin

This code check, if current AX user is in System Administrator group:
if ( isSystemAdministrator() ) { ... }

AX - How check if (current) user is in group

AX 2012 define user groups (System administration\User groups):



if ( UserInfoHelp::userInUserGroup( curUserId(), 'PLANNING' ) ) { ... }

AX - How get enum labels to db table

When you have AX enum, often you need to read its labels externally - for example in SQL question.

In AX exists table SRSAnalysisEnums, which contain enum name, enum value and its label.
select * from SRSAnalysisEnums
where
enumname = 'NoYes' and
languageid in ( 'de', 'en-us' )
Output:
ENUMITEMVALUE ENUMITEMLABEL LANGUAGEID ENUMNAME ENUMITEMNAME RECVERSION RECID

0 Nein de NoYes No 1 5637179205
0 No en-us NoYes No 1 5637144576 1
Ja de NoYes Yes 1 5637179250 1 
Yes en-us NoYes Yes 1 5637144577
For rebuild this table (->new enum in AX) you can use class BIGenerator, method populateSRSAnalysisEnums(). Implicitly are generated enums from tables in AX BI perspectives.
static void cieb_updateSSRSEnums(Args _args)
{
    BIGenerator::populateSRSAnalysisEnums();
    info( "OK" );
}
Explicitly you can change in inner method addFrameworkEnumsToDictEnumSet(), where you can define some others special enums for SRSAnalysisEnums table:
void addFrameworkEnumsToDictEnumSet()
{
    addEnumToDictEnumSet(new DictEnum(enumNum(boolean)));
    addEnumToDictEnumSet(new DictEnum(enumNum(NoYes)));
    addEnumToDictEnumSet(new DictEnum(enumNum(AutoNoYes)));

    /* -- added - start */
    addEnumToDictEnumSet( new DictEnum( enumNum( cieb_technology_sale_type_enum ) ) );
    addEnumToDictEnumSet( new DictEnum( enumNum( cieb_technology_type_enum ) ) );
    addEnumToDictEnumSet( new DictEnum( enumNum( cieb_technology_type1_enum ) ) );
    /* -- added - end */

    addEdtEnumToDictEnumSet(new DictType(extendedTypeNum(BIIsNotApplicable)));
}

AX - Where are defined languages for BI generation

When you regenerate BI table SRSAnalysisEnums, languages for regeneration are defined in table BIUdmTranslations:
select * from BIUdmTranslations
where
generate = 1
Output:
LANGUAGEID GENERATE    RECVERSION  RECID
---------- ----------- ----------- --------------------
cs         1           1963884511  5637144578
en-us      1           2063432002  5637144591

2 row(s) affected)

Tuesday, November 21, 2017

SQL SERVER - How get info about table

Very easy SQL server command (stored procedure):
exec sp_help prodtable


AX - How check if DateEdit control is empty

if ( EDates.dateValue() == dateNull() ) {
  error( "Date value is empty." );
  EDates.setFocus();
}

AX - empty code

For empty code use method exceptionTextFallThrough():
if ( RDates.selection() == ProdRouteCardForm_Dates::BySchedule ) {
  exceptionTextFallThrough();
}

AX - How to get first and last day in month

Use this code:
int iMonth = 6;
int iYear = 2017;

date firstDate = mkDate( 1, iMonth, iYear );
date lastDate = endMth( firstDate );

info( date2str( firstDate, 321, DateDay::Digits2, DateSeparator::Hyphen, DateMonth::Digits2, 
      DateSeparator::Hyphen, DateYear::Digits4 ) );
info( date2str( lastDate, 321, DateDay::Digits2, DateSeparator::Hyphen, DateMonth::Digits2, 
      DateSeparator::Hyphen, DateYear::Digits4 ) );