Monday, June 21, 2021

AX - How to disable AOS validation for table update

ValidateWrite() causes in this case dialog, this is how to disable its calling.
AssetTable assetTable;
    
new SkipAOSValidationPermission().assert();
    
ttsBegin;
       
while
  select forUpdate * from assetTable
  where
  ( assetTable.AssetId == "13487" ) || (  assetTable.AssetId == "13488" )
  {        
         
    assetTable.AcquisitionDate_W = str2Date( "1/6/2021", 123 );
    assetTable.update();        
            
  }

ttsCommit;
  
CodeAccessPermission::revertAssert();

Friday, June 18, 2021

DELPHI - How to open file in Windows Explorer (default opening)

Shellapi unit.
ShellExecute( Handle,
              'OPEN',
              PChar('explorer.exe'),
              PChar('/select, "' + path + '"'),
              nil,
              SW_NORMAL
             ) ;

Thursday, May 27, 2021

C# - How parse double from string with specific char for decimal delimiter

If in your culture is used comma char (",") as decimal delimiter, it could appears problem, when double stored in string is delimited with classic decimal point ("."). 

 In this situation you must specify that decimal point as used delimiter. 

 So, if you have this string value "135.009995"; for right parsing you must define this code:
var currentCulture = System.Globalization.CultureInfo.InstalledUICulture;
var numberFormat = (System.Globalization.NumberFormatInfo) currentCulture.NumberFormat.Clone(); 
numberFormat.NumberDecimalSeparator = ".";

double value = 0;
bool b = Double.TryParse ( values[1], System.Globalization.NumberStyles.Any, 
                           numberFormat, out value ); 
if ( b ) el.Open = value;
Now, value contains good double value:

Wednesday, March 17, 2021

C# - How to draw image with Gamma or Threshold effect

var rectDest = new Rectangle( 0, 0, this.m_bitmap_source.Width, this.m_bitmap_source.Height );
using ( var graphics = Graphics.FromImage( this.m_bitmap_dest ) ) using ( var attr = new ImageAttributes() ) { attr.SetGamma( 0.2f ); graphics.DrawImage( this.m_bitmap_source, rectDest, 0, 0, this.m_bitmap_source.Width, this.m_bitmap_source.Height, GraphicsUnit.Pixel, attr ); }
You can use Threshold effect too (replace row with Gamma):
attr.SetThreshold( 0.4f );

Friday, March 5, 2021

C# - How to initialize List items in new statement

One possibility:
image.Normalize( new List() { new Rectangle( 100, 100, 300, 100 ) }  );
Another possibility with setting accessible properties by name:
image.Normalize( new List()
{ 
  new Rectangle() { X=100, Y=100, Width=300, Height=100 }, 
  new Rectangle() { X=200, Y=250, Width=200, Height=50 }
}  
);

Monday, March 1, 2021

C# - How to check installed .NET SDK

With this command tool dotnet.exe you can list for example installed .NET SDK.
Tip: If you want make .NET 5 app, create .NET CORE x project and then you can change it into .NET 5 (Feb 2021).

Friday, January 29, 2021

office (vba) - How to load data from text file into excel

If you have this text file with two columns, first with key, second with value:
osc;value
476;56
113;102
272;32.5
This VBA macro code enables to load data, check key comparing with first A column, if key is equal (exactly, if starts with key), then fill value into column R.
Sub Import()
  
  Dim file As String
  Dim counter As Integer
  Dim arr() As String
  Dim key As String
  Dim rngFound As Range
  Dim sheet As Worksheet
  Dim cell As Object
  
  file = Application.GetOpenFilename("Data files (*.txt),*.txt", Title:="Select file")
  
  If file = "False" Then Exit Sub
  
  ' Open file for reading
  
  Set sheet = ActiveSheet
  counter = 1
  
  Open file For Input As #1
  Do Until EOF(1)
    Line Input #1, textline
    
    ' Header - omit it
    If counter <> 1 Then
    
        arr = Split(textline, ";")
                
        ' Find row key value
        For Each cell In sheet.UsedRange.Rows
          
          key = sheet.Cells(cell.Row, "A").Value
                    
          If key <> "" Then
            If key Like arr(0) + "*" Then                
                
                sheet.Cells(cell.Row, "R") = arr(1)
                
            End If
          End If
                    
        Next cell
       
        ' MsgBox (arr(0) + "=" + arr(1))
    End If
        
    counter = counter + 1
  Loop
  Close #1
  
  MsgBox ("Hotovo")
  
