Saturday, December 9, 2017

JAVA - How get installed Java version

Run cmd.exe (on Win).
java -version
Output:
C:\>java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

JAVA - How to format currency

double value = 35.4567;
    
/* get current currency formatter */
    
NumberFormat currency = NumberFormat.getCurrencyInstance();        

/* format to currency */
    
System.out.println( currency.format( value ) );
Output:
35,46 Kč
With java.text.NumberFormat you can change currency or for example set minimal number of decimal places.
double value = 35.4567;
    
/* get current currency formatter */
    
NumberFormat currency = NumberFormat.getCurrencyInstance();        
    
/* set to UK currency */
    
currency.setCurrency( Currency.getInstance( Locale.UK ) );
currency.setMinimumFractionDigits( 3 );
    
/* format to currency */
    
System.out.println( currency.format( value ) );
Output:
35,457 GBP

Friday, December 8, 2017

JAVA - How read text file

Rows are retrived row by row from text file with helping of java.io.BufferedReaded class.
import java.io.*;
...
/* -- check if file exists */

File file = new File( "c:\\test2.txt" );

if ( ! file.exists() ) {
  return;
}

/* -- read data by rows */

try {
  BufferedReader in = new BufferedReader( new FileReader( file ) );

  try {
    String s;
    while ( ( s = in.readLine() ) != null ) {

      /* -- action with row */

      System.out.println( s );
    }
  } finally {

    /* -- close reader */
 
    in.close();
  }
} catch ( IOException e ) {}
Output could be:
50
51,9940881520819
53,9831973101194
55,9623857448431
57,92678579208
59,8716397322638
...

JAVA - How to get device MAC address

For getting MAC address of the device use this code:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.net.SocketException;
...
try {
  InetAddress ia = InetAddress.getLocalHost();

  NetworkInterface ni = NetworkInterface.getByInetAddress( ia );

  /* -- write results */

  System.out.println( ni.getName() );
  System.out.println( ni.getDisplayName() );

  byte[] mac = ni.getHardwareAddress();

  for ( int i = 0; i < mac.length; i++ )
    System.out.format( "%02X%s",  mac[i], ( i < mac.length - 1 ) ? "-" : "" );

  } 
  catch ( UnknownHostException ex ) {} 
  catch ( SocketException ex ) {}
...
Output:
Realtek PCIe GBE Family Controller - Packet Scheduler Miniport
eth2
70-71-BC-54-E7-8B

JAVA - How to split String to parts

For split String use function java.lang.String.Split(). The parameter is mask for splitting, you can use here advanced regular expressions too.
/* -- split by spaces */

String s = "This is some text";

String[] array = s.split( " " );

System.out.println( s + " -> " + Arrays.toString( array ) );

/* -- split by " is" text */

String[] array1 = s.split( " is" );

System.out.println( s + " -> " + Arrays.toString( array1 ) );

/* -- split by all spaces of any length */

String s2 = "This is some     text";

String[] array2 = s2.split( "\\s+" );

System.out.println( s2 + " -> " + Arrays.toString( array2 ) );

/* -- split groups in () */

String s3 = "(123)(A)(ABDC)";

String[] array3 = s3.split( "[()]" );

System.out.println( s3 + " -> " + Arrays.toString( array3 ) );
Output:
This is some text -> [This, is, some, text]
This is some text -> [This,  some text]
This is some     text -> [This, is, some, text]
(123)(A)(ABDC) -> [, 123, , A, , ABDC]

SQL SERVER - How create table with referential integrity (foreign key)

Field LOGS.USER_IDENT is linked to primary key of table USERS. So, in this field are enabled only values from USERS.IDENT. When is USERS.IDENT changed, cascade rule change its value in LOGS table too.
create table [logs]
( 
  id int not null primary key identity,
  [date] datetime default getdate(),
  ...
  [user_ident] [dbo].[USER]    
    foreign key references [users]( ident )     
    on update cascade
);
Table USERS:
create table [users]
( 
  ident [dbo].[USER] not null primary key,
  [name] [dbo].[USER_NAME],
  [active] bit not null default 1
...
);

DELPHI - How enumerate all directories

Use faDirectory setting in FindFirst():
var
  recSearch : TSearchRec;
  sUNC : string;
...
begin
  { get unc path to base directory }

  sUnc := DB.QSetup_Globalupdate_unc.AsString;

  { enumerate only directories }

  i := FindFirst( sUNC + '*.*' , faDirectory, recSearch );
  while i = 0 do
    begin
      if recSearch.name[1] <> '.' then
        begin
          try
            { do something; } 
          except
          end;
        end;

      { try find next }
      i := FindNext( recSearch );
    end;
  FindClose( recSearch );
...
end;

Thursday, December 7, 2017

JAVA - How check if file exists

import java.io.*;
...
if ( new File( "c:\\test.txt" ).exists() ) System.out.print( "File exists" );

SSRS - How add current timezone name to report

=Globals!ExecutionTime + “ (” + TimeZone.CurrentTimeZone.StandardName + “)”



DELPHI - How enumerate all files in directory

This example enumerate all *.png files in directory (..and get its system date info).
var
  sr : TSearchRec;
  tim : TSystemTime;
  dDate : TDate;
  sMask : string;
begin
  ..
  { mask for .png files only }
  sMask := gcsDrawingDirectory + sFocusedValue + '*' + '.png';

  { find first file, to sr }
  i := FindFirst( sMask , faAnyFile, sr );
  while i = 0 do
    begin
      try
        { here is some action with file -> here get file time }       
 
        FileTimeToSystemTime( FileTime( sr.FindData.ftLastWriteTime) , tim );
        dDate := EncodeDate( tim.wYear, tim.wMonth, tim.wDay );

        { do some action..}

      except
      end;

  { try find next file }  
  i := FindNext( sr );
end;
{ close finding }
FindClose( sr );

SQL SERVER - How create table with constraint on column

This example shows creating table with constraint on column [type]. Allowed values are "I", "E" and "W" (..and null, column is not mandatory).
create table [logs]
( 
  id int not null primary key identity,
  [date] datetime default getdate(),
  /* I=info; E=error, W=warning */
  [type] varchar(1) check ( [type] in ( 'I', 'E', 'W' ) ),
  [description] nvarchar( 1024 ),
  [data_group] varchar( 10 )
)

Wednesday, December 6, 2017

JAVA - How convent number to string

int to String

int i = 10;
String s = Integer.toString( i );

System.out.println( s );  // write result to Output window
Output:
10

long to String

long l = 456;
s = Long.toString( l );

System.out.println( s );  // write result to Output window
Output:
456

double to String

double d = 5.51;
s = Double.toString( d );

System.out.println( s );  // write result to Output window
Output:
5.51

float to String

float f = 15.55f;
s = Float.toString( f );

System.out.println( s );  // write result to Output window
The output is:
15.55

AX - How change Grid cells colors (conditional formatting)

When you need to change grid cells color you must override form DataSource displayOption() method.


This method has two parameters:
  • First is record for every row in grid.
  • Second is used for color change.
Here is applied change only for grid`s column ProductivityPercent.
public void displayOption(Common _record, FormRowDisplayOption _options)
{

    DM_ProductivityTable dm_productivityTable;
    real iPercent;

    /* record for every row (currently drawn row), get percent from it */

    dm_productivityTable = _record;

    iPercent = dm_productivityTable.ProductivityPercent;

    /* conditions */

    if ( ( iPercent > 0 ) && ( iPercent < 75 ) ) {
        _options.backColor( WinAPI::RGB2int( 153, 31, 0 ) );
        _options.textColor( WinAPI::RGB2int( 255, 255, 255 ) ) ;
        _options.affectedElementsByControl( DM_ProductivityTable_ProductivityPercent.id() );
    }
    if ( ( iPercent >= 75 ) && ( iPercent < 100 ) ) {
        _options.backColor( WinAPI::RGB2int( 255, 92, 51 ) );
        _options.textColor( WinAPI::RGB2int( 255, 255, 255 ) ) ;
        _options.affectedElementsByControl( DM_ProductivityTable_ProductivityPercent.id() );
    }
    if ( ( iPercent >= 100 ) && ( iPercent < 120 ) ) {
        _options.backColor( WinAPI::RGB2int( 0, 230, 0 ) );
        //_options.textColor( WinAPI::RGB2int( 255, 255, 255 ) ) ;
        _options.affectedElementsByControl( DM_ProductivityTable_ProductivityPercent.id() );
    }
    if ( iPercent >= 120 ) {
        _options.backColor( WinAPI::RGB2int( 0, 128, 0 ) );
        _options.textColor( WinAPI::RGB2int( 255, 255, 255 ) ) ;
        _options.affectedElementsByControl( DM_ProductivityTable_ProductivityPercent.id() );
    }

    /* call */

    super( _record, _options );
}
PS: ..and set Grid.HighlightActive => No.

SQL SERVER - How drop table (with table exists check)

This example shows script for drop table with check if this table exists in DB.
use db;

set nocount on;

if exists( select 'x' from information_schema.tables 
           where
           lower( table_name ) = 'sql_detail_methods'            
         )
begin
  drop table [sql_detail_methods];
end;

SQL SERVER - How create new type (with type exists check)

Sometimes is better make new type. Later you can use it, for example for new column in table, or in stored procedure. Here is created type for nvarchar(25).
use db;
...
if not exists
  ( select 'x' from sys.systypes
    where
    lower( name ) = 'user'
  )
begin
  create type [dbo].[USER] from nvarchar(25);
end;
And using it in create table statement:
create table [users]
( 
  ident [dbo].[USER] not null primary key,
  [name] [dbo].[USER_NAME],
  [active] bit not null default 1
);

Tuesday, December 5, 2017

JAVA - How to use TreeMap

java.util.TreeMap is map with this behavior:
  • Keys can`t be duplicated.
  • Elements are sorted by keys.
TreeMap tr = new TreeMap();

/* -- add keys and it values */
    
tr.put( "one", 1 );
tr.put( "two", 2 );
tr.put( "three", 3 );
tr.put( "three", 5 ); // exists already -> ignore
tr.put( "three", 3 ); // exists already -> ignore
tr.put( "four", null ); 

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

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

/* get value for key */
System.out.println( "\"one\" value = " + tr.get( "two" ) );   
    
/* -- write all keys and all values */
        
System.out.println( "Keys = " + new ArrayList( tr.keySet() ).toString() );  
System.out.println( "Values = " + new ArrayList( tr.values() ).toString() );
Output:
Elements count = 4
Contains "one" = true
"one" value = 2
Keys = [four, one, three, two]
Values = [null, 1, 3, 2]
See that the order of elements are by the key name. Also count of elements is 4 - two items were omitted.

JAVAFX - How convent numeric to string with locale rules

This example convent double value to String with locale rules (first US, second French, third English):
@FXML TextArea memo;

private void btnActionOnAction(ActionEvent event) {
  double iValue = 1234567.2345;
  String sText;
    
  sText = "US = " + 
    NumberFormat.getNumberInstance( Locale.US ).format( iValue ) + "\n";
  sText += "French = " + 
    NumberFormat.getNumberInstance( Locale.FRENCH ).format( iValue ) + "\n";         
  sText += "English = " + 
    NumberFormat.getNumberInstance( Locale.ENGLISH ).format( iValue ) + "\n";         
    
  memo.setText( sText );    
}
How you can see, US adds thousand separator:
US = 1,234,567.235
French = 1 234 567,235
English = 1,234,567.235

AX - How find sales (purchase) price for item

On Released products in AX 2012 you can define Sales price:













So here is code for its reading:
InventTable inventTable = InventTable::find( '5801-105-535-ND_0_0000' );
PriceDisc priceDisc;
PriceCur iPrice;

if ( inventTable ) {

  /* -- find sales price for item, dimension, unit, date and company */
                
  priceDisc = new PriceDisc( ModuleInventPurchSales::Sales, inventTable.ItemId, null, 'ks', 
                             systemdateget(), 1, 'COMPANY_AG' );

  if ( priceDisc.findPrice( CustTable::find( 'COMPANY_AG' ).PriceGroup ) )
    iPrice = priceDisc.price();
  /*else if ( priceDisc.findItemPrice() )
    iPrice = priceDisc.price();*/           

  info( "Sales price: " + num2str( iPrice, 15, 2, 1, 0 ) );                            
}
Output could be:
Sales price: 20.50

JAVAFX - How show new modal dialog

@FXML
private void btnAboutAction( ActionEvent event ) throws Exception {
 
  /* read form from .fxml */

  FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "FAbout.fxml" ) );

  /* get form */

  Parent form = (Parent) fxmlLoader.load();

  /* set dialog properties */

  Stage stage = new Stage();
  stage.initModality( Modality.APPLICATION_MODAL );
  stage.setResizable( false );
  stage.setTitle( "About" );  

  /* show it in screen center */

  stage.setScene( new Scene( form ) );  
  stage.centerOnScreen();
  stage.show();
}

Monday, December 4, 2017

AX - How get item cost (std) price

For getting cost price use class InventItemPrice. Second parameter is date for cost price,
then are two parameters for dimension. Last parameter tells if throw error, if cost price will not be found.
InventTable inventTable = InventTable::find( '55555-555555_555' );
InventItemPrice inventItemPrice;

if ( inventTable ) {

  /* -- get price for selected date */
        
  inventItemPrice = InventItemPrice::stdCostFindDate( 
                      inventTable, /*systemDateGet()*/
                      mkDate( 31, 1, 2017 ), 
                      '', null, 'COMPANY', false 
                    );

  info( "Price: " + num2str( inventItemPrice.Price(), 15, 2, 1, 0 ) );                            
}
Output could be:
Price: 11879.30

AX - How check if file exists + YesNo dialog

Link for external WIN API function.
FilenameSave filename;
...
if ( WinAPI::fileExists( filename ) )
  if ( ! Box::yesNo( strfmt( "@SYS60148", filename ), DialogButton::No ) )
  {
    info( "Export cancelled." );
    return false;
  }

ORACLE - How remove time part from datetime

Use trunc() function:
delete orders a
where
( select date_ from menu b
  where
  b.id = a.menu_id 
) <= trunc( to_date( '01.01.2017' ) )

AX - How find active BOM version and list its items

Base example shows how to get BOM active version to data, with fromQty=1, no configuration.
InventTable inventTable = InventTable::find( '5801-382-066_0_0200' );
BOMVersion bomVersion;
BOM bom;
    
if ( inventTable ) {
        
  /* -- get active BOM version to date, with fromQty=1, no config */
        
  bomVersion = BomVersion::findActive( inventTable.ItemId, systemdateGet(), 1, null );
        
  if ( bomVersion ) {
            
    /* -- list items and quantity */
            
    while 
    select bom 
    where bom.BOMId == bomVersion.BOMId 
    {            
      info( bom.ItemId + ", " + num2str( bom.BOMQty(), 15, 2, 1, 0 ) + " " + bom.UnitId );
    }
  }

}
Ouput could be:
5801-380-510_0_0000,       1.00 KS
5801-361-927-1_0_0000,     2.00 ks
S-442-900-2347,            1.00 KS
...

AX - How get info about AX user

When you need info about connected user, you can use class UserInfo and xUserInfo:
UserInfo userInfo = xUserInfo::find( false, curUserId() );
    
if ( userInfo ) {
  info( "Name: " + userInfo.name );        
  info( "Language: " + userInfo.language );
  info( "Enabled: " + ( userInfo.enable ? "Yes" : "No" ) );
}
Output:
Name: Aldiss, Brian
Language: en-us
Enabled: Yes
Note: For current user you can use directly:
UserInfo userInfo = xUserInfo::find();

AX - How get info about licence

X++ contains class xSysConfig for providing information about licence. Below code shows info with AX serial number and licence holder.
info( "Licence number: " + xSysConfig::serialnumber() );    
info( "Licence holder: " + xSysConfig::licenseHolder() );    
Output could be:
Licence number: M1218154
Licence holder: Company AG