Saturday, December 2, 2017

DELPHI - How add items to TListView

Listview has 2 columns. First column value is added by Caption property, second by SubItems list.
var
  List: TListView;
  pItem : TListItem;
begin
  ..
  { first item }
  pItem := List.Items.Add;
  pItem.Caption := 'Total record count';
  pItem.SubItems.Add( IntToStr( FLocalData.TotalRecordCount ) );
  pItem.ImageIndex := 0;
  pItem.Selected := true;

  { second item }
  pItem := List.Items.Add;
  pItem.Caption := 'Record count';
  pItem.SubItems.Add( IntToStr( FLocalData.RecordCount ) );
  pItem.ImageIndex := 0;
  ..
end;

JAVA - How to use HashMap

java.util.HashMap is map with this behavior:
  • Keys can`t be duplicated.
  • Order of keys is unpredictable.
HashMap hm = new HashMap();

/* -- add keys and it values */

hm.put( "one", 1 );
hm.put( "two", 2 );
hm.put( "three", 3 );
hm.put( "three", 5 ); // exists already -> ignore
hm.put( "three", 3 ); // exists already -> ignore
hm.put( "four", null );

/* elements count */
System.out.println( "Elements count = " + hm.size() );

/* check if contains key */
System.out.println( "Contains \"one\" = " + hm.containsKey( "one" ) );

/* get value for key */
System.out.println( "\"one\" value = " + hm.get( "two" ) );

/* -- write all keys and all values */

System.out.println( "Keys = " + new ArrayList( hm.keySet() ).toString() );
System.out.println( "Values = " + new ArrayList( hm.values() ).toString() );
The output:
Elements count = 4
Contains "one" = true
"one" value = 2
Keys = [two, one, three, four]
Values = [2, 1, 3, null]
See that the order of elements are different than you have inserted. Also two items were omitted.

Friday, December 1, 2017

ORACLE - How handle pl/sql exception

Typical example for handling pl/sql exception (when no row is found in select):
is
  iCount number;
  /* take type from table field */
  iKategp factory.an_hr_table.kategp%type;
begin
...
  begin
    select kategp into iKategp
    from factory.an_hr_table 
    where
    osc = pOsc;
  exception
    when NO_DATA_FOUND then
      pErrorMessage := 'No data found for worker: ' || pOsc;
      return( -1 );
  end;
...

ORACLE - example of pl/sql function (stored function)

Stored function takes two params and returns number value (0 when row is added):
function sql_addToFavorite( pUser in varchar2, pID in number ) return number
is
  iCount number;
begin
  /* exists ? */

  select count(*) into iCount
  from factory.cieb_an_sql_favorite
  where
  upper( c_user ) = upper( pUser ) and
  c_ID = pID;

  if iCount <> 0 then
    return( 1 );
  end if;

  /* add */

  insert into factory.cieb_an_sql_favorite
  ( c_user, c_id )
  values
  ( upper( pUser ), pID );

  commit;

  return( 0 );
end;

ORACLE - How call stored pl/sql procedure/function

How to call externally pl/sql stored procedure:
declare
  i number;
  sErrorMessage varchar2(255);
begin
  /* form user.package.function */

  i := factory.cieb_inv_nv_p.CallBatchProc( '201611', 11, sErrorMessage );
end;

ORACLE - How to get substring from string

Get 2 chars from position 6:
select substr( 'This is text', 6, 2 ) from dual 
Output:
SU
--
is
1 row selected.

SQL SERVER - How get substring from string

Get 2 chars from position 6:
select substring( 'This is text', 6, 2 ) 
Output:
----
is

(1 row(s) affected)

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]