End Sub
Output:

Tuesday, January 26, 2021

AX - How to set conditionally grid font type to bold

..on DataSource override displayOption() method:
public void displayOption(Common _record, FormRowDisplayOption _options)
{
    DM_ProductivityDuplicate dm_productivityDuplicate1;
    real iPercent;

    dm_productivityDuplicate1 = _record;

    if ( dm_productivityDuplicate1.cieb_duplicate == NoYes::Yes ) _options.fontBold( true );

    super( _record, _options );
}

Tuesday, December 22, 2020

AX - How to read name from product

InventTable inventTable;

inventTable = InventTable::find( InventQuarantineOrder.itemId );
if ( !inventTable ) return false;
...
sText += inventTable.productName( SystemParameters::getSystemLanguageId() );

Friday, December 18, 2020

C# - How to convert short array/list into byte array list

/* source with short values */
public List<short> Data = new List<short>();
...
short[] DataArray = Data.ToArray();
byte[] bufferBytes = new byte[ DataArray.Length * sizeof( short ) ];
Buffer.BlockCopy( DataArray, 0, bufferBytes, 0, bufferBytes.Length );
      
/* dest with byte values */      
Console.WriteLine( bufferBytes[0] + ", " + bufferBytes[1] );
If first short value in source list is 313, then first two values in bufferBytes after copy will be 57 (111001) a 1(1).

Friday, September 18, 2020

AX - How to sort datasource

Simple add into datasource Init() method this code:
public void init()
{
  super();    
           
  smmEncyclopediaItems_ds.query().dataSourceNo( 1 ).
    addSortField( fieldNum( smmEncyclopediaItems, ParentId ), SortOrder::Ascending );
  smmEncyclopediaItems_ds.query().dataSourceNo( 1 ).
    addSortField( fieldNum( smmEncyclopediaItems, order ), SortOrder::Ascending );
  smmEncyclopediaItems_ds.query().dataSourceNo( 1 ).
    addSortField( fieldNum( smmEncyclopediaItems, ItemName ), SortOrder::Ascending );        
}

Tuesday, August 25, 2020

C# - How to make question into active directory (AD, LDAP)

This example shows all Petr names contained in defined AD:
/* -- question */
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Comp Users,DC=EU,DC=company,DC=local");

/* -- define searcher */

DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=User)(objectClass=person)(givenname=*petr*))";
ds.Sort = new SortOption( "name", SortDirection.Ascending );
      
/* -- enumerate results */

SearchResultCollection results = ds.FindAll();
    
foreach ( SearchResult sr in results )
{
  string output = "";
  if ( sr.Properties["name"].Count > 0 ) 
  	output+= sr.Properties["name"][0].ToString();
  if ( sr.Properties["mail"].Count > 0 ) 
  	output+= " - " + sr.Properties["mail"][0].ToString();
  if ( sr.Properties["givenname"].Count > 0 ) 
  	output+= " - " + sr.Properties["givenname"][0].ToString();
  if ( sr.Properties["sn"].Count > 0 ) 
  	output+= " - " + sr.Properties["sn"][0].ToString();
  if ( sr.Properties["userPrincipalName"].Count > 0 ) 
  	output+= " - " + sr.Properties["userPrincipalName"][0].ToString();
  if ( sr.Properties["distinguishedName"].Count > 0 ) 
  	output+= " - " + sr.Properties["distinguishedName"][0].ToString();
        
  Console.WriteLine( output );
}
Output:
Bednaro, Petr - Petr.Bednar@company.com - Petr - Bednaro - bednarop@EU.company.local - 
CN=Bednaro\, Petr,OU=Czech Republic,OU=MKPE,OU=Comp Users,DC=EU,DC=company,DC=local

Cepka, Petr - Petr.Cepka@company.com - Petr - Cepka - cepkap@EU.company.local - 
CN=Cepka\, Petr,OU=Czech Republic,OU=BEIC,OU=Comp Users,DC=EU,DC=company,DC=local

Hartigo, Petr - Petr.Hartigo@company.com - Petr - Hartigo - hartigop@EU.company.local - 
CN=Hartigo\, Petr,OU=Czech Republic,OU=MKPE,OU=Comp Users,DC=EU,DC=company,DC=local
For DirectoryEntry is possible use Domain class:
DirectoryEntry de = domain.GetDirectoryEntry();      
If you want filter only for company BEIC, extent the filter in LDAP string:
DirectoryEntry de = new DirectoryEntry("LDAP://OU=BEIC,OU=Comp Users,DC=EU,DC=company,DC=local");

WIN OS - How to get important info about machine

systeminfo
Output:
For another information you can use command:
msinfo

Thursday, August 20, 2020

C# - How to get active domain name

Domain domain;
try {
  domain = Domain.GetCurrentDomain();
  Console.WriteLine( domain.Name );
}
catch ( ActiveDirectoryOperationException e ) {
  Console.WriteLine( "No domain" );
  return;
}
Output:
EU.company.local

Monday, July 13, 2020

C# - How to compute hash value for the file

using( var md5 = MD5.Create() )
using( var sha256 = SHA256.Create() )
{
  using ( FileStream stream = File.OpenRead( @"c:\_ax\3of9.ttf" ) )
  {          
    byte[] hashMD5 = md5.ComputeHash( stream );
    Console.WriteLine( BitConverter.ToString( hashMD5 ) );  

    byte[] hashSHA256 = sha256.ComputeHash( stream );
    Console.WriteLine( BitConverter.ToString( hashSHA256 ) );  
  }
}
Output:
DB-E9-C0-88-6B-BB-A1-84-5D-4C-D8-95-60-DD-91-4E
E3-B0-C4-42-98-FC-1C-14-9A-FB-F4-C8-99-6F-B9-24-27-AE-41-E4-64-9B-93-4C-A4-95-99-1B-78-52-B8-55

Tuesday, June 23, 2020

SQL SERVER - How to load data from text file to table ?

If I have this table:
column_name     datatype   length
--------------- ---------- ------
id              varchar    7
description     nvarchar   60
last_index      int        NULL
..and this text file (first three rows only here):
-94544;ovládání;74
-00000;přídavné podstavce;15
-01881;hřídel, nástavec-spojovací(keiper);145
For import file data to this table use this statement:
delete dbo.drawing_index;

bulk insert dbo.drawing_index
from 'c:\cieb\import\drawing_index.txt'
with
(
	CODEPAGE = '65001',	-- UTF-8
	fieldterminator = ';',
	ROWTERMINATOR = '\n'
)
Output:

Tuesday, June 2, 2020

C# - How to hide TabPage ?

TabPage.Hide() doesn`t work correctly. But you can use this trick:
TabCommon.Parent = null;
TabLabels.Parent = null;
Output:

Wednesday, May 6, 2020

C# - How get Max() on FindAll() - LINQ

This example finds between MapAreas items max(Page) - but only in same Row as mapArea.Row.
int page = this.MapAreas.FindAll( area => area.Row == mapArea.Row ).Max( x => x.Page );

Thursday, April 2, 2020

SQL SERVER - How to align string length to fixed size

With left() function is problem because ending spaces are lost. The solution is little trick with space() function.
select top 1 left( itemid, 25 ) + 'x' from inventitemprice
where
itemid = 'S-144-700-1006'

select top 1 left( itemid + space(100), 25 ) + 'x' from inventitemprice
where
itemid = 'S-144-700-1006'
Output:
--------------------------
S-144-700-1006x

(1 row(s) affected)


--------------------------
S-144-700-1006           x

(1 row(s) affected)

Monday, March 9, 2020

C# - How call stored proc with output/return parameter ?

public static string GetStatistics() {
  string value = "";

  SqlCommand command = DB.SPPrepare( "GetStatisticsAsString" );
            
  command.Parameters.Add( new SqlParameter( "@catalog", "HYG" ) );
  command.Parameters.Add( new SqlParameter( "@catalogDSO", "MYDSO" ) );
  SqlParameter par = new SqlParameter( "@output", System.Data.SqlDbType.NVarChar, 2048 );
  par.Direction = System.Data.ParameterDirection.Output;
  command.Parameters.Add( par );

  command.ExecuteNonQuery();

  value = (string)command.Parameters[ "@output" ].Value;

  return value;
}

Monday, March 2, 2020

C# - How to use generic Min(), Max()

shape.Saved_Width =
 Math.Abs( shape.Points.Max( item => item.Draw_X )-shape.Points.Min( item => item.Draw_X ) );

Friday, February 28, 2020

WIN OS - How to flush your machine DNS cache ?

ipconfig /flushdns

AX - How to make sorting in grid column

Override datasource Init() method:
public void init()
{
    super();

    this.query().dataSourceNo( 1 ).addSortField( fieldNum( CIEB_Torque, cieb_datetime ), 
      SortOrder::Ascending );
}
Output: