Tuesday, December 26, 2017

JAVA - How to serialize object instance into file stream

You can serialize object instance data into stream - in this scenario into file stream. It means, save object instance into file for later reloading.

STEP 1
First you must prepare class for serialization. This class must implements java.io.Serializable interface.
import java.io.Serializable;

public class Person implements Serializable {
          
  public Person() {}
      
  String name;
  int age;  
}
STEP 2
For serialization to file stream use this code:
/* -- create and fill object instance */

Person person = new Person();

person.name = "Jack Howard";
person.age = 35;

/* -- serialiaze object instance  to stream */

try {

  /* -- serialize object instance to file */

  ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream( "c:\\test.str" ) );

  /* -- write */

  stream.writeObject( person );

  /* -- close stream */

  stream.close();

} catch (FileNotFoundException ex) {
} catch (IOException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
Above code created file c:\test.str.
STEP 3
When you need de-serialize data => load data from the stream and create again saved object instance(s), use this code:
try {

  /* -- create file stream for reading data */

  ObjectInputStream stream = new ObjectInputStream( new FileInputStream( "c:\\test.str" ) );

  /* -- read saved object instance */

  Person person = ( Person ) stream.readObject();

  /* -- write readed data */

  System.out.println( person.name );
  System.out.println( person.age );

  stream.close();

} catch ( IOException ex ) {
} catch ( ClassNotFoundException ex) {
  Logger.getLogger(Window.class.getName()).log( Level.SEVERE, null, ex );
}
Output:
Jack Howard
35

Saturday, December 23, 2017

JAVA - How to check if the instance is descendant of particular class

When you have more classes and its instances, you can check, if the object instance is descendant of the particular class - or if the instance directly is particular class. For this reason use java instanceof operator.

Suppose you have this classes,
public class Car {};
public class Nissan extends Car {};
and you create this two instances:
Car car = new Car();
Nissan nissan = new Nissan();
Now you can perform test, if the particular instance is descendant of the particular class:
/* check "car - Car" */

if ( car instanceof Car )
  System.out.println( "car instance of Car = true" );
else
  System.out.println( "car instance of Car  -> false" );

/* check "car - Nissan" */

if ( car instanceof Nissan )
  System.out.println( "car instance of Nissan -> true" );
else
  System.out.println( "car instance of Nissan -> false" );

/* check "nissan - Nissan" */

if ( nissan instanceof Nissan )
  System.out.println( "nissan instance of Nissan -> true" );
else
  System.out.println( "nissan instance of Nissan -> false" );
Output:
car instance of Car = true
car instance of Nissan -> false
nissan instance of Nissan -> true
-> car is not descendant of Nissan class.

JAVA - How disable instantiate of class

In some situation class works for example as storage for static methods. In this situation is useful to disable instantiating of class.

The trick is easy - only mark constructor of the class a private.
public class Person {

  private Person() {}

  String name;
}
The compiler shows this message (NetBeans):

Friday, December 22, 2017

JAVA - How check if character is number

if ( Character.isDigit( '5' ) ) System.out.println( "5 " + "is digit" );
  else System.out.println( "5 " + "is not digit" );

if ( Character.isDigit( 'x' ) ) System.out.println( "x " + "is digit" );
  else System.out.println( "x " + "is not digit" );
Output:
5 is digit
x is not digit

SQL SERVER - How encrypt/decrypt text with symmetric key

This is example using the easy symmetric TRIPLE DES cipher (128 bit).
First parameter both functions is key (must be same in both functions for good result).
select encryptByPassPhrase( 'abc', 'This is a text' ); 

select cast( decryptByPassPhrase( 'abc', 
cast( 0x0100000020125E55A80E96076336C470EA49C009E8F8C1675CDEEBFE663A01D217F19F8B as 
varbinary(100) ) ) as varchar(100) );
Output:
-------------------------------------------------------------------------------------
0x0100000020125E55A80E96076336C470EA49C009E8F8C1675CDEEBFE663A01D217F19F8B

(1 row(s) affected)

-------------------------------------------------------------------------------------
This is a text

(1 row(s) affected)

SQL SERVER - How insert image (.png) to table

Table has column IMAGE that is varbinary type:
create table app_images
( 
  ident varchar( 25 ) not null primary key,
  [size] int check ( [size] in ( 16, 32 ) ),
  [image] varbinary( max ) 
);
For inserting (.png) image to table use this code:
insert into app_images 
( ident, [size], [image] ) 
select 'tablet_32', '32', bulkcolumn 
from openrowset( bulk 'c:\db\images\tablet_32.png', single_blob ) as test

JAVA - How download document from web

This example is used for downloading rss channel:
try {    
  /* - open source */
      
  URL website = new URL( app.pSetup.getData().sRSSLink );
  InputStream in = website.openStream();      
  ...
}
catch( MalformedURLException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
  return false;
} 
catch( IOException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
  return false;
}

Thursday, December 21, 2017

ORACLE - How add new fields to existing table

alter table factory.erappo_new add 
( sSelect varchar2(1),
  sNewRecord varchar2(1),
  sState varchar2(1),
  iZeit_new number,
  iMeh_new number   
);

ORACLE - How get sessionid variable

Oracle sessionid identify user session - every user has own sessionid.
procedure delete_piece
is
  sID number;
begin
  sID := UserEnv( 'SESSIONID' );

  delete from piece
  where 
  sessionid = sID or 
  to_char( dat_net, 'YYYYMMDD' ) <> to_char( sysdate, 'YYYYMMDD' );

  commit;
end;

ORACLE - SELECT which returns only 1 row

This example returns only one (or no) row:
declare
  iPrice number;
begin
  ..
  select kost_soll_voll_mz into iPrice
  from erhtks
  where 
  tl_nr = pTl_nr and 
  tl_fam = pTl_fam and 
  tl_atn = pTl_atn and 
  koa_nr = pKoa_nr and 
  kal_auf_nr_ursp = pKal_auf_nr and 
  rownum = 1;

AX, X++ - How get time offset to UTC zone time

Example returns offset in hours to UTC time.
UtcDateTime dt_DateTime_Create;
int iUTCOffset;

dt_DateTime_Create = DateTimeUtil::getSystemDateTime();
    
iUTCOffset = DateTimeUtil::getTimeZoneOffset( dt_DateTime_Create, 
               Timezone::GMT_DUBLIN_EDINBURGH_LISBON_LONDON ) / 60;
info( int2str( iUTCOffset ) );
    
iUTCOffset = DateTimeUtil::getTimeZoneOffset( dt_DateTime_Create, 
               Timezone::GMTPLUS0100_AMSTERDAM_BERLIN_BERN_ROME ) / 60;
info( int2str( iUTCOffset ) );
    
iUTCOffset = DateTimeUtil::getTimeZoneOffset( dt_DateTime_Create, 
               Timezone::GMTPLUS0800PERTH ) / 60;
info( int2str( iUTCOffset ) );
Output (Prague, Berlin):
0
1
8

AX, X++ - How calculate difference with date types

Best for date difference calculation is intvNo() function. But exists another methods too.
static void zDate(Args _args)
{
  date d1 = mkDate( 15, 11, 2017 );
  date d2 = mkDate( 20, 12, 2017 );       
  int iDiffDays, iDiffMonths, iDiffYears;
  int64 iDiffSec;
  utcDateTime utcd1, utcd2;
    
  /* -- difference in days (date type) */
    
  iDiffDays = d2 - d1;
  info( "Days diff. = " + int2str( iDiffDays ) );
        
  /* -- difference in seconds (utcDateTime type */
    
  utcd1 = DateTimeUtil::newDateTime( d1, 0 );
  utcd2 = DateTimeUtil::newDateTime( d2, 0 );
  iDiffSec = DateTimeUtil::getDifference( utcd2, utcd1 );
  info( "Days diff. = " + int642str( iDiffSec ) );
   
  /* -- intvNo() */
    
  info( "" );
  iDiffDays = intvNo( d2, d1, intvScale::Day );
  info( "Days = " + int2str( iDiffDays ) );

  iDiffDays = intvNo( d2, d1, intvScale::MonthDay );
  info( "Days (total) = " + int2str( iDiffDays ) );
    
  iDiffMonths = intvNo( d2, d1, intvScale::Month );
  info( "Months = " + int2str( iDiffMonths ) );
    
  iDiffYears = intvNo( d2, d1, intvScale::Year );
  info( "Years = " + int2str( iDiffYears ) );   
}
Output:
Days diff. = 35
Days diff. = 3024000

Days = 5
Days (total) = 35
Months = 1
Years = 0
PS: Better way how make difference in days (3/2024):
iDiffDays = DateTimeUtil::date( sysDatabaseLog.createdDateTime ) - 
            DateTimeUtil::date( sysDatabaseLogInsert.createdDateTime );

Wednesday, December 20, 2017

SQL SERVER - How remove line feed char from text

Use replace() function:
select b.description
from inventTable a
left outer join ecoResProductTranslation b
on b.product = a.product
where
a.itemid = '153024_0_0000' and
b.languageid = 'cs'

select replace( b.description, char(10), ' ' ) as description
from inventTable a
left outer join ecoResProductTranslation b
on b.product = a.product
where
a.itemid = '153024_0_0000' and
b.languageid = 'cs'
Output:
description
----------------------------------------
153024
Date: 12.12.2016

(1 row(s) affected)

description
----------------------------------------
153024 Date: 12.12.2016

(1 row(s) affected)

DELPHI - How reconnect to another OS user - (AD account)

This example shows how to reconnect to other active directory user (with possibility to change domain).
var
  token : THandle;

  sApp_ReconnectUser_NewOSUser : string;
  sApp_ReconnectUser_NewOSDomain : string;
  sApp_ReconnectUser_NewOSPassword : string;
begin
  ...
  if not LogonUser( pchar( sApp_ReconnectUser_NewOSUser ), 
                    pchar( sApp_ReconnectUser_NewOSDomain ),
                    pchar( sApp_ReconnectUser_NewOSPassword ), 
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, 
                    token ) then RaiseLastOSError;
  if not ImpersonateLoggedOnUser( token ) then
    begin
      ShowMessage( 'Reconnect problem.' );
      Application.Terminate;
    end;
  ...

Tuesday, December 19, 2017

SQL SERVER - How to measure size of DB or table

Use this stored procedure:
use framework;
exec sp_spaceused;
Output:
database_name                         database_size      unallocated space
------------------------------------- ------------------ ------------------
framework                             7.50 MB            0.94 MB

reserved           data               index_size         unused
------------------ ------------------ ------------------ ------------------
5184 KB            2816 KB            1808 KB            560 KB
For question to concrete table add its name as parameter:
use framework;
exec sp_spaceused 'users';
Output:
name   rows        reserved           data               index_size         unused
------ ----------- ------------------ ------------------ ------------------ ------
users  40          16 KB              8 KB               8 KB               0 KB

JAVAFX - How close form (=stage)

Get Stage - for example from button and then close form.
@FXML Button btnClose;

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

DELPHI - How use TIdHTTP, TTrayIcon and hotkeys for TTrayIcon

This is code for camera which can be controlled by HTTP commands.
For HTTP commands are used object TIdHTTP. Application is minimized and has own tray icon.
Hotkeys are served by WM_HOTKEY message.
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdHTTP, IdTCPConnection,
  IdTCPClient, IdCmdTCPClient, IdBaseComponent, IdComponent, IdUDPBase,
  IdUDPClient, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    IdHTTP1: TIdHTTP;
    Button2: TButton;
    TrayIcon1: TTrayIcon;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure TrayIcon1DblClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    procedure WMHotkey( Var msg: TWMHotkey ) ; message WM_HOTKEY;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  { ..here you can see example of testing connection to idHTTP }
  
  IdHTTP1.Request.Clear;
  IdHTTP1.Request.BasicAuthentication:= true;
  IdHTTP1.Request.Authentication.Username := 'admin';
  IdHTTP1.Request.Authentication.Password := 'xxx'; }

  idHTTP1.Connect;
  idHTTP1.Get( 'http://10.36.1.29/command/presetposition.cgi?PresetCall=1,24' );
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  { -- hotkeys registration }

  RegisterHotkey( handle, 1, MOD_CONTROL, ord( '1' ) );
  RegisterHotkey( handle, 2, MOD_CONTROL, ord( '2' ) );
  RegisterHotkey( handle, 3, MOD_CONTROL, ord( '3' ) );
  RegisterHotkey( handle, 4, MOD_CONTROL, ord( '4' ) );
  RegisterHotkey( handle, 5, MOD_CONTROL, ord( '5' ) );
  RegisterHotkey( handle, 6, MOD_CONTROL, ord( '6' ) );
  RegisterHotkey( handle, 7, MOD_CONTROL, ord( '7' ) );
  RegisterHotkey( handle, 8, MOD_CONTROL, ord( '8' ) );
  RegisterHotkey( handle, 9, MOD_CONTROL, ord( '9' ) );

  { -- tray settings }

  TrayIcon1.Hint := 'Version 1.0 - click for close.';
  TrayIcon1.AnimateInterval := 200;

  { set up a hint balloon }
  TrayIcon1.BalloonTitle := 'CTRL + [1..9].';
  TrayIcon1.BalloonHint := 'Press for camera change';
  TrayIcon1.BalloonFlags := bfInfo;

  { initial calling for connection }
  idHTTP1.Get( 'http://10.36.1.29/command/presetposition.cgi?PresetCall=3,24' );

  { hide the window and set its state to wsMinimized. }
  Hide();
  WindowState := wsMinimized;

  { show animated tray icon and also a hint balloon. }
  TrayIcon1.Visible := True;
  TrayIcon1.Animate := True;
  TrayIcon1.ShowBalloonHint;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnRegisterHotkey( Handle, 1 );
  UnRegisterHotkey( Handle, 2 );
  UnRegisterHotkey( Handle, 3 );
  UnRegisterHotkey( Handle, 4 );
  UnRegisterHotkey( Handle, 5 );
  UnRegisterHotkey( Handle, 6 );
  UnRegisterHotkey( Handle, 7 );
  UnRegisterHotkey( Handle, 8 );
  UnRegisterHotkey( Handle, 9 );
end;

procedure TForm1.TrayIcon1DblClick(Sender: TObject);
begin
  close;
end;

procedure TForm1.WMHotkey( Var msg: TWMHotkey );
begin
  { reaction for hotkey }

  idHTTP1.Get( 'http://10.36.1.29/command/presetposition.cgi?PresetCall=' + 
               IntToStr( msg.HotKey ) + ',24' );
end;

end.

JAVAFX - How add support for CSS to your application

Three main ways:

1) For every Scene instance you can add support for css:
Scene scene = new Scene( root );
scene.getStylesheets().add( getClass().getResource( "style.css" ).toExternalForm() );

2) For every control item you can call setStyle() method:
button.setStyle( "-fx-effect: dropshadow( one-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 );");



3) In .fxml editor (scene builder) in menu Preview:

Monday, December 18, 2017

AX - Missing button "View details" on form

When on form is missing button "View details",



















the reason could be in IgnoreEDTRelation=Yes on table field. Set this property to value No.







Now is all OK, button is visible:



DELPHI - Yes/No dialog

Easy yes/no dialog:
if MessageDlg( 'Already delete ?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrNo then exit;
Output:

DELPHI - How show base info dialog

This is an easiest way how to show info dialog in Delphi:
ShowMessage( 'This is an info dialog.' );
Output:







Another variant is advanced version, where you can specify type, buttons and help context:
MessageDlg( 'This is an info dialog.', mtInformation, [ mbOk ], 0 );

Sunday, December 17, 2017

JAVAFX - How to use Platform.runLater()

@Override
public void initialize( URL url, ResourceBundle rb ) {
                    
  Platform.runLater( new Runnable() {
    @Override
    public void run() {
        
      prepare();                
 
    }   
  } );
    
}  

Friday, December 15, 2017

AX - errror by SSRS report run: "Error while setting server report parameters. Error message: Failed to load expression host assembly. Details: Could not load file or assembly 'InventTableOverviewReport.BusinessLogic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. (rsErrorLoadingExprHostAssembly)"

Solutions:

  • Not installed "AX reporting services extensions" on SQL side.
  • Try again re-deploy all SSRS reports.

AX - error "The AOS server name or instance name is not correctly configured" by installing Reporting Services Extensions

SSRS reporting services extension you must install on SQL side.

This error code is probably caused by missing WCF configuration.
  1. Run "Microsoft Dynamics AX 2012 configuration".
  2. For local and bussiness connection import right configuration and then press "Refresh configuration" button. This action refresh WCF configuration.
  3. Do it for SQL and AOS servers.

Thursday, December 14, 2017

DELPHI - How get default decimal separator

var
  DefaultLCID: LCID;
  sDefaultDecimalSeparator : string;
begin
  ...
  { read default decimal separator }
  DefaultLCID := GetThreadLocale;
  try
    sDefaultDecimalSeparator := trim( GetLocaleChar( DefaultLCID, LOCALE_SDECIMAL, '.' ) );
  except
    sDefaultDecimalSeparator := '.';
  end;

DELPHI - How change file extension

var
  sFileName : string;
begin
  ...
  sFileName := 'c:\temp\file.txt';
  ShowMessage( sFileName + #13 + changeFileExt( sFileName, '.exe' ) );
Output:

DELPHI - How set active printer to color/monochrome

When is parameter TRUE -> set active printer to color.
function SetPrinterColor( _b : boolean ) : boolean;
var
  buffer1 : array[0..250] of char;
  buffer2 : array[0..250] of char;
  buffer3 : array[0..250] of char;
  ADevice, ADriver, APort : pchar;
  hDm : THandle;
  pdm : PDEVMODE;
begin
  ADevice := buffer1;
  ADriver := buffer2;
  APort   := buffer3;

  { get active printer }

  Printer.GetPrinter( ADevice, ADriver, APort, hDm );

  { make change }

  Pdm := globalLock ( hDm );
  if _b then
    pdm^.dmColor := DMCOLOR_COLOR
  else
    pdm^.dmColor := DMCOLOR_MONOCHROME;
  globalUnlock(hDm);

  { set value }

  Printer.SetPrinter( ADevice, ADriver, APort, hDm );

  result := true;
end;

DELPHI - How get computer name

function My_GetComputerName : string;
var
  buffer : array[ 0..255 ] of char;
  i      : dword;
begin
  fillChar( buffer, sizeof( buffer ), #0 );
  i := sizeof( buffer );
  GetComputerName( @buffer, i );
  result := strPas( Buffer );
end;
When you call it:
ShowMessage( My_GetComputerName );
Output could be:

Wednesday, December 13, 2017

JAVAFX - How show base info dialog (Alert class)

Since java version 8u40 is available javafx.scene.control.Alert for easy info/warning/error dialog.

1) Base form:
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
...
Alert alert = new Alert( AlertType.INFORMATION, "This is alert." );
alert.showAndWait();










2) You can specify button (or more buttons):
alert = new Alert( AlertType.INFORMATION, "This is alert.\n\nSecond line.", 
                   new ButtonType( "Close it" ) );
alert.showAndWait();












3) Or you can specify dialog title and remove header text:
Alert alert = new Alert( AlertType.INFORMATION );
alert.setTitle( "Info" );
alert.setHeaderText( null );
alert.setContentText( "This is alert.\n\nSecond line." );
alert.showAndWait();


DELPHI - How get username of connected user

function My_GetUserName : string;
var
  buffer : array[ 0..255 ] of char;
  i      : dword;
begin
  fillChar( buffer, sizeof( buffer ), #0 );
  i := sizeof( buffer );
  getUserName( @buffer, i );
  result := strPas( buffer );
end;
When you call it:
ShowMessage( My_GetUserName );
Output could be:

ORACLE - How get name of connected DB instance

select sys_context( 'USERENV','DB_NAME' ) as instance from dual;
Output (for example):
INSTANCE                                                                        
--------------------------------------------------------------------------------
ORCL                                                                            
1 row selected.

SQL SERVER - How convert date/datetime to string

You can use convert() function with last parameter which tells how to convert.
select convert( varchar(10), getdate() ) union
select convert( varchar(10), getdate(), 101 ) union
select convert( varchar(10), getdate(), 102 ) union
select convert( nvarchar(10), getdate(), 103 ) union
select convert( varchar(10), getdate(), 104 ) union
select convert( nvarchar(10), getdate(), 105 ) 
Output:
----------
12/13/2017
13.12.2017
13/12/2017
13-12-2017
2017.12.13
Dec 13 201

(6 row(s) affected)

Tuesday, December 12, 2017

AX - How validate ComboBox value (validate() method)

With validate() method you can define check(s) for control on form (return FALSE when is something wrong).
When combobox is bound to Enun, use this form:
public boolean validate()
{
  boolean ret;

  ret = super();

  /* do check */
    
  if ( JmgFeedbackStatus.selection() == JmgFeedbackStatus::Completed ) {
    ret = false;
    warning( "@SYS316081" );
    //throw Global::error( "The parameter value is invalid." );
  }    

  return ret;
}
When combobox is bound to DataSource, you can add validate() directly to datasource field:
public boolean validate()
{
  boolean ret;

  ret = super();

  /* do check */
    
  if ( JmgTmpJobBundleProdFeedback.ReportAsFinished == JmgFeedbackStatus::Completed ) {
    ret = false;
    warning( "@SYS316081" );
    //throw Global::error( "The parameter value is invalid." );
  }  

  return ret;
}

ORACLE - How connect to DB

Typical form is: username/password@db_instance
connect scott/tiger@orcl
When is db_instance set in registry, you can use directly only username and password:
connect scott/tiger
When connection is OK:
SQLWKS> connect scoot/tiger@orcl
ORA-01017: invalid username/password; logon denied
SQLWKS> connect scott/tiger@orcl
Connected.

SQL SERVER - How get info about SQL server

When you need some base settings about SQL server, call sp_server_info stored procedure:
exec sp_server_info
Output:
attribute_id attribute_name attribute_value
1 DBMS_NAME Microsoft SQL Server
2 DBMS_VER Microsoft SQL Server 2014 - 12.0.5000.0
10 OWNER_TERM owner
11 TABLE_TERM table
12 MAX_OWNER_NAME_LENGTH 128
13 TABLE_LENGTH 128
14 MAX_QUAL_LENGTH 128
15 COLUMN_LENGTH 128
16 IDENTIFIER_CASE MIXED
17 TX_ISOLATION 2
18 COLLATION_SEQ charset=iso_1 sort_order=nocase_iso charset_num=1 sort_order_num=52
19 SAVEPOINT_SUPPORT Y
20 MULTI_RESULT_SETS Y
22 ACCESSIBLE_TABLES Y
100 USERID_LENGTH 128
101 QUALIFIER_TERM database
102 NAMED_TRANSACTIONS Y
103 SPROC_AS_LANGUAGE Y
104 ACCESSIBLE_SPROC Y
105 MAX_INDEX_COLS 16
106 RENAME_TABLE Y
107 RENAME_COLUMN Y
108 DROP_COLUMN Y
109 INCREASE_COLUMN_LENGTH Y
110 DDL_IN_TRANSACTION Y
111 DESCENDING_INDEXES Y
112 SP_RENAME Y
113 REMOTE_SPROC Y
500 SYS_SPROC_VERSION 12.00.5000

Monday, December 11, 2017

JAVAFX - How select file (FileChooser)

Typical open file dialog:
/* - select file */

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle( "Select image.." );
    
/* - get saved directory - or get user`s home dir */

File pDir = new File( app.pSetup.getData().sLastPath );
if ( ! ( pDir.exists() && pDir.isDirectory() ) ) {      
  pDir = new File( System.getProperty( "user.home" ) );      
}  
 fileChooser.setInitialDirectory( pDir );
    
/* - set filters */
    
fileChooser.getExtensionFilters().addAll(
  new FileChooser.ExtensionFilter( "All Images", "*.*" ),
  new FileChooser.ExtensionFilter( "JPG", "*.jpg" ),
  new FileChooser.ExtensionFilter( "PNG", "*.png" ),
  new FileChooser.ExtensionFilter( "BMP", "*.bmp" )
);
    
/* - open dialog */
    
File pfile = fileChooser.showOpenDialog( scrollPane.getScene().getWindow() );

/* - draw image */
    
if ( pfile != null )
{      
      
  /* -- read image */
      
  Image image = new Image( pfile.toURI().toURL().toExternalForm() );
  ...
}
Output:

SQL SERVER - How get difference between dates (here in days)

Here is example difference between two dates in days (first parameter), but you can use for example hour or month, etc.
select salesid, linenum, itemid, qtyordered, createddatetime, confirmeddlv, 
datediff( day, createddatetime, confirmeddlv ) as diffdays 
from salesline
where
confirmeddlv > '2017/12/01' and
datediff( day, createddatetime, confirmeddlv )  <= 7
Output:
salesid              createddatetime         confirmeddlv            diffdays
-------------------- ----------------------- ----------------------- -----------
PO171475             2017-12-08 10:51:45.000 2017-12-10 00:00:00.000 2
PO171475             2017-12-08 10:52:03.000 2017-12-10 00:00:00.000 2
PO171675             2017-11-27 19:58:26.000 2017-12-04 00:00:00.000 7
...

ORACLE - How make cursor and how go through its rows

With Oracle cursor you can read table data by SQL.
is
  /* person`s list */

  cursor c_persons is
    select a.id, a.email
    from factory.an_users a
    where
    nvl( a.active, 'N' ) = 'A'
    ;

  pc_persons c_persons%rowtype;

  sEmail varchar2( 4000 );
begin
  ...
  sEmail := '';
  
  /* open cursor */ 
  open c_persons;
  loop

    /* read every rows of the cursor */
    fetch c_persons into pc_persons;
    exit when c_persons%notfound;

    /* -- action with row data.. */
    if pc_persons.email is not null then
      sEmail := sEmail || pc_persons.email || ';';
    end if;
    
  end loop;
  close c_persons;
  ...
end;

SQL SERVER - How check if database exists

Use this script code:
use master;

/* -- define DB name */

declare @database_name nvarchar( max );  
set @database_name = 'framework'; 

/* -- check if DB exists yet */

if db_id( @database_name ) is not null
begin
  print 'DB exists.';
  /* db exists -> end */
  return;
end;
...

Sunday, December 10, 2017

DELPHI - How check if file exists

var
  sPath : string;
begin
  ...
  if not FileExists( sPath ) then
    begin
      MessageDlg( Format( 'File "%s" not found.', [sPath] ), mtError, [mbOk], 0 );
      exit;
    end;
  ...
end;

JAVAFX - How get Controller after form load

When you want to call some method on loaded form, you need at first controller:
public class App extends Application {
    
  @Override
  public void start( Stage stage ) throws Exception {
        
    /* load form FXMLMain */
    
    FXMLLoader fLoader = new FXMLLoader( getClass().getResource( "FXMLMain.fxml" ) );
    Parent root = fLoader.load();

    /* ..get its controller..and call some method */

    FXMLMain controller = fLoader.getController();
    controller.prepare( this );
    ...
  }

Saturday, December 9, 2017

JAVA - How to convert String to time

For conversion use SimpleDateFormat class where you can specify date mask.
import java.text.*;
...
/* - value for conversion */
    
String s = "13:52:10";
    
/* - specify format mask */
   
DateFormat df = new SimpleDateFormat( "H:m:s" );
    
try {
  /* - try to convert */
      
  Date d = df.parse( s );              
      
  /* - print result */
      
  System.out.println( df.format( d ) );

  /* - print time hour part (in 24-format) */

  Calendar c = df.getCalendar();
  c.setTime( d );

  System.out.println( c.get( Calendar.HOUR_OF_DAY ) );
} 
catch ( ParseException ex ) {}
Output:
13:52:10
13

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 );
}

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

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